blob: e7d2a11e7b3f8b6f8cdf2bc34372b5e24944aed1 [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>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080041#include <gui/Surface.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000042#include <gui/TraceUtils.h>
Alec Mourie60041e2019-06-14 18:59:51 -070043#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070044#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080045#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070046#include <stdint.h>
47#include <stdlib.h>
48#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000049#include <system/graphics-base-v1.0.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080050#include <ui/DebugUtils.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000051#include <ui/FloatRect.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080052#include <ui/GraphicBuffer.h>
Sally Qif6918d42023-08-07 15:28:30 -070053#include <ui/HdrRenderTypeUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080054#include <ui/PixelFormat.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000055#include <ui/Rect.h>
56#include <ui/Transform.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#include <utils/Errors.h>
58#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080059#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080061#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Alec Mourie60041e2019-06-14 18:59:51 -070063#include <algorithm>
64#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070065#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070066#include <sstream>
67
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070068#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080069#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070070#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070071#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +000072#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000073#include "FrontEnd/LayerHandle.h"
Melody Hsue4ef87f2024-03-26 23:54:45 +000074#include "Layer.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080075#include "LayerProtoHelper.h"
Josh Gao194ff392022-09-08 16:19:29 -070076#include "MutexUtils.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080078#include "TimeStats/TimeStats.h"
Melody Hsue4ef87f2024-03-26 23:54:45 +000079#include "TransactionCallbackInvoker.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070080#include "TunnelModeEnabledReporter.h"
Alec Mouri9892aac2023-12-11 21:16:59 +000081#include "Utils/FenceUtils.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070082
David Sodman41fdfc92017-11-06 16:09:56 -080083#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000084#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086namespace android {
Alec Mouri9892aac2023-12-11 21:16:59 +000087using namespace std::chrono_literals;
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010088namespace {
89constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000090
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000091const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000092
Patrick Williamsbb25f802022-08-30 23:02:34 +000093bool assignTransform(ui::Transform* dst, ui::Transform& from) {
94 if (*dst == from) {
95 return false;
96 }
97 *dst = from;
98 return true;
99}
100
101TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
102 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
103 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
104 const auto frameRateCompatibility = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700105 switch (frameRate.vote.type) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000106 case Layer::FrameRateCompatibility::Default:
107 return FrameRateCompatibility::Default;
108 case Layer::FrameRateCompatibility::ExactOrMultiple:
109 return FrameRateCompatibility::ExactOrMultiple;
110 default:
111 return FrameRateCompatibility::Undefined;
112 }
113 }();
114
115 const auto seamlessness = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700116 switch (frameRate.vote.seamlessness) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000117 case scheduler::Seamlessness::OnlySeamless:
118 return Seamlessness::ShouldBeSeamless;
119 case scheduler::Seamlessness::SeamedAndSeamless:
120 return Seamlessness::NotRequired;
121 default:
122 return Seamlessness::Undefined;
123 }
124 }();
125
Rachel Leece6e0042023-06-27 11:22:54 -0700126 return TimeStats::SetFrameRateVote{.frameRate = frameRate.vote.rate.getValue(),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000127 .frameRateCompatibility = frameRateCompatibility,
128 .seamlessness = seamlessness};
129}
130
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100131} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800132
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700133using namespace ftl::flag_operators;
134
Yiwei Zhang5434a782018-12-05 18:06:32 -0800135using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000136using frontend::LayerSnapshot;
137using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800138using gui::GameMode;
139using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500140using gui::WindowInfo;
Vishnu Nair494a2e42023-11-10 17:21:19 -0800141using ui::Size;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800142
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700143using PresentState = frametimeline::SurfaceFrame::PresentState;
144
Kean Mariotti4ba343c2023-04-19 13:31:02 +0000145Layer::Layer(const surfaceflinger::LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000146 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700147 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000148 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700149 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800150 mWindowType(static_cast<WindowInfo::Type>(
151 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000152 mLayerCreationFlags(args.flags),
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000153 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000154 ALOGV("Creating Layer %s", getDebugName());
155
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700156 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700157 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
158 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
159 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700160 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
161 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700162 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700163 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700164 mDrawingState.z = 0;
165 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700166 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700167 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700168 mDrawingState.transform.set(0, 0);
169 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +0000170 mDrawingState.previousFrameNumber = 0;
Vishnu Nair63221212023-04-06 15:17:37 -0700171 mDrawingState.barrierFrameNumber = 0;
172 mDrawingState.producerId = 0;
173 mDrawingState.barrierProducerId = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700174 mDrawingState.bufferTransform = 0;
175 mDrawingState.transformToDisplayInverse = false;
Robert Carr6a160312021-05-17 12:08:20 -0700176 mDrawingState.acquireFence = sp<Fence>::make(-1);
177 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
Alec Mouri74c7ae12023-03-26 02:57:47 +0000178 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Robert Carr6a160312021-05-17 12:08:20 -0700179 mDrawingState.hdrMetadata.validTypes = 0;
180 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
181 mDrawingState.cornerRadius = 0.0f;
182 mDrawingState.backgroundBlurRadius = 0;
183 mDrawingState.api = -1;
184 mDrawingState.hasColorTransform = false;
185 mDrawingState.colorSpaceAgnostic = false;
186 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
187 mDrawingState.metadata = args.metadata;
188 mDrawingState.shadowRadius = 0.f;
189 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
190 mDrawingState.frameTimelineInfo = {};
191 mDrawingState.postTime = -1;
192 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000193 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700194 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700195 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000196 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Rachel Lee70f7b692023-11-22 11:24:02 -0800197 mDrawingState.frameRateSelectionStrategy = FrameRateSelectionStrategy::Propagate;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700198
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700199 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
200 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700201 mDrawingState.color.r = -1.0_hf;
202 mDrawingState.color.g = -1.0_hf;
203 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700204 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700205
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500206 mFrameTracker.setDisplayRefreshPeriod(
207 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700208
Vishnu Naircb8be502022-10-12 19:03:23 +0000209 mOwnerUid = args.ownerUid;
210 mOwnerPid = args.ownerPid;
Tony Huangf3621102023-09-04 17:14:22 +0800211 mOwnerAppId = mOwnerUid % PER_USER_RANGE;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000212
213 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
214 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
215 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000216
217 mSnapshot->sequence = sequence;
218 mSnapshot->name = getDebugName();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000219 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000220 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800221}
222
223void Layer::onFirstRef() {
224 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700225}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700226
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700227Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000228 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
229 "Layer destructor called off the main thread.");
230
Patrick Williamsbb25f802022-08-30 23:02:34 +0000231 // The original layer and the clone layer share the same texture and buffer. Therefore, only
232 // one of the layers, in this case the original layer, needs to handle the deletion. The
233 // original layer and the clone should be removed at the same time so there shouldn't be any
234 // issue with the clone layer trying to use the texture.
235 if (mBufferInfo.mBuffer != nullptr) {
236 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
237 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800238 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000239 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000240 const int32_t layerId = getSequence();
241 mFlinger->mTimeStats->onDestroy(layerId);
242 mFlinger->mFrameTracer->onDestroy(layerId);
243
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000244 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700245 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700246
247 if (mDrawingState.sidebandStream != nullptr) {
248 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
249 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700250 if (mHadClonedChild) {
Vishnu Nair3be61902023-04-26 19:47:29 -0700251 auto& roots = mFlinger->mLayerMirrorRoots;
252 roots.erase(std::remove(roots.begin(), roots.end(), this), roots.end());
Robert Carr6a0382d2021-07-01 15:57:17 -0700253 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000254 if (hasTrustedPresentationListener()) {
255 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000256 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000257 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700258}
259
Mathias Agopian13127d82013-03-05 17:47:11 -0800260// ---------------------------------------------------------------------------
261// callbacks
262// ---------------------------------------------------------------------------
263
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700264void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700265 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700266 return;
267 }
Robert Carr2e102c92018-10-23 12:11:15 -0700268
Robert Carr6a160312021-05-17 12:08:20 -0700269 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700270 if (strongRelative == nullptr) {
271 setZOrderRelativeOf(nullptr);
272 return;
273 }
274
275 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700276 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700277 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800278 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700279 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700280}
281
282void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700283 if (!mRemovedFromDrawingState) {
284 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700285 mFlinger->mScheduler->deregisterLayer(this);
286 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000287 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000288
Ady Abrahamd11bade2022-08-01 16:18:03 -0700289 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700290}
Chia-I Wu38512252017-05-17 14:36:16 -0700291
chaviw68d4dab2020-06-08 15:07:32 -0700292sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000293 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700294 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700295 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700296 }
297 return parent->getRootLayer();
298}
299
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700300void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700301 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
302 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700303 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700304
Josh Gao194ff392022-09-08 16:19:29 -0700305 REQUIRE_MUTEX(mFlinger->mStateLock);
306 traverse(LayerVector::StateSet::Current,
307 [&](Layer* layer) REQUIRES(layer->mFlinger->mStateLock) {
308 layer->removeFromCurrentState();
309 layer->removeRelativeZ(layersInTree);
310 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700311}
312
chaviw61626f22018-11-15 16:26:27 -0800313void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700314 if (mRemovedFromDrawingState) {
315 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700316 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700317 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700318 }
chaviw61626f22018-11-15 16:26:27 -0800319
320 for (const auto& child : mCurrentChildren) {
321 child->addToCurrentState();
322 }
323}
324
Mathias Agopian13127d82013-03-05 17:47:11 -0800325// ---------------------------------------------------------------------------
326// set-up
327// ---------------------------------------------------------------------------
328
chaviw13fdc492017-06-27 12:40:18 -0700329bool Layer::getPremultipledAlpha() const {
330 return mPremultipliedAlpha;
331}
332
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700333sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800334 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700335 if (mGetHandleCalled) {
336 ALOGE("Get handle called twice" );
337 return nullptr;
338 }
339 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700340 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000341 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800342}
343
344// ---------------------------------------------------------------------------
345// h/w composer set-up
346// ---------------------------------------------------------------------------
347
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700348static Rect reduce(const Rect& win, const Region& exclude) {
349 if (CC_LIKELY(exclude.isEmpty())) {
350 return win;
351 }
352 if (exclude.isRect()) {
353 return win.reduce(exclude.getBounds());
354 }
355 return Region(win).subtract(exclude).getBounds();
356}
357
Dan Stoza80d61162017-12-20 15:57:52 -0800358static FloatRect reduce(const FloatRect& win, const Region& exclude) {
359 if (CC_LIKELY(exclude.isEmpty())) {
360 return win;
361 }
362 // Convert through Rect (by rounding) for lack of FloatRegion
363 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
364}
365
Vishnu Nair4351ad52019-02-11 14:13:02 -0800366Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800367 if (!reduceTransparentRegion) {
368 return Rect{mScreenBounds};
369 }
370
371 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800372 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800373 // Transform to screen space.
374 bounds = t.transform(bounds);
375 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700376}
377
Vishnu Nair4351ad52019-02-11 14:13:02 -0800378FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000379 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800380 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700381}
382
Vishnu Nairf0c28512019-02-08 12:40:28 -0800383FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
384 // Subtract the transparent region and snap to the bounds.
385 return reduce(mBounds, activeTransparentRegion);
386}
387
Chavi Weingarten076acac2023-01-19 17:20:43 +0000388// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000389void Layer::updateTrustedPresentationState(const DisplayDevice* display,
390 const frontend::LayerSnapshot* snapshot,
391 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000392 if (!hasTrustedPresentationListener()) {
393 return;
394 }
395 const bool lastState = mLastComputedTrustedPresentationState;
396 mLastComputedTrustedPresentationState = false;
397
398 if (!leaveState) {
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000399 const auto outputLayer = findOutputLayerForDisplay(display, snapshot->path);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000400 if (outputLayer != nullptr) {
401 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
402 Region coveredRegion =
403 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
404 mLastComputedTrustedPresentationState =
405 computeTrustedPresentationState(snapshot->geomLayerBounds,
406 snapshot->sourceBounds(), coveredRegion,
407 snapshot->transformedBounds,
408 snapshot->alpha,
409 snapshot->geomLayerTransform,
410 mTrustedPresentationThresholds);
411 } else {
412 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
413 "TrustedPresentationState",
414 getDebugName());
415 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000416 }
417 }
418 const bool newState = mLastComputedTrustedPresentationState;
419 if (lastState && !newState) {
420 // We were in the trusted presentation state, but now we left it,
421 // emit the callback if needed
422 if (mLastReportedTrustedPresentationState) {
423 mLastReportedTrustedPresentationState = false;
424 mTrustedPresentationListener.invoke(false);
425 }
426 // Reset the timer
427 mEnteredTrustedPresentationStateTime = -1;
428 } else if (!lastState && newState) {
429 // We were not in the trusted presentation state, but we entered it, begin the timer
430 // and make sure this gets called at least once more!
431 mEnteredTrustedPresentationStateTime = time_in_ms;
432 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
433 }
434
435 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
436 if (!mLastReportedTrustedPresentationState && newState &&
437 (time_in_ms - mEnteredTrustedPresentationStateTime >
438 mTrustedPresentationThresholds.stabilityRequirementMs)) {
439 mLastReportedTrustedPresentationState = true;
440 mTrustedPresentationListener.invoke(true);
441 }
442}
443
444/**
445 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
446 * of how the parameters and thresholds are interpreted. The general spirit is
447 * to produce an upper bound on the amount of the buffer which was presented.
448 */
449bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
450 const Region& coveredRegion,
451 const FloatRect& screenBounds, float alpha,
452 const ui::Transform& effectiveTransform,
453 const TrustedPresentationThresholds& thresholds) {
454 if (alpha < thresholds.minAlpha) {
455 return false;
456 }
457 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
458 return false;
459 }
460 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
461 return false;
462 }
463
464 const float sx = effectiveTransform.dsdx();
465 const float sy = effectiveTransform.dsdy();
466 float fractionRendered = std::min(sx * sy, 1.0f);
467
468 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
469 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
470 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
471
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000472 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
473 // Compute the size of all the rects since they may be disconnected.
474 float coveredSize = 0;
475 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
476 float size = rect->width() * rect->height();
477 coveredSize += size;
478 }
479
480 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000481
482 if (fractionRendered < thresholds.minFractionRendered) {
483 return false;
484 }
485
486 return true;
487}
488
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700489void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
490 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800491 const State& s(getDrawingState());
492
493 // Calculate effective layer transform
494 mEffectiveTransform = parentTransform * getActiveTransform(s);
495
Garfield Tan2c1782c2022-02-16 15:25:05 -0800496 if (CC_UNLIKELY(!isTransformValid())) {
497 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
498 getDebugName());
499 return;
500 }
501
Vishnu Nair4351ad52019-02-11 14:13:02 -0800502 // Transform parent bounds to layer space
503 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
504
Vishnu Nairc652ff82019-03-15 12:48:54 -0700505 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800506 mSourceBounds = computeSourceBounds(parentBounds);
507
508 // Calculate bounds by croping diplay frame with layer crop and parent bounds
509 FloatRect bounds = mSourceBounds;
510 const Rect layerCrop = getCrop(s);
511 if (!layerCrop.isEmpty()) {
512 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
513 }
514 bounds = bounds.intersect(parentBounds);
515
516 mBounds = bounds;
517 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700518
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700519 // Use the layer's own shadow radius if set. Otherwise get the radius from
520 // parent.
521 if (s.shadowRadius > 0.f) {
522 mEffectiveShadowRadius = s.shadowRadius;
523 } else {
524 mEffectiveShadowRadius = parentShadowRadius;
525 }
526
527 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
528 // don't pass it to its children.
529 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
530
Vishnu Nair4351ad52019-02-11 14:13:02 -0800531 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700532 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800533 }
Vishnu Nairba354102022-08-01 00:14:18 +0000534
535 if (mPotentialCursor) {
536 prepareCursorCompositionState();
537 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800538}
539
Vishnu Nair60356342018-11-13 13:00:45 -0800540Rect Layer::getCroppedBufferSize(const State& s) const {
541 Rect size = getBufferSize(s);
542 Rect crop = getCrop(s);
543 if (!crop.isEmpty() && size.isValid()) {
544 size.intersect(crop, &size);
545 } else if (!crop.isEmpty()) {
546 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700547 }
Vishnu Nair60356342018-11-13 13:00:45 -0800548 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800549}
550
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700551void Layer::setupRoundedCornersCropCoordinates(Rect win,
552 const FloatRect& roundedCornersCrop) const {
553 // Translate win by the rounded corners rect coordinates, to have all values in
554 // layer coordinate space.
555 win.left -= roundedCornersCrop.left;
556 win.right -= roundedCornersCrop.left;
557 win.top -= roundedCornersCrop.top;
558 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700559}
560
Lloyd Piquede196652020-01-22 17:29:58 -0800561void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800562 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800563 const auto alpha = static_cast<float>(getAlpha());
564 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700565 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800566
567 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
568 if (!opaque || alpha != 1.0f) {
569 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
570 : Hwc2::IComposerClient::BlendMode::COVERAGE;
571 }
572
Alec Mourif4af03e2023-02-11 00:25:24 +0000573 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000574 auto* snapshot = editLayerSnapshot();
575 snapshot->outputFilter = getOutputFilter();
576 snapshot->isVisible = isVisible();
577 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
Vishnu Naird9e4f462023-10-06 04:05:45 +0000578 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800579
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000580 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800581 contentDirty = false;
582
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000583 snapshot->geomLayerBounds = mBounds;
584 snapshot->geomLayerTransform = getTransform();
585 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
586 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000587 snapshot->localTransform = getActiveTransform(drawingState);
588 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000589 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
590 snapshot->alpha = alpha;
Vishnu Nairc6384702023-07-31 12:22:20 -0700591 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
592 snapshot->blurRegions = getBlurRegions();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000593 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800594}
595
Lloyd Piquede196652020-01-22 17:29:58 -0800596void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800597 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000598 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700599
Alec Mourif4af03e2023-02-11 00:25:24 +0000600 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000601 snapshot->geomBufferSize = getBufferSize(drawingState);
602 snapshot->geomContentCrop = getBufferCrop();
603 snapshot->geomCrop = getCrop(drawingState);
604 snapshot->geomBufferTransform = getBufferTransform();
605 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
606 snapshot->geomUsesSourceCrop = usesSourceCrop();
607 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800608
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000609 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800610 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
611 for (const auto& [key, mandatory] : supportedMetadata) {
612 const auto& genericLayerMetadataCompatibilityMap =
613 mFlinger->getGenericLayerMetadataKeyMap();
614 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
615 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
616 continue;
617 }
618 const uint32_t id = compatIter->second;
619
620 auto it = drawingState.metadata.mMap.find(id);
621 if (it == std::end(drawingState.metadata.mMap)) {
622 continue;
623 }
624
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000625 snapshot->metadata.emplace(key,
626 compositionengine::GenericLayerMetadataEntry{mandatory,
627 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800628 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800629}
David Sodmanba340492018-08-05 21:51:33 -0700630
Lloyd Piquede196652020-01-22 17:29:58 -0800631void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800632 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000633 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000634 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800635
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000636 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800637
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000638 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
639 snapshot->dataspace = getDataSpace();
640 snapshot->colorTransform = getColorTransform();
641 snapshot->colorTransformIsIdentity = !hasColorTransform();
642 snapshot->surfaceDamage = surfaceDamageRegion;
643 snapshot->hasProtectedContent = isProtected();
644 snapshot->dimmingEnabled = isDimmingEnabled();
Sally Qi963049b2023-03-23 14:06:21 -0700645 snapshot->currentHdrSdrRatio = getCurrentHdrSdrRatio();
646 snapshot->desiredHdrSdrRatio = getDesiredHdrSdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000647 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800648
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700649 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700650
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000651 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800652
653 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400654 // Rounded corners no longer force client composition, since we may use a
655 // hole punch so that the layer will appear to have rounded corners.
Alec Mouri994761f2023-08-04 21:50:55 +0000656 if (drawShadows() || snapshot->stretchEffect.hasEffect()) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000657 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800658 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700659 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairc6384702023-07-31 12:22:20 -0700660 snapshot->blurRegions = getBlurRegions();
661 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400662
663 // Layer framerate is used in caching decisions.
664 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
665 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000666 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000667
668 if (hasBufferOrSidebandStream()) {
669 preparePerFrameBufferCompositionState();
670 } else {
671 preparePerFrameEffectsCompositionState();
672 }
673}
674
675void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000676 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000677 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000678 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000679 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
680 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000681 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
682 return;
683 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000684 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000685 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800686 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
687 snapshot->compositionType =
688 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000689 } else {
690 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000691 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
692 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000693 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
694 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
695 }
696
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000697 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000698 snapshot->acquireFence = mBufferInfo.mFence;
699 snapshot->frameNumber = mBufferInfo.mFrameNumber;
700 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000701}
702
703void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000704 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000705 auto* snapshot = editLayerSnapshot();
706 snapshot->color = getColor();
707 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000708 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800709}
710
Lloyd Piquede196652020-01-22 17:29:58 -0800711void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800712 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000713 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000714 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800715
716 // Apply the layer's transform, followed by the display's global transform
717 // Here we're guaranteed that the layer's transform preserves rects
718 Rect win = getCroppedBufferSize(drawingState);
719 // Subtract the transparent region and snap to the bounds
720 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
721 Rect frame(getTransform().transform(bounds));
722
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000723 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800724}
725
Lloyd Piquea83776c2019-01-29 18:42:32 -0800726const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700727 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800728}
729
Mathias Agopian13127d82013-03-05 17:47:11 -0800730// ---------------------------------------------------------------------------
731// drawing...
732// ---------------------------------------------------------------------------
733
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500734aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
735 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700736 const auto outputLayer = findOutputLayerForDisplay(&display);
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000737 return getCompositionType(outputLayer);
738}
739
740aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
741 const compositionengine::OutputLayer* outputLayer) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -0800742 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500743 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800744 }
745 if (outputLayer->getState().hwc) {
746 return (*outputLayer->getState().hwc).hwcCompositionType;
747 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500748 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800749 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800750}
751
Mathias Agopian13127d82013-03-05 17:47:11 -0800752// ----------------------------------------------------------------------------
753// local state
754// ----------------------------------------------------------------------------
755
David Sodman41fdfc92017-11-06 16:09:56 -0800756bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800757 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700758 if (s.flags & layer_state_t::eLayerSecure) {
759 return true;
760 }
761
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000762 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700763 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700764}
765
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100766void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
767 std::vector<JankData>& jankData) {
768 if (mPendingJankClassifications.empty() ||
769 !mPendingJankClassifications.front()->getJankType()) {
770 return;
771 }
772
773 bool includeJankData = false;
774 for (const auto& handle : handles) {
775 for (const auto& cb : handle->callbackIds) {
776 if (cb.includeJankData) {
777 includeJankData = true;
778 break;
779 }
780 }
781
782 if (includeJankData) {
783 jankData.reserve(mPendingJankClassifications.size());
784 break;
785 }
786 }
787
788 while (!mPendingJankClassifications.empty() &&
789 mPendingJankClassifications.front()->getJankType()) {
790 if (includeJankData) {
791 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
792 mPendingJankClassifications.front();
Pascal Muetschardac7bcd92023-10-03 15:05:36 +0200793 jankData.emplace_back(JankData(surfaceFrame->getToken(),
794 surfaceFrame->getJankType().value(),
795 surfaceFrame->getRenderRate().getPeriodNsecs()));
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100796 }
797 mPendingJankClassifications.pop_front();
798 }
799}
800
Mathias Agopian13127d82013-03-05 17:47:11 -0800801// ----------------------------------------------------------------------------
802// transaction
803// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800804
Vishnu Naira156f482023-02-22 00:23:38 +0000805uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700806 ATRACE_CALL();
807
Robert Carr0758e5d2021-03-11 22:15:04 -0800808 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700809 mDrawingStateModified = mDrawingState.modified;
810 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700811
Alec Mourib416efd2018-09-06 21:01:59 +0000812 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700813
Robert Carr6a160312021-05-17 12:08:20 -0700814 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800815 // invalidate and recompute the visible regions if needed
816 flags |= Layer::eVisibleRegion;
817 }
818
Robert Carr6a160312021-05-17 12:08:20 -0700819 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800820 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000821 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800822 flags |= eVisibleRegion;
823 this->contentDirty = true;
824
825 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700826 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800827 }
828
Arthur Hung9ed43392022-05-27 06:31:57 +0000829 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
830 mFlinger->mUpdateInputInfo = true;
831 }
832
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700833 commitTransaction();
Robert Carra1257842020-01-31 13:48:28 -0800834
Mathias Agopian13127d82013-03-05 17:47:11 -0800835 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800836}
837
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700838void Layer::commitTransaction() {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000839 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
840 // bufferSurfaceFrameTX will be presented in latchBuffer.
841 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
842 if (surfaceFrame->getPresentState() != PresentState::Presented) {
843 // With applyPendingStates, we could end up having presented surfaceframes from previous
844 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800845 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000846 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
847 }
848 }
Robert Carr6a160312021-05-17 12:08:20 -0700849 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700850}
851
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700852uint32_t Layer::clearTransactionFlags(uint32_t mask) {
853 const auto flags = mTransactionFlags & mask;
854 mTransactionFlags &= ~mask;
855 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800856}
857
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700858void Layer::setTransactionFlags(uint32_t mask) {
859 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800860}
861
Robert Carr1f0a16a2016-10-24 16:27:39 -0700862bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
863 ssize_t idx = mCurrentChildren.indexOf(childLayer);
864 if (idx < 0) {
865 return false;
866 }
867 if (childLayer->setLayer(z)) {
868 mCurrentChildren.removeAt(idx);
869 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800870 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700871 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800872 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700873}
874
Robert Carr503c7042017-09-27 15:06:08 -0700875bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
876 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
877 ssize_t idx = mCurrentChildren.indexOf(childLayer);
878 if (idx < 0) {
879 return false;
880 }
881 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
882 mCurrentChildren.removeAt(idx);
883 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800884 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700885 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800886 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700887}
888
Robert Carrae060832016-11-28 10:51:00 -0800889bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700890 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
891 mDrawingState.sequence++;
892 mDrawingState.z = z;
893 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700894
Robert Carra70e91c2021-06-11 13:59:52 -0700895 mFlinger->mSomeChildrenChanged = true;
896
Robert Carrdb66e622017-04-10 16:55:57 -0700897 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700898 if (mDrawingState.zOrderRelativeOf != nullptr) {
899 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700900 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700901 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700902 }
chaviw606e5cf2019-03-01 10:12:10 -0800903 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700904 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800905 setTransactionFlags(eTransactionNeeded);
906 return true;
907}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700908
Robert Carrdb66e622017-04-10 16:55:57 -0700909void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700910 mDrawingState.zOrderRelatives.remove(relative);
911 mDrawingState.sequence++;
912 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700913 setTransactionFlags(eTransactionNeeded);
914}
915
916void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700917 mDrawingState.zOrderRelatives.add(relative);
918 mDrawingState.modified = true;
919 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700920 setTransactionFlags(eTransactionNeeded);
921}
922
chaviw606e5cf2019-03-01 10:12:10 -0800923void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700924 mDrawingState.zOrderRelativeOf = relativeOf;
925 mDrawingState.sequence++;
926 mDrawingState.modified = true;
927 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700928
chaviw606e5cf2019-03-01 10:12:10 -0800929 setTransactionFlags(eTransactionNeeded);
930}
931
Robert Carr503d2bd2017-12-04 15:49:47 -0800932bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000933 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700934 if (relative == nullptr) {
935 return false;
936 }
937
Robert Carr6a160312021-05-17 12:08:20 -0700938 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
939 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800940 return false;
941 }
942
Robert Carr88b85e12022-03-21 15:47:35 -0700943 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
944 (relative->mDrawingState.zOrderRelativeOf == this)) {
945 ALOGE("Detected relative layer loop between %s and %s",
946 mName.c_str(), relative->mName.c_str());
947 ALOGE("Ignoring new call to set relative layer");
948 return false;
949 }
950
Robert Carra70e91c2021-06-11 13:59:52 -0700951 mFlinger->mSomeChildrenChanged = true;
952
Robert Carr6a160312021-05-17 12:08:20 -0700953 mDrawingState.sequence++;
954 mDrawingState.modified = true;
955 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700956
Robert Carr6a160312021-05-17 12:08:20 -0700957 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700958 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700959 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700960 }
chaviw606e5cf2019-03-01 10:12:10 -0800961 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700962 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700963
964 setTransactionFlags(eTransactionNeeded);
965
966 return true;
967}
968
Winson Chunga30f7c92021-06-29 15:42:56 -0700969bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
970 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
971 mDrawingState.isTrustedOverlay = isTrustedOverlay;
972 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000973 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700974 setTransactionFlags(eTransactionNeeded);
975 return true;
976}
977
978bool Layer::isTrustedOverlay() const {
979 if (getDrawingState().isTrustedOverlay) {
980 return true;
981 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000982 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700983 return (p != nullptr) && p->isTrustedOverlay();
984}
985
Dan Stoza9e56aa02015-11-02 13:00:03 -0800986bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700987 if (mDrawingState.color.a == alpha) return false;
988 mDrawingState.sequence++;
989 mDrawingState.color.a = alpha;
990 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800991 setTransactionFlags(eTransactionNeeded);
992 return true;
993}
chaviw13fdc492017-06-27 12:40:18 -0700994
Valerie Haudd0b7572019-01-29 14:59:27 -0800995bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700996 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700997 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800998 }
Robert Carr6a160312021-05-17 12:08:20 -0700999 mDrawingState.sequence++;
1000 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -08001001 setTransactionFlags(eTransactionNeeded);
1002
Robert Carr6a160312021-05-17 12:08:20 -07001003 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001004 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001005 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001006 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001007 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Kean Mariotti4ba343c2023-04-19 13:31:02 +00001008 surfaceflinger::LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
1009 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001010
Valerie Haudd0b7572019-01-29 14:59:27 -08001011 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001012 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001013 mFlinger->mLayersAdded = true;
1014 // set up SF to handle added color layer
1015 if (isRemovedFromCurrentState()) {
Josh Gao194ff392022-09-08 16:19:29 -07001016 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001017 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001018 }
1019 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001020 } else if (mDrawingState.bgColorLayer && alpha == 0) {
Josh Gao194ff392022-09-08 16:19:29 -07001021 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001022 mDrawingState.bgColorLayer->reparent(nullptr);
1023 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001024 return true;
1025 }
1026
Robert Carr6a160312021-05-17 12:08:20 -07001027 mDrawingState.bgColorLayer->setColor(color);
1028 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1029 mDrawingState.bgColorLayer->setAlpha(alpha);
1030 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001031
chaviw13fdc492017-06-27 12:40:18 -07001032 return true;
1033}
1034
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001035bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001036 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001037
Robert Carr6a160312021-05-17 12:08:20 -07001038 mDrawingState.sequence++;
1039 mDrawingState.cornerRadius = cornerRadius;
1040 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001041 setTransactionFlags(eTransactionNeeded);
1042 return true;
1043}
1044
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001045bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001046 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001047 // If we start or stop drawing blur then the layer's visibility state may change so increment
1048 // the magic sequence number.
1049 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1050 mDrawingState.sequence++;
1051 }
Robert Carr6a160312021-05-17 12:08:20 -07001052 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1053 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001054 setTransactionFlags(eTransactionNeeded);
1055 return true;
1056}
Marissa Wall61c58622018-07-18 10:12:20 -07001057
Mathias Agopian13127d82013-03-05 17:47:11 -08001058bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001059 mDrawingState.sequence++;
1060 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001061 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001062 setTransactionFlags(eTransactionNeeded);
1063 return true;
1064}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001065
Lucas Dupinc3800b82020-10-02 16:24:48 -07001066bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001067 // If we start or stop drawing blur then the layer's visibility state may change so increment
1068 // the magic sequence number.
1069 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1070 mDrawingState.sequence++;
1071 }
Robert Carr6a160312021-05-17 12:08:20 -07001072 mDrawingState.blurRegions = blurRegions;
1073 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001074 setTransactionFlags(eTransactionNeeded);
1075 return true;
1076}
1077
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001078bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001079 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1080 if (mDrawingState.flags == newFlags) return false;
1081 mDrawingState.sequence++;
1082 mDrawingState.flags = newFlags;
1083 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001084 setTransactionFlags(eTransactionNeeded);
1085 return true;
1086}
Robert Carr99e27f02016-06-16 15:18:02 -07001087
chaviw25714502021-02-11 10:01:08 -08001088bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001089 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001090 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001091 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001092
Robert Carr6a160312021-05-17 12:08:20 -07001093 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001094 setTransactionFlags(eTransactionNeeded);
1095 return true;
1096}
Robert Carr8d5227b2017-03-16 15:41:03 -07001097
Evan Roskyef876c92019-01-25 17:46:06 -08001098bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001099 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1100 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001101 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001102 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001103}
1104
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001105bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001106 if (mDrawingState.layerStack == layerStack) return false;
1107 mDrawingState.sequence++;
1108 mDrawingState.layerStack = layerStack;
1109 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001110 setTransactionFlags(eTransactionNeeded);
1111 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001112}
1113
Peiyong Linc502cb72019-03-01 15:00:23 -08001114bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001115 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001116 return false;
1117 }
Robert Carr6a160312021-05-17 12:08:20 -07001118 mDrawingState.sequence++;
1119 mDrawingState.colorSpaceAgnostic = agnostic;
1120 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001121 setTransactionFlags(eTransactionNeeded);
1122 return true;
1123}
1124
Sally Qi81d95e62022-03-21 19:41:33 -07001125bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1126 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1127
1128 mDrawingState.sequence++;
1129 mDrawingState.dimmingEnabled = dimmingEnabled;
1130 mDrawingState.modified = true;
1131 setTransactionFlags(eTransactionNeeded);
1132 return true;
1133}
1134
Ana Krulecc84d09b2019-11-02 23:10:29 +01001135bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001136 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1137 mDrawingState.frameRateSelectionPriority = priority;
1138 mDrawingState.sequence++;
1139 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001140 setTransactionFlags(eTransactionNeeded);
1141 return true;
1142}
1143
1144int32_t Layer::getFrameRateSelectionPriority() const {
1145 // Check if layer has priority set.
1146 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1147 return mDrawingState.frameRateSelectionPriority;
1148 }
1149 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001150 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001151 if (parent != nullptr) {
1152 return parent->getFrameRateSelectionPriority();
1153 }
1154
1155 return Layer::PRIORITY_UNSET;
1156}
1157
Andy Labrada096227e2022-06-15 16:58:11 +00001158bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1159 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1160 mDrawingState.defaultFrameRateCompatibility = compatibility;
1161 mDrawingState.modified = true;
Vishnu Nair80e8cfe2023-09-29 17:03:45 -07001162 mFlinger->mScheduler->setDefaultFrameRateCompatibility(sequence, compatibility);
Andy Labrada096227e2022-06-15 16:58:11 +00001163 setTransactionFlags(eTransactionNeeded);
1164 return true;
1165}
1166
Vishnu Nair3fbe3262023-09-29 17:07:00 -07001167scheduler::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
Andy Labrada096227e2022-06-15 16:58:11 +00001168 return mDrawingState.defaultFrameRateCompatibility;
1169}
1170
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001171bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1172 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1173};
1174
Vishnu Nair73908d12022-10-24 21:46:42 -07001175ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1176 bool useDrawing = state == LayerVector::StateSet::Drawing;
1177 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1178 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001179 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001180 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001181 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001182}
1183
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001184bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001185 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001186 return false;
1187 }
1188
Robert Carr6a160312021-05-17 12:08:20 -07001189 mDrawingState.sequence++;
1190 mDrawingState.shadowRadius = shadowRadius;
1191 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001192 setTransactionFlags(eTransactionNeeded);
1193 return true;
1194}
1195
Vishnu Nair6213bd92020-05-08 17:42:25 -07001196bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001197 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001198 return false;
1199 }
1200
Robert Carr6a160312021-05-17 12:08:20 -07001201 mDrawingState.sequence++;
1202 mDrawingState.fixedTransformHint = fixedTransformHint;
1203 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001204 setTransactionFlags(eTransactionNeeded);
1205 return true;
1206}
1207
John Reckcdb4ed72021-02-04 13:39:33 -05001208bool Layer::setStretchEffect(const StretchEffect& effect) {
1209 StretchEffect temp = effect;
1210 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001211 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001212 return false;
1213 }
Robert Carr6a160312021-05-17 12:08:20 -07001214 mDrawingState.sequence++;
1215 mDrawingState.stretchEffect = temp;
1216 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001217 setTransactionFlags(eTransactionNeeded);
1218 return true;
1219}
1220
John Reckc00c6692021-02-16 11:37:33 -05001221StretchEffect Layer::getStretchEffect() const {
1222 if (mDrawingState.stretchEffect.hasEffect()) {
1223 return mDrawingState.stretchEffect;
1224 }
1225
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001226 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001227 if (parent != nullptr) {
1228 auto effect = parent->getStretchEffect();
1229 if (effect.hasEffect()) {
1230 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1231 return effect;
1232 }
1233 }
1234 return StretchEffect{};
1235}
1236
Rachel Lee0faad6c2023-09-08 13:34:34 -07001237bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool overrideChildren,
1238 bool* transactionNeeded) {
1239 // Gets the frame rate to propagate to children.
Ady Abrahama850c182021-08-04 13:04:37 -07001240 const auto frameRate = [&] {
Rachel Lee0faad6c2023-09-08 13:34:34 -07001241 if (overrideChildren && parentFrameRate.isValid()) {
1242 return parentFrameRate;
1243 }
1244
Rachel Leece6e0042023-06-27 11:22:54 -07001245 if (mDrawingState.frameRate.isValid()) {
Ady Abrahama850c182021-08-04 13:04:37 -07001246 return mDrawingState.frameRate;
1247 }
1248
1249 return parentFrameRate;
1250 }();
1251
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001252 auto now = systemTime();
1253 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate, now);
Ady Abrahama850c182021-08-04 13:04:37 -07001254
Rachel Leea021bb02023-11-20 21:51:09 -08001255 // The frame rate is propagated to the children by default, but some properties may override it.
Ady Abrahama850c182021-08-04 13:04:37 -07001256 bool childrenHaveFrameRate = false;
Rachel Leea021bb02023-11-20 21:51:09 -08001257 const bool overrideChildrenFrameRate = overrideChildren || shouldOverrideChildrenFrameRate();
1258 const bool canPropagateFrameRate = shouldPropagateFrameRate() || overrideChildrenFrameRate;
Ady Abrahama850c182021-08-04 13:04:37 -07001259 for (const sp<Layer>& child : mCurrentChildren) {
1260 childrenHaveFrameRate |=
Rachel Leea021bb02023-11-20 21:51:09 -08001261 child->propagateFrameRateForLayerTree(canPropagateFrameRate ? frameRate
1262 : FrameRate(),
1263 overrideChildrenFrameRate, transactionNeeded);
Ady Abrahama850c182021-08-04 13:04:37 -07001264 }
1265
Rachel Leece6e0042023-06-27 11:22:54 -07001266 // If we don't have a valid frame rate specification, but the children do, we set this
Ady Abrahama850c182021-08-04 13:04:37 -07001267 // layer as NoVote to allow the children to control the refresh rate
Rachel Leece6e0042023-06-27 11:22:54 -07001268 if (!frameRate.isValid() && childrenHaveFrameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001269 *transactionNeeded |=
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001270 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote),
1271 now);
Ady Abrahama850c182021-08-04 13:04:37 -07001272 }
1273
Rachel Leece6e0042023-06-27 11:22:54 -07001274 // We return whether this layer or its children has a vote. We ignore ExactOrMultiple votes for
Ady Abrahama850c182021-08-04 13:04:37 -07001275 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001276 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001277 const auto layerVotedWithDefaultCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001278 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Default;
1279 const auto layerVotedWithNoVote = frameRate.vote.type == FrameRateCompatibility::NoVote;
1280 const auto layerVotedWithCategory = frameRate.category != FrameRateCategory::Default;
Ady Abrahama850c182021-08-04 13:04:37 -07001281 const auto layerVotedWithExactCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001282 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Exact;
1283 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote || layerVotedWithCategory ||
Ady Abrahama850c182021-08-04 13:04:37 -07001284 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1285}
1286
Ady Abraham60e42ea2020-03-09 19:17:31 -07001287void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001288 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001289 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001290 while (auto parent = layer->getParent()) {
1291 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001292 }
Ady Abrahama850c182021-08-04 13:04:37 -07001293 return layer;
1294 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001295
Ady Abraham60e42ea2020-03-09 19:17:31 -07001296 bool transactionNeeded = false;
Rachel Lee0faad6c2023-09-08 13:34:34 -07001297 root->propagateFrameRateForLayerTree({}, false, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001298
Ady Abrahama850c182021-08-04 13:04:37 -07001299 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001300 if (transactionNeeded) {
1301 mFlinger->setTransactionFlags(eTraversalNeeded);
1302 }
1303}
1304
Rachel Leece6e0042023-06-27 11:22:54 -07001305bool Layer::setFrameRate(FrameRate::FrameRateVote frameRateVote) {
1306 if (mDrawingState.frameRate.vote == frameRateVote) {
Steven Thomas3172e202020-01-06 19:25:30 -08001307 return false;
1308 }
1309
Robert Carr6a160312021-05-17 12:08:20 -07001310 mDrawingState.sequence++;
Rachel Leece6e0042023-06-27 11:22:54 -07001311 mDrawingState.frameRate.vote = frameRateVote;
1312 mDrawingState.modified = true;
1313
1314 updateTreeHasFrameRateVote();
1315
1316 setTransactionFlags(eTransactionNeeded);
1317 return true;
1318}
1319
Rachel Lee67afbea2023-09-28 15:35:07 -07001320bool Layer::setFrameRateCategory(FrameRateCategory category, bool smoothSwitchOnly) {
1321 if (mDrawingState.frameRate.category == category &&
1322 mDrawingState.frameRate.categorySmoothSwitchOnly == smoothSwitchOnly) {
Rachel Leece6e0042023-06-27 11:22:54 -07001323 return false;
1324 }
1325
1326 mDrawingState.sequence++;
1327 mDrawingState.frameRate.category = category;
Rachel Lee67afbea2023-09-28 15:35:07 -07001328 mDrawingState.frameRate.categorySmoothSwitchOnly = smoothSwitchOnly;
Robert Carr6a160312021-05-17 12:08:20 -07001329 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001330
1331 updateTreeHasFrameRateVote();
1332
Steven Thomas3172e202020-01-06 19:25:30 -08001333 setTransactionFlags(eTransactionNeeded);
1334 return true;
1335}
1336
Rachel Lee58cc90d2023-09-05 18:50:20 -07001337bool Layer::setFrameRateSelectionStrategy(FrameRateSelectionStrategy strategy) {
1338 if (mDrawingState.frameRateSelectionStrategy == strategy) return false;
1339 mDrawingState.frameRateSelectionStrategy = strategy;
1340 mDrawingState.sequence++;
1341 mDrawingState.modified = true;
Rachel Leed7479502023-09-25 17:02:35 -07001342
1343 updateTreeHasFrameRateVote();
Rachel Lee58cc90d2023-09-05 18:50:20 -07001344 setTransactionFlags(eTransactionNeeded);
1345 return true;
1346}
1347
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001348void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1349 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001350 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001351
1352 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1353 // there are two transactions with the same token, the first one without a buffer and the
1354 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1355 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001356 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1357 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001358 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001359 mDrawingState.bufferSurfaceFrameTX = it->second;
1360 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1361 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1362 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001363 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001364 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001365 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1366 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001367
1368 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001369}
1370
1371void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1372 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001373 mDrawingState.frameTimelineInfo = info;
1374 mDrawingState.postTime = postTime;
1375 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001376 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001377
Robert Carr6a160312021-05-17 12:08:20 -07001378 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001379 bufferSurfaceFrameTX != nullptr) {
1380 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1381 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1382 // being used for BufferSurfaceFrame, don't create a new one.
1383 return;
1384 }
1385 }
1386 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1387 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1388 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001389 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1390 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001391 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001392 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001393 } else {
1394 if (it->second->getPresentState() == PresentState::Presented) {
1395 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1396 // have been from previous vsync.
1397 it->second = createSurfaceFrameForTransaction(info, postTime);
1398 }
1399 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001400
1401 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001402}
1403
1404void Layer::addSurfaceFrameDroppedForBuffer(
Ady Abraham5a3e3562023-06-07 10:32:08 -07001405 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t dropTime) {
1406 surfaceFrame->setDropTime(dropTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001407 surfaceFrame->setPresentState(PresentState::Dropped);
1408 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1409}
1410
1411void Layer::addSurfaceFramePresentedForBuffer(
1412 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1413 nsecs_t currentLatchTime) {
1414 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1415 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1416 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001417 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001418}
1419
1420std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1421 const FrameTimelineInfo& info, nsecs_t postTime) {
1422 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001423 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1424 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001425 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001426 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001427 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001428 // For Transactions, the post time is considered to be both queue and acquire fence time.
1429 surfaceFrame->setActualQueueTime(postTime);
1430 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001431 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1432 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001433 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001434 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001435 onSurfaceFrameCreated(surfaceFrame);
1436 return surfaceFrame;
1437}
1438
1439std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1440 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1441 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001442 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001443 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001444 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001445 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001446 // For buffers, acquire fence time will set during latch.
1447 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001448 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1449 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001450 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001451 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001452 onSurfaceFrameCreated(surfaceFrame);
1453 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001454}
1455
Ady Abraham5a3e3562023-06-07 10:32:08 -07001456void Layer::setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
1457 std::string debugName) {
1458 if (info.skippedFrameVsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
1459 return;
1460 }
1461
1462 FrameTimelineInfo skippedFrameTimelineInfo = info;
1463 skippedFrameTimelineInfo.vsyncId = info.skippedFrameVsyncId;
1464
1465 auto surfaceFrame =
1466 mFlinger->mFrameTimeline->createSurfaceFrameForToken(skippedFrameTimelineInfo,
1467 mOwnerPid, mOwnerUid,
1468 getSequence(), mName, debugName,
1469 /*isBuffer*/ false, getGameMode());
1470 surfaceFrame->setActualStartTime(skippedFrameTimelineInfo.skippedFrameStartTimeNanos);
1471 // For Transactions, the post time is considered to be both queue and acquire fence time.
1472 surfaceFrame->setActualQueueTime(postTime);
1473 surfaceFrame->setAcquireFenceTime(postTime);
1474 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1475 if (fps) {
1476 surfaceFrame->setRenderRate(*fps);
1477 }
1478 onSurfaceFrameCreated(surfaceFrame);
1479 addSurfaceFrameDroppedForBuffer(surfaceFrame, postTime);
1480}
1481
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001482bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate, nsecs_t now) {
Ady Abrahama850c182021-08-04 13:04:37 -07001483 if (mDrawingState.frameRateForLayerTree == frameRate) {
1484 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001485 }
1486
Ady Abrahama850c182021-08-04 13:04:37 -07001487 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001488
Ady Abrahama850c182021-08-04 13:04:37 -07001489 // TODO(b/195668952): we probably don't need to dirty visible regions here
1490 // or even store frameRateForLayerTree in mDrawingState
1491 mDrawingState.sequence++;
1492 mDrawingState.modified = true;
1493 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001494
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001495 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001496 ->recordLayerHistory(sequence, getLayerProps(), now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001497 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1498 return true;
1499}
Ady Abrahama850c182021-08-04 13:04:37 -07001500
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001501bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps,
1502 nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001503 if (mDrawingState.frameRateForLayerTree == frameRate) {
1504 return false;
1505 }
1506
1507 mDrawingState.frameRateForLayerTree = frameRate;
1508 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001509 ->recordLayerHistory(sequence, layerProps, now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001510 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001511 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001512}
1513
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001514Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1515 return getDrawingState().frameRateForLayerTree;
1516}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001517
Robert Carr1f0a16a2016-10-24 16:27:39 -07001518bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001519 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001520 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001521 if (parent != nullptr && parent->isHiddenByPolicy()) {
1522 return true;
1523 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001524 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1525 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1526 if (zOrderRelativeOf != nullptr) {
1527 if (zOrderRelativeOf->isHiddenByPolicy()) {
1528 return true;
1529 }
1530 }
1531 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001532 if (CC_UNLIKELY(!isTransformValid())) {
1533 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1534 return true;
1535 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001536 return s.flags & layer_state_t::eLayerHidden;
1537}
1538
David Sodman41fdfc92017-11-06 16:09:56 -08001539uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001540 // TODO: should we do something special if mSecure is set?
1541 if (mProtectedByApp) {
1542 // need a hardware-protected path to external video sink
1543 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001544 }
Riley Andrews03414a12014-07-01 14:22:59 -07001545 if (mPotentialCursor) {
1546 usage |= GraphicBuffer::USAGE_CURSOR;
1547 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001548 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001549 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001550}
1551
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001552void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1553 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1554 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001555 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001556
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001557 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001558}
1559
Mathias Agopian13127d82013-03-05 17:47:11 -08001560// ----------------------------------------------------------------------------
1561// debugging
1562// ----------------------------------------------------------------------------
1563
Yiwei Zhang5434a782018-12-05 18:06:32 -08001564void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001565 result.append(kDumpTableRowLength, '-');
1566 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001567 result.append(" Layer name\n");
1568 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001569 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001570 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001571 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001572 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001573 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001574 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1575 result.append(kDumpTableRowLength, '-');
1576 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001577}
1578
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001579void Layer::miniDumpLegacy(std::string& result, const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001580 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001581 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001582 return;
1583 }
1584
Yiwei Zhang5434a782018-12-05 18:06:32 -08001585 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001586 if (mName.length() > 77) {
1587 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001588 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001589 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001590 shortened.append(mName, mName.length() - 36);
1591 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001592 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001593 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001594 }
1595
Yiwei Zhang5434a782018-12-05 18:06:32 -08001596 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001597
Alec Mourib416efd2018-09-06 21:01:59 +00001598 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001599 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001600
Chia-I Wu1e043612018-03-01 09:45:09 -08001601 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001602 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001603 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001604 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001605 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001606 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001607 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001608 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1609 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001610 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001611 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001612 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001613 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001614 const auto frameRate = getFrameRateForLayerTree();
Rachel Leece6e0042023-06-27 11:22:54 -07001615 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
1616 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.vote.rate).c_str(),
1617 ftl::enum_string(frameRate.vote.type).c_str(),
1618 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001619 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001620 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001621 }
Dan Stozae22aec72016-08-01 13:20:59 -07001622
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001623 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1624 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1625
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001626 result.append(kDumpTableRowLength, '-');
1627 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001628}
Dan Stozae22aec72016-08-01 13:20:59 -07001629
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001630void Layer::miniDump(std::string& result, const frontend::LayerSnapshot& snapshot,
1631 const DisplayDevice& display) const {
1632 const auto outputLayer = findOutputLayerForDisplay(&display, snapshot.path);
1633 if (!outputLayer) {
1634 return;
1635 }
1636
1637 StringAppendF(&result, " %s\n", snapshot.debugName.c_str());
1638 StringAppendF(&result, " %10zu | ", snapshot.globalZ);
1639 StringAppendF(&result, " %10d | ",
1640 snapshot.layerMetadata.getInt32(gui::METADATA_WINDOW_TYPE, 0));
1641 StringAppendF(&result, "%10s | ", toString(getCompositionType(outputLayer)).c_str());
1642 const auto& outputLayerState = outputLayer->getState();
1643 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1644 const Rect& frame = outputLayerState.displayFrame;
1645 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1646 const FloatRect& crop = outputLayerState.sourceCrop;
1647 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
1648 crop.bottom);
1649 const auto frameRate = snapshot.frameRate;
Ady Abraham77d406d2023-11-22 15:00:23 -08001650 std::string frameRateStr;
1651 if (frameRate.vote.rate.isValid()) {
1652 StringAppendF(&frameRateStr, "%.2f", frameRate.vote.rate.getValue());
1653 }
Rachel Leece6e0042023-06-27 11:22:54 -07001654 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
Ady Abraham77d406d2023-11-22 15:00:23 -08001655 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
Rachel Leece6e0042023-06-27 11:22:54 -07001656 ftl::enum_string(frameRate.vote.type).c_str(),
1657 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abraham77d406d2023-11-22 15:00:23 -08001658 } else if (frameRate.category != FrameRateCategory::Default) {
1659 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
1660 (std::string("Cat::") + ftl::enum_string(frameRate.category)).c_str(),
1661 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001662 } else {
1663 result.append(41, ' ');
1664 }
1665
1666 const auto focused = isLayerFocusedBasedOnPriority(snapshot.frameRateSelectionPriority);
1667 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1668
1669 result.append(kDumpTableRowLength, '-');
1670 result.append("\n");
1671}
1672
Yiwei Zhang5434a782018-12-05 18:06:32 -08001673void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001674 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001675}
1676
Svetoslavd85084b2014-03-20 10:28:31 -07001677void Layer::clearFrameStats() {
1678 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001679}
1680
Jamie Gennis6547ff42013-07-16 20:12:42 -07001681void Layer::logFrameStats() {
1682 mFrameTracker.logAndResetStats(mName);
1683}
1684
Svetoslavd85084b2014-03-20 10:28:31 -07001685void Layer::getFrameStats(FrameStats* outStats) const {
1686 mFrameTracker.getStats(outStats);
1687}
1688
Vishnu Nair76554eb2022-12-09 03:38:36 +00001689void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1690 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
Vishnu Nair3be61902023-04-26 19:47:29 -07001691 StringAppendF(&result, "Layer %s%s pid:%d uid:%d%s\n", getName().c_str(), hasBuffer.c_str(),
1692 mOwnerPid, mOwnerUid, isHandleAlive() ? " handleAlive" : "");
Vishnu Nair0f085c62019-08-30 08:49:12 -07001693}
1694
Brian Anderson5ea5e592016-12-01 16:54:33 -08001695void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001696 const int32_t layerId = getSequence();
1697 mFlinger->mTimeStats->onDestroy(layerId);
1698 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001699}
1700
Vishnu Nair787aa782023-03-17 13:46:46 -07001701size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001702 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001703 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001704 count += 1 + child->getChildrenCount();
1705 }
1706 return count;
1707}
1708
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001709void Layer::setGameModeForTree(GameMode gameMode) {
1710 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001711 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1712 gameMode =
1713 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001714 }
1715 setGameMode(gameMode);
1716 for (const sp<Layer>& child : mCurrentChildren) {
1717 child->setGameModeForTree(gameMode);
1718 }
1719}
1720
Robert Carr1f0a16a2016-10-24 16:27:39 -07001721void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001722 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001723 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001724
Robert Carr1f0a16a2016-10-24 16:27:39 -07001725 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001726 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001727 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001728 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001729}
1730
1731ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001732 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001733 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001734
Robert Carr1323c952019-01-28 18:13:27 -08001735 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001736 const auto removeResult = mCurrentChildren.remove(layer);
1737
1738 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001739 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001740 layer->updateTreeHasFrameRateVote();
1741
1742 return removeResult;
1743}
1744
Robert Carr15eae092018-03-23 13:43:53 -07001745void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001746 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001747 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001748 const float parentShadowRadius =
1749 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001750 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001751 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001752 }
1753}
1754
chaviwf1961f72017-09-18 16:41:07 -07001755bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001756 sp<Layer> newParent;
1757 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001758 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001759 if (newParent == nullptr) {
1760 ALOGE("Unable to promote Layer handle");
1761 return false;
1762 }
1763 if (newParent == this) {
1764 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1765 return false;
1766 }
1767 }
1768
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001769 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001770 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001771 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001772 }
1773
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001774 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001775 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001776 if (!newParent->isRemovedFromCurrentState()) {
1777 addToCurrentState();
1778 } else {
1779 onRemovedFromCurrentState();
1780 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001781 } else {
1782 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001783 }
1784
chaviw06178942017-07-27 10:25:59 -07001785 return true;
1786}
1787
Peiyong Lind3788632018-09-18 16:01:31 -07001788bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001789 static const mat4 identityMatrix = mat4();
1790
Robert Carr6a160312021-05-17 12:08:20 -07001791 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001792 return false;
1793 }
Robert Carr6a160312021-05-17 12:08:20 -07001794 ++mDrawingState.sequence;
1795 mDrawingState.colorTransform = matrix;
1796 mDrawingState.hasColorTransform = matrix != identityMatrix;
1797 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001798 setTransactionFlags(eTransactionNeeded);
1799 return true;
1800}
1801
chaviwf66724d2018-11-28 16:35:21 -08001802mat4 Layer::getColorTransform() const {
1803 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001804 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001805 colorTransform = parent->getColorTransform() * colorTransform;
1806 }
1807 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001808}
1809
1810bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001811 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001812 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001813 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1814 }
1815 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001816}
1817
Chia-I Wu11481472018-05-04 10:43:19 -07001818bool Layer::isLegacyDataSpace() const {
1819 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001820 return !(getDataSpace() &
1821 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1822 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001823}
1824
Robert Carr1f0a16a2016-10-24 16:27:39 -07001825void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001826 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001827}
1828
Robert Carr6a160312021-05-17 12:08:20 -07001829int32_t Layer::getZ(LayerVector::StateSet) const {
1830 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001831}
1832
Robert Carr1c5481e2019-07-01 14:42:27 -07001833bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001834 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001835 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001836 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001837}
1838
David Sodman41fdfc92017-11-06 16:09:56 -08001839__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001840 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001841 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1842 "makeTraversalList received invalid stateSet");
1843 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1844 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001845 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001846
Robert Carr29abff82017-12-04 13:51:20 -08001847 if (state.zOrderRelatives.size() == 0) {
1848 *outSkipRelativeZUsers = true;
1849 return children;
1850 }
1851
chaviwfd462612018-05-31 16:11:27 -07001852 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001853 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001854 sp<Layer> strongRelative = weakRelative.promote();
1855 if (strongRelative != nullptr) {
1856 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001857 }
1858 }
1859
Dan Stoza412903f2017-04-27 13:42:17 -07001860 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001861 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001862 continue;
1863 }
Robert Carrdb66e622017-04-10 16:55:57 -07001864 traverse.add(child);
1865 }
1866
1867 return traverse;
1868}
1869
Robert Carr1f0a16a2016-10-24 16:27:39 -07001870/**
Robert Carrdb66e622017-04-10 16:55:57 -07001871 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001872 */
Dan Stoza412903f2017-04-27 13:42:17 -07001873void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001874 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1875 // produce a new list for traversing, including our relatives, and not including our children
1876 // who are relatives of another surface. In the case that there are no relative Z,
1877 // makeTraversalList returns our children directly to avoid significant overhead.
1878 // However in this case we need to take the responsibility for filtering children which
1879 // are relatives of another surface here.
1880 bool skipRelativeZUsers = false;
1881 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001882
Robert Carr1f0a16a2016-10-24 16:27:39 -07001883 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001884 for (; i < list.size(); i++) {
1885 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001886 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1887 continue;
1888 }
1889
chaviw301b1d82019-11-06 13:15:09 -08001890 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001891 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001892 }
Dan Stoza412903f2017-04-27 13:42:17 -07001893 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001894 }
Robert Carr29abff82017-12-04 13:51:20 -08001895
Dan Stoza412903f2017-04-27 13:42:17 -07001896 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001897 for (; i < list.size(); i++) {
1898 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001899
Robert Carr29abff82017-12-04 13:51:20 -08001900 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1901 continue;
1902 }
Dan Stoza412903f2017-04-27 13:42:17 -07001903 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001904 }
1905}
1906
1907/**
Robert Carrdb66e622017-04-10 16:55:57 -07001908 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001909 */
Dan Stoza412903f2017-04-27 13:42:17 -07001910void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1911 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001912 // See traverseInZOrder for documentation.
1913 bool skipRelativeZUsers = false;
1914 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001915
Robert Carr1f0a16a2016-10-24 16:27:39 -07001916 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001917 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001918 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001919
1920 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1921 continue;
1922 }
1923
chaviw301b1d82019-11-06 13:15:09 -08001924 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001925 break;
1926 }
Dan Stoza412903f2017-04-27 13:42:17 -07001927 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001928 }
Dan Stoza412903f2017-04-27 13:42:17 -07001929 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001930 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001931 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001932
1933 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1934 continue;
1935 }
1936
Dan Stoza412903f2017-04-27 13:42:17 -07001937 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001938 }
1939}
1940
Edgar Arriaga844fa672020-01-16 14:21:42 -08001941void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1942 visitor(this);
1943 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001944 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001945 for (const sp<Layer>& child : children) {
1946 child->traverse(state, visitor);
1947 }
1948}
1949
Vishnu Nair787aa782023-03-17 13:46:46 -07001950void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
1951 for (const sp<Layer>& child : mDrawingChildren) {
1952 visitor(child.get());
1953 }
1954}
1955
chaviw4b129c22018-04-09 16:19:43 -07001956LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1957 const std::vector<Layer*>& layersInTree) {
1958 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1959 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001960 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1961 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001962 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001963
chaviwfd462612018-05-31 16:11:27 -07001964 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001965 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1966 sp<Layer> strongRelative = weakRelative.promote();
1967 // Only add relative layers that are also descendents of the top most parent of the tree.
1968 // If a relative layer is not a descendent, then it should be ignored.
1969 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1970 traverse.add(strongRelative);
1971 }
1972 }
1973
1974 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001975 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001976 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1977 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1978 // the child here since it won't be added later as a relative.
1979 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1980 childState.zOrderRelativeOf.promote().get())) {
1981 continue;
1982 }
1983 traverse.add(child);
1984 }
1985
1986 return traverse;
1987}
1988
1989void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1990 LayerVector::StateSet stateSet,
1991 const LayerVector::Visitor& visitor) {
1992 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001993
1994 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001995 for (; i < list.size(); i++) {
1996 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001997 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001998 break;
1999 }
chaviw4b129c22018-04-09 16:19:43 -07002000 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002001 }
chaviw4b129c22018-04-09 16:19:43 -07002002
chaviwa76b2712017-09-20 12:02:26 -07002003 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07002004 for (; i < list.size(); i++) {
2005 const auto& relative = list[i];
2006 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002007 }
2008}
2009
chaviw4b129c22018-04-09 16:19:43 -07002010std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2011 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2012 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2013
2014 std::vector<Layer*> layersInTree = {this};
2015 for (size_t i = 0; i < children.size(); i++) {
2016 const auto& child = children[i];
2017 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2018 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2019 }
2020
2021 return layersInTree;
2022}
2023
2024void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2025 const LayerVector::Visitor& visitor) {
2026 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2027 std::sort(layersInTree.begin(), layersInTree.end());
2028 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2029}
2030
Peiyong Linefefaac2018-08-17 12:27:51 -07002031ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08002032 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002033}
2034
Garfield Tan2c1782c2022-02-16 15:25:05 -08002035bool Layer::isTransformValid() const {
2036 float transformDet = getTransform().det();
2037 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2038}
2039
chaviw13fdc492017-06-27 12:40:18 -07002040half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002041 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002042
chaviw13fdc492017-06-27 12:40:18 -07002043 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2044 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002045}
Robert Carr6452f122017-03-21 10:41:29 -07002046
Vishnu Nair6213bd92020-05-08 17:42:25 -07002047ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002048 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002049 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2050 return fixedTransformHint;
2051 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002052 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002053 if (!p) return fixedTransformHint;
2054 return p->getFixedTransformHint();
2055}
2056
chaviw13fdc492017-06-27 12:40:18 -07002057half4 Layer::getColor() const {
2058 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002059 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002060}
Robert Carr6452f122017-03-21 10:41:29 -07002061
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002062int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002063 if (getDrawingState().backgroundBlurRadius == 0) {
2064 return 0;
2065 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002066
Vishnu Nair29810f72022-07-01 16:38:41 +00002067 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002068 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2069 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002070}
2071
Galia Peychevae0acf382021-04-12 21:22:34 +02002072const std::vector<BlurRegion> Layer::getBlurRegions() const {
2073 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002074 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002075 for (auto& region : regionsCopy) {
2076 region.alpha = region.alpha * layerAlpha;
2077 }
2078 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002079}
2080
Vishnu Naire14c6b32022-08-06 04:20:15 +00002081RoundedCornerState Layer::getRoundedCornerState() const {
Leon Scroggins IIIc1dbfcb2022-03-21 16:48:10 -04002082 // Today's DPUs cannot do rounded corners. If RenderEngine cannot render
2083 // protected content, remove rounded corners from protected content so it
2084 // can be rendered by the DPU.
2085 if (isProtected() && !mFlinger->getRenderEngine().supportsProtectedContent()) {
2086 return {};
2087 }
2088
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002089 // Get parent settings
2090 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002091 const auto& parent = mDrawingParent.promote();
2092 if (parent != nullptr) {
2093 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002094 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002095 ui::Transform t = getActiveTransform(getDrawingState());
2096 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002097 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002098 parentSettings.radius.x *= t.getScaleX();
2099 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002100 }
2101 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002102
2103 // Get layer settings
2104 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002105 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002106 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002107 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002108
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002109 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002110 // If the parent and the layer have rounded corner settings, use the parent settings if the
2111 // parent crop is entirely inside the layer crop.
2112 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2113 if (parentSettings.cropRect.left > layerCropRect.left &&
2114 parentSettings.cropRect.top > layerCropRect.top &&
2115 parentSettings.cropRect.right < layerCropRect.right &&
2116 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2117 return parentSettings;
2118 } else {
2119 return layerSettings;
2120 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002121 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002122 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002123 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002124 return parentSettings;
2125 }
2126 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002127}
2128
Robert Carr88b85e12022-03-21 15:47:35 -07002129bool Layer::findInHierarchy(const sp<Layer>& l) {
2130 if (l == this) {
2131 return true;
2132 }
2133 for (auto& child : mDrawingChildren) {
2134 if (child->findInHierarchy(l)) {
2135 return true;
2136 }
2137 }
2138 return false;
2139}
2140
Robert Carr1f0a16a2016-10-24 16:27:39 -07002141void Layer::commitChildList() {
2142 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2143 const auto& child = mCurrentChildren[i];
2144 child->commitChildList();
2145 }
2146 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002147 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002148 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2149 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2150 if (zOrderRelativeOf == nullptr) return;
2151 if (findInHierarchy(zOrderRelativeOf)) {
2152 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2153 zOrderRelativeOf->mName.c_str());
2154 ALOGE("Severing rel Z loop, potentially dangerous");
2155 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002156 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002157 }
2158 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002159}
2160
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002161
chaviw3277faf2021-05-19 16:45:23 -05002162void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002163 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002164 mDrawingState.touchableRegionCrop =
2165 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002166 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002167 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002168 setTransactionFlags(eTransactionNeeded);
2169}
2170
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002171perfetto::protos::LayerProto* Layer::writeToProto(perfetto::protos::LayersProto& layersProto,
2172 uint32_t traceFlags) {
2173 perfetto::protos::LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002174 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002175 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2176
Vishnu Nair00b90132021-11-05 14:03:40 -07002177 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nair2f65e972023-04-04 16:36:28 +00002178 ui::LayerStack layerStack =
2179 (mSnapshot) ? mSnapshot->outputFilter.layerStack : ui::INVALID_LAYER_STACK;
2180 writeCompositionStateToProto(layerProto, layerStack);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002181 }
2182
chaviw08f3cb22020-01-13 13:17:21 -08002183 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002184 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002185 }
chaviw6d89e2d2020-01-14 14:42:01 -08002186
2187 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002188}
2189
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002190void Layer::writeCompositionStateToProto(perfetto::protos::LayerProto* layerProto,
2191 ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002192 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002193 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +00002194
2195 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002196 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002197 const auto compositionType = getCompositionType(*display);
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002198 layerProto->set_hwc_composition_type(
2199 static_cast<perfetto::protos::HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +00002200 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +00002201 [&]() { return layerProto->mutable_visible_region(); });
2202 }
2203}
2204
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002205void Layer::writeToProtoDrawingState(perfetto::protos::LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002206 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002207 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002208 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002209 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002210 [&]() { return layerInfo->mutable_active_buffer(); });
2211 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2212 layerInfo->mutable_buffer_transform());
2213 }
2214 layerInfo->set_invalidate(contentDirty);
2215 layerInfo->set_is_protected(isProtected());
2216 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2217 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002218 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002219 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002220 layerInfo->set_corner_radius(
2221 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002222 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2223 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2224 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2225 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2226 [&]() { return layerInfo->mutable_position(); });
2227 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002228 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2229 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002230
Vishnu Nair00b90132021-11-05 14:03:40 -07002231 if (hasColorTransform()) {
2232 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002233 }
2234
Vishnu Nair60db8c02020-04-02 11:55:16 -07002235 LayerProtoHelper::writeToProto(mSourceBounds,
2236 [&]() { return layerInfo->mutable_source_bounds(); });
2237 LayerProtoHelper::writeToProto(mScreenBounds,
2238 [&]() { return layerInfo->mutable_screen_bounds(); });
2239 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2240 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2241 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002242}
2243
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002244void Layer::writeToProtoCommonState(perfetto::protos::LayerProto* layerInfo,
2245 LayerVector::StateSet stateSet, uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002246 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2247 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002248 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002249
chaviw766c9c52021-02-10 17:36:47 -08002250 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002251
Vishnu Nair00b90132021-11-05 14:03:40 -07002252 layerInfo->set_id(sequence);
2253 layerInfo->set_name(getName().c_str());
2254 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002255
Vishnu Nair00b90132021-11-05 14:03:40 -07002256 for (const auto& child : children) {
2257 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002258 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002259
Vishnu Nair00b90132021-11-05 14:03:40 -07002260 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2261 sp<Layer> strongRelative = weakRelative.promote();
2262 if (strongRelative != nullptr) {
2263 layerInfo->add_relatives(strongRelative->sequence);
2264 }
2265 }
2266
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002267 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002268 [&]() { return layerInfo->mutable_transparent_region(); });
2269
2270 layerInfo->set_layer_stack(getLayerStack().id);
2271 layerInfo->set_z(state.z);
2272
2273 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2274 return layerInfo->mutable_requested_position();
2275 });
2276
Vishnu Nair00b90132021-11-05 14:03:40 -07002277 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2278
2279 layerInfo->set_is_opaque(isOpaque(state));
2280
2281 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2282 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2283 LayerProtoHelper::writeToProto(state.color,
2284 [&]() { return layerInfo->mutable_requested_color(); });
2285 layerInfo->set_flags(state.flags);
2286
2287 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2288 layerInfo->mutable_requested_transform());
2289
2290 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2291 if (parent != nullptr) {
2292 layerInfo->set_parent(parent->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002293 }
2294
2295 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2296 if (zOrderRelativeOf != nullptr) {
2297 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002298 }
2299
2300 layerInfo->set_is_relative_of(state.isRelativeOf);
2301
2302 layerInfo->set_owner_uid(mOwnerUid);
2303
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002304 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002305 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002306 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002307 info = fillInputInfo(
2308 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002309 } else {
2310 info = state.inputInfo;
2311 }
2312
2313 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002314 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002315 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002316
Vishnu Nair00b90132021-11-05 14:03:40 -07002317 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002318 auto protoMap = layerInfo->mutable_metadata();
2319 for (const auto& entry : state.metadata.mMap) {
2320 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2321 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002322 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002323
2324 LayerProtoHelper::writeToProto(state.destinationFrame,
2325 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002326}
2327
Robert Carr2e102c92018-10-23 12:11:15 -07002328bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002329 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002330}
2331
Prabir Pradhan33da9462022-06-14 14:55:57 +00002332// Applies the given transform to the region, while protecting against overflows caused by any
2333// offsets. If applying the offset in the transform to any of the Rects in the region would result
2334// in an overflow, they are not added to the output Region.
2335static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2336 const std::string& debugWindowName) {
2337 // Round the translation using the same rounding strategy used by ui::Transform.
2338 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2339 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2340
2341 ui::Transform transformWithoutOffset = t;
2342 transformWithoutOffset.set(0.f, 0.f);
2343
2344 const Region transformed = transformWithoutOffset.transform(r);
2345
2346 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2347 Region ret;
2348 for (const auto& rect : transformed) {
2349 Rect newRect;
2350 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2351 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2352 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2353 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2354 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2355 debugWindowName.c_str());
2356 continue;
2357 }
2358 ret.orSelf(newRect);
2359 }
2360 return ret;
2361}
2362
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002363void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002364 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2365 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002366 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002367 }
2368
Chavi Weingarten7f019192023-08-08 20:39:01 +00002369 info.frame = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
chaviw1ff3d1e2020-07-01 15:53:47 -07002370
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002371 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002372 inputToLayer.set(inputBounds.left, inputBounds.top);
2373 const ui::Transform layerToScreen = getInputTransform();
2374 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002375
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002376 // InputDispatcher expects a display-to-input transform.
2377 info.transform = inputToDisplay.inverse();
2378
2379 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002380 info.touchableRegion =
2381 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002382}
2383
chaviw3277faf2021-05-19 16:45:23 -05002384void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002385 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002386 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002387 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002388 }
2389 if (p != nullptr) {
2390 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2391 }
2392}
2393
Vishnu Naira066d902021-09-13 18:40:17 -07002394gui::DropInputMode Layer::getDropInputMode() const {
2395 gui::DropInputMode mode = mDrawingState.dropInputMode;
2396 if (mode == gui::DropInputMode::ALL) {
2397 return mode;
2398 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002399 sp<Layer> parent = mDrawingParent.promote();
2400 if (parent) {
2401 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002402 if (parentMode != gui::DropInputMode::NONE) {
2403 return parentMode;
2404 }
2405 }
2406 return mode;
2407}
2408
2409void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002410 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002411 return;
2412 }
2413
2414 // Check if we need to drop input unconditionally
2415 gui::DropInputMode dropInputMode = getDropInputMode();
2416 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002417 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002418 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2419 return;
2420 }
2421
2422 // Check if we need to check if the window is obscured by parent
2423 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2424 return;
2425 }
2426
2427 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002428 sp<Layer> parent = mDrawingParent.promote();
2429 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002430 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002431 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2432 static_cast<float>(getAlpha()));
2433 }
2434
2435 // Check if the parent has cropped the buffer
2436 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2437 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002438 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002439 return;
2440 }
2441
2442 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2443 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2444 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2445 // match then the layer has not been cropped by its parents.
2446 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2447 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2448
2449 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002450 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002451 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2452 getDebugName());
2453 } else {
2454 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2455 // input if the window is obscured. This check should be done in surfaceflinger but the
2456 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2457 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002458 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002459 }
2460}
2461
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002462WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002463 if (!hasInputInfo()) {
2464 mDrawingState.inputInfo.name = getName();
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002465 mDrawingState.inputInfo.ownerUid = gui::Uid{mOwnerUid};
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00002466 mDrawingState.inputInfo.ownerPid = gui::Pid{mOwnerPid};
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002467 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002468 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002469 }
2470
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002471 const ui::Transform& displayTransform =
2472 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2473
chaviw3277faf2021-05-19 16:45:23 -05002474 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002475 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002476 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002477
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002478 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002479
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002480 if (displayArgs.transform == nullptr) {
2481 // Do not let the window receive touches if it is not associated with a valid display
2482 // transform. We still allow the window to receive keys and prevent ANRs.
2483 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2484 }
2485
Patrick Williams1caf3b72023-03-31 10:59:10 -05002486 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !isVisibleForInput());
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002487
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002488 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002489 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002490 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002491
Vishnu Nair16a938f2021-09-24 07:14:54 -07002492 // If the window will be blacked out on a display because the display does not have the secure
2493 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002494 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002495 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002496 }
2497
Vishnu Nairfed7c122023-03-18 01:54:43 +00002498 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002499 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002500 Rect inputBoundsInDisplaySpace;
2501 if (!cropLayer) {
2502 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2503 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2504 } else {
2505 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2506 inputBoundsInDisplaySpace =
2507 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2508 }
2509 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002510 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002511 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2512 Rect inputBoundsInDisplaySpace =
2513 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2514 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002515 }
2516
Winson Chunga30f7c92021-06-29 15:42:56 -07002517 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2518 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002519 if (isTrustedOverlay()) {
2520 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2521 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002522
chaviwaf87b3e2019-10-01 16:59:28 -07002523 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2524 // touches from going outside the cloned area.
2525 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002526 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002527 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2528 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002529 info.touchableRegion = info.touchableRegion.intersect(rect);
2530 }
2531 }
2532
Vishnu Nair494a2e42023-11-10 17:21:19 -08002533 Rect bufferSize = getBufferSize(getDrawingState());
2534 info.contentSize = Size(bufferSize.width(), bufferSize.height());
2535
Robert Carr720e5062018-07-30 17:45:14 -07002536 return info;
2537}
2538
Vishnu Nairfed7c122023-03-18 01:54:43 +00002539Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2540 const ui::Transform& screenToDisplay) {
2541 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2542 // frame and transform used for the layer, which determines the bounds and the coordinate space
2543 // within which the layer will receive input.
2544
2545 // Coordinate space definitions:
2546 // - display: The display device's coordinate space. Correlates to pixels on the display.
2547 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2548 // - layer: The coordinate space of this layer.
2549 // - input: The coordinate space in which this layer will receive input events. This could be
2550 // different than layer space if a surfaceInset is used, which changes the origin
2551 // of the input space.
2552
2553 // Crop the input bounds to ensure it is within the parent's bounds.
2554 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2555 const ui::Transform layerToScreen = getInputTransform();
2556 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2557 return Rect{layerToDisplay.transform(croppedInputBounds)};
2558}
2559
chaviwaf87b3e2019-10-01 16:59:28 -07002560sp<Layer> Layer::getClonedRoot() {
2561 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002562 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002563 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002564 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002565 return nullptr;
2566 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002567 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002568}
2569
Robert Carredd13602020-04-13 17:24:34 -07002570bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002571 return mDrawingState.inputInfo.token != nullptr ||
2572 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002573}
2574
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002575compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002576 const DisplayDevice* display) const {
2577 if (!display) return nullptr;
Lloyd Pique30db6402023-06-26 18:56:51 +00002578 if (!mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00002579 return display->getCompositionDisplay()->getOutputLayerForLayer(
2580 getCompositionEngineLayerFE());
2581 }
2582 sp<LayerFE> layerFE;
2583 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2584 for (auto& [p, layer] : mLayerFEs) {
2585 if (p == path) {
2586 layerFE = layer;
2587 }
2588 }
2589
2590 if (!layerFE) return nullptr;
2591 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002592}
2593
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002594compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
2595 const DisplayDevice* display, const frontend::LayerHierarchy::TraversalPath& path) const {
2596 if (!display) return nullptr;
Vishnu Naire9ee0002023-07-01 03:14:51 +00002597 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2598 return display->getCompositionDisplay()->getOutputLayerForLayer(
2599 getCompositionEngineLayerFE());
2600 }
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002601 sp<LayerFE> layerFE;
2602 for (auto& [p, layer] : mLayerFEs) {
2603 if (p == path) {
2604 layerFE = layer;
2605 }
2606 }
2607
2608 if (!layerFE) return nullptr;
2609 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
2610}
2611
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002612Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2613 const auto outputLayer = findOutputLayerForDisplay(display);
2614 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002615}
2616
Patrick Williamsbb25f802022-08-30 23:02:34 +00002617void Layer::updateCloneBufferInfo() {
2618 if (!isClone() || !isClonedFromAlive()) {
2619 return;
2620 }
2621
2622 sp<Layer> clonedFrom = getClonedFrom();
2623 mBufferInfo = clonedFrom->mBufferInfo;
2624 mSidebandStream = clonedFrom->mSidebandStream;
2625 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2626 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2627 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2628
2629 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2630 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2631 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2632 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2633 // the cloned drawingState again.
2634 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2635 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2636 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2637 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2638
2639 cloneDrawingState(clonedFrom.get());
2640
2641 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2642 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2643 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2644 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002645}
chaviw74b03172019-08-19 11:09:03 -07002646
Vishnu Nair3be61902023-04-26 19:47:29 -07002647bool Layer::updateMirrorInfo(const std::deque<Layer*>& cloneRootsPendingUpdates) {
chaviw74b03172019-08-19 11:09:03 -07002648 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2649 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2650 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2651 // that case, we want to delete the reference to the clone since we want it to get
2652 // destroyed. The root, this layer, will still be around since the client can continue
2653 // to hold a reference, but no cloned layers will be displayed.
2654 mClonedChild = nullptr;
Vishnu Nair3be61902023-04-26 19:47:29 -07002655 return true;
chaviw74b03172019-08-19 11:09:03 -07002656 }
2657
2658 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2659 // If the real layer exists and is in current state, add the clone as a child of the root.
2660 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2661 // copied to drawingState for the root layer. So the clonedChild is always removed from
2662 // drawingState and then needs to be added back each traversal.
2663 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2664 addChildToDrawing(mClonedChild);
2665 }
2666
2667 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002668 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002669 mClonedChild->updateClonedRelatives(clonedLayersMap);
Vishnu Nair3be61902023-04-26 19:47:29 -07002670
2671 for (Layer* root : cloneRootsPendingUpdates) {
2672 if (clonedLayersMap.find(sp<Layer>::fromExisting(root)) != clonedLayersMap.end()) {
2673 return false;
2674 }
2675 }
2676 return true;
chaviw74b03172019-08-19 11:09:03 -07002677}
2678
2679void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2680 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2681 // to the clone. If the real layer is no longer alive, continue traversing the children
2682 // since we may be able to pull out other children that are still alive.
2683 if (isClonedFromAlive()) {
2684 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002685 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002686 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002687 }
2688
2689 // The clone layer may have children in drawingState since they may have been created and
2690 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2691 // that already exist, since we can just re-use them.
2692 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2693 // not updated in the regular traversal. They are skipped since the root will lose the
2694 // reference to them when it copies its currentChildren to drawing.
2695 for (sp<Layer>& child : mDrawingChildren) {
2696 child->updateClonedDrawingState(clonedLayersMap);
2697 }
2698}
2699
2700void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2701 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2702 mDrawingChildren.clear();
2703
2704 if (!isClonedFromAlive()) {
2705 return;
2706 }
2707
2708 sp<Layer> clonedFrom = getClonedFrom();
2709 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2710 if (child == mirrorRoot) {
2711 // This is to avoid cyclical mirroring.
2712 continue;
2713 }
2714 sp<Layer> clonedChild = clonedLayersMap[child];
2715 if (clonedChild == nullptr) {
Melody Hsu12ecd082024-04-17 19:03:13 +00002716 clonedChild = child->createClone();
chaviw74b03172019-08-19 11:09:03 -07002717 clonedLayersMap[child] = clonedChild;
2718 }
2719 addChildToDrawing(clonedChild);
2720 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2721 }
2722}
2723
chaviwaf87b3e2019-10-01 16:59:28 -07002724void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2725 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2726 if (cropLayer != nullptr) {
2727 if (clonedLayersMap.count(cropLayer) == 0) {
2728 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2729 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002730 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002731 } else {
2732 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2733 mDrawingState.touchableRegionCrop = clonedCropLayer;
2734 }
2735 }
2736 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2737 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002738 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002739}
2740
2741void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002742 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002743 mDrawingState.zOrderRelatives.clear();
2744
2745 if (!isClonedFromAlive()) {
2746 return;
2747 }
2748
chaviwaf87b3e2019-10-01 16:59:28 -07002749 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002750 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002751 const sp<Layer>& relative = relativeWeak.promote();
2752 if (clonedLayersMap.count(relative) > 0) {
2753 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002754 mDrawingState.zOrderRelatives.add(clonedRelative);
2755 }
2756 }
2757
2758 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2759 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2760 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2761 // still traverse the children, but the layer with the missing relativeOf will not be shown
2762 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002763 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2764 if (clonedLayersMap.count(relativeOf) > 0) {
2765 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002766 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2767 }
2768
chaviwaf87b3e2019-10-01 16:59:28 -07002769 updateClonedInputInfo(clonedLayersMap);
2770
chaviw74b03172019-08-19 11:09:03 -07002771 for (sp<Layer>& child : mDrawingChildren) {
2772 child->updateClonedRelatives(clonedLayersMap);
2773 }
2774}
2775
2776void Layer::addChildToDrawing(const sp<Layer>& layer) {
2777 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002778 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002779}
2780
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002781bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002782 const State& s(mDrawingState);
2783 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2784 return true;
2785 }
2786
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002787 sp<Layer> parent = mDrawingParent.promote();
2788 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002789}
2790
Robert Carr6a0382d2021-07-01 15:57:17 -07002791void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2792 mClonedChild = clonedChild;
2793 mHadClonedChild = true;
Vishnu Nair3be61902023-04-26 19:47:29 -07002794 mFlinger->mLayerMirrorRoots.push_back(this);
Robert Carr6a0382d2021-07-01 15:57:17 -07002795}
2796
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002797bool Layer::setDropInputMode(gui::DropInputMode mode) {
2798 if (mDrawingState.dropInputMode == mode) {
2799 return false;
2800 }
2801 mDrawingState.dropInputMode = mode;
2802 return true;
2803}
2804
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002805void Layer::cloneDrawingState(const Layer* from) {
2806 mDrawingState = from->mDrawingState;
2807 // Skip callback info since they are not applicable for cloned layers.
2808 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002809 // TODO (b/238781169) currently broken for mirror layers because we do not
2810 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002811 mDrawingState.callbackHandles = {};
2812}
2813
Patrick Williamsbb25f802022-08-30 23:02:34 +00002814void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2815 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002816 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002817 if (!listener) {
2818 return;
2819 }
2820 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002821 uint32_t currentMaxAcquiredBufferCount =
2822 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002823 listener->onReleaseBuffer({buffer->getId(), framenumber},
2824 releaseFence ? releaseFence : Fence::NO_FENCE,
2825 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002826}
2827
Melody Hsu793f8362024-01-08 20:00:35 +00002828sp<CallbackHandle> Layer::findCallbackHandle() {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002829 // If we are displayed on multiple displays in a single composition cycle then we would
2830 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2831 // For example we can only use it if all the displays are client comp, and we need
2832 // to merge all the client comp fences. We could do this, but for now we just
2833 // disable the optimization when a layer is composed on multiple displays.
2834 if (mClearClientCompositionFenceOnLayerDisplayed) {
2835 mLastClientCompositionFence = nullptr;
2836 } else {
2837 mClearClientCompositionFenceOnLayerDisplayed = true;
2838 }
2839
2840 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2841 // buffer that was presented on this layer. The first transaction that came in this frame that
2842 // replaced the previous buffer on this layer needs this release fence, because the fence will
2843 // let the client know when that previous buffer is removed from the screen.
2844 //
2845 // Every other transaction on this layer does not need a release fence because no other
2846 // Transactions that were set on this layer this frame are going to have their preceding buffer
2847 // removed from the display this frame.
2848 //
2849 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2850 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2851 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2852 // the previous buffer will be released this frame. The third transaction also contains a
2853 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2854 // transaction will now no longer be presented so it is released immediately and the third
2855 // transaction doesn't need a previous release fence.
2856 sp<CallbackHandle> ch;
2857 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002858 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002859 ch = handle;
2860 break;
2861 }
2862 }
Melody Hsu793f8362024-01-08 20:00:35 +00002863 return ch;
2864}
2865
2866void Layer::prepareReleaseCallbacks(ftl::Future<FenceResult> futureFenceResult,
2867 ui::LayerStack layerStack) {
2868 sp<CallbackHandle> ch = findCallbackHandle();
2869
2870 if (ch != nullptr) {
2871 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2872 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2873 ch->name = mName;
2874 } else {
Melody Hsue4ef87f2024-03-26 23:54:45 +00002875 // If we didn't get a release callback yet (e.g. some scenarios when capturing
2876 // screenshots asynchronously) then make sure we don't drop the fence.
2877 // Older fences for the same layer stack can be dropped when a new fence arrives.
2878 // An assumption here is that RenderEngine performs work sequentially, so an
2879 // incoming fence will not fire before an existing fence.
2880 mAdditionalPreviousReleaseFences.emplace_or_replace(layerStack,
2881 std::move(futureFenceResult));
Melody Hsu793f8362024-01-08 20:00:35 +00002882 }
2883
2884 if (mBufferInfo.mBuffer) {
2885 mPreviouslyPresentedLayerStacks.push_back(layerStack);
2886 }
2887
2888 if (mDrawingState.frameNumber > 0) {
2889 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
2890 }
2891}
2892
2893void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
2894 ui::LayerStack layerStack,
2895 std::function<FenceResult(FenceResult)>&& continuation) {
2896 sp<CallbackHandle> ch = findCallbackHandle();
Alec Mouri9892aac2023-12-11 21:16:59 +00002897
2898 if (!FlagManager::getInstance().screenshot_fence_preservation() && continuation) {
2899 futureFenceResult = ftl::Future(futureFenceResult).then(std::move(continuation)).share();
2900 }
2901
Patrick Williamsbb25f802022-08-30 23:02:34 +00002902 if (ch != nullptr) {
2903 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
Melody Hsu793f8362024-01-08 20:00:35 +00002904 ch->previousSharedReleaseFences.emplace_back(std::move(futureFenceResult));
Patrick Williamsbb25f802022-08-30 23:02:34 +00002905 ch->name = mName;
Alec Mouri9892aac2023-12-11 21:16:59 +00002906 } else if (FlagManager::getInstance().screenshot_fence_preservation()) {
2907 // If we didn't get a release callback yet, e.g. some scenarios when capturing screenshots
2908 // asynchronously, then make sure we don't drop the fence.
Melody Hsu793f8362024-01-08 20:00:35 +00002909 mPreviousReleaseFenceAndContinuations.emplace_back(std::move(futureFenceResult),
2910 std::move(continuation));
Alec Mouri9892aac2023-12-11 21:16:59 +00002911 std::vector<FenceAndContinuation> mergedFences;
2912 sp<Fence> prevFence = nullptr;
2913 // For a layer that's frequently screenshotted, try to merge fences to make sure we don't
2914 // grow unbounded.
Melody Hsu793f8362024-01-08 20:00:35 +00002915 for (const auto& futureAndContinuation : mPreviousReleaseFenceAndContinuations) {
2916 auto result = futureAndContinuation.future.wait_for(0s);
Alec Mouri9892aac2023-12-11 21:16:59 +00002917 if (result != std::future_status::ready) {
Melody Hsu793f8362024-01-08 20:00:35 +00002918 mergedFences.emplace_back(futureAndContinuation);
Alec Mouri9892aac2023-12-11 21:16:59 +00002919 continue;
2920 }
2921
Melody Hsu793f8362024-01-08 20:00:35 +00002922 mergeFence(getDebugName(),
2923 futureAndContinuation.chain().get().value_or(Fence::NO_FENCE), prevFence);
Alec Mouri9892aac2023-12-11 21:16:59 +00002924 }
2925 if (prevFence != nullptr) {
2926 mergedFences.emplace_back(ftl::yield(FenceResult(std::move(prevFence))).share());
2927 }
2928
Melody Hsu793f8362024-01-08 20:00:35 +00002929 mPreviousReleaseFenceAndContinuations.swap(mergedFences);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002930 }
Alec Mouri9892aac2023-12-11 21:16:59 +00002931
Vishnu Nair316b7f42023-10-13 23:44:46 +00002932 if (mBufferInfo.mBuffer) {
2933 mPreviouslyPresentedLayerStacks.push_back(layerStack);
2934 }
Alec Mouri21d94322023-10-17 19:51:39 +00002935
2936 if (mDrawingState.frameNumber > 0) {
2937 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
2938 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002939}
2940
2941void Layer::onSurfaceFrameCreated(
2942 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2943 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2944 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2945 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2946 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002947 if (hasBufferOrSidebandStreamInDrawing()) {
2948 // Only log for layers with a buffer, since we expect the jank data to be drained for
2949 // these, while there may be no jank listeners for bufferless layers.
2950 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2951 mName.c_str());
2952 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2953 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2954 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002955 mPendingJankClassifications.pop_front();
2956 }
2957 mPendingJankClassifications.emplace_back(surfaceFrame);
2958}
2959
2960void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2961 for (const auto& handle : mDrawingState.callbackHandles) {
Melody Hsu9af30702024-04-17 18:23:43 +00002962 handle->transformHint = mTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002963 handle->dequeueReadyTime = dequeueReadyTime;
2964 handle->currentMaxAcquiredBufferCount =
2965 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2966 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2967 handle->previousReleaseCallbackId.framenumber);
2968 }
2969
2970 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002971 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002972 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2973 break;
2974 }
2975 }
2976
2977 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002978 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002979 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2980 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002981 mDrawingState.callbackHandles = {};
2982}
2983
2984bool Layer::willPresentCurrentTransaction() const {
2985 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2986 return (getSidebandStreamChanged() || getAutoRefresh() ||
2987 (mDrawingState.modified &&
2988 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2989}
2990
2991bool Layer::setTransform(uint32_t transform) {
2992 if (mDrawingState.bufferTransform == transform) return false;
2993 mDrawingState.bufferTransform = transform;
2994 mDrawingState.modified = true;
2995 setTransactionFlags(eTransactionNeeded);
2996 return true;
2997}
2998
2999bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
3000 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
3001 mDrawingState.sequence++;
3002 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
3003 mDrawingState.modified = true;
3004 setTransactionFlags(eTransactionNeeded);
3005 return true;
3006}
3007
3008bool Layer::setBufferCrop(const Rect& bufferCrop) {
3009 if (mDrawingState.bufferCrop == bufferCrop) return false;
3010
3011 mDrawingState.sequence++;
3012 mDrawingState.bufferCrop = bufferCrop;
3013
3014 mDrawingState.modified = true;
3015 setTransactionFlags(eTransactionNeeded);
3016 return true;
3017}
3018
3019bool Layer::setDestinationFrame(const Rect& destinationFrame) {
3020 if (mDrawingState.destinationFrame == destinationFrame) return false;
3021
3022 mDrawingState.sequence++;
3023 mDrawingState.destinationFrame = destinationFrame;
3024
3025 mDrawingState.modified = true;
3026 setTransactionFlags(eTransactionNeeded);
3027 return true;
3028}
3029
3030// Translate destination frame into scale and position. If a destination frame is not set, use the
3031// provided scale and position
3032bool Layer::updateGeometry() {
3033 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
3034 mDrawingState.destinationFrame.isEmpty()) {
3035 // If destination frame is not set, use the requested transform set via
3036 // Layer::setPosition and Layer::setMatrix.
3037 return assignTransform(&mDrawingState.transform, mRequestedTransform);
3038 }
3039
3040 Rect destRect = mDrawingState.destinationFrame;
3041 int32_t destW = destRect.width();
3042 int32_t destH = destRect.height();
3043 if (destRect.left < 0) {
3044 destRect.left = 0;
3045 destRect.right = destW;
3046 }
3047 if (destRect.top < 0) {
3048 destRect.top = 0;
3049 destRect.bottom = destH;
3050 }
3051
3052 if (!mDrawingState.buffer) {
3053 ui::Transform t;
3054 t.set(destRect.left, destRect.top);
3055 return assignTransform(&mDrawingState.transform, t);
3056 }
3057
3058 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3059 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3060 // Undo any transformations on the buffer.
3061 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3062 std::swap(bufferWidth, bufferHeight);
3063 }
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003064 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003065 if (mDrawingState.transformToDisplayInverse) {
3066 if (invTransform & ui::Transform::ROT_90) {
3067 std::swap(bufferWidth, bufferHeight);
3068 }
3069 }
3070
3071 float sx = destW / static_cast<float>(bufferWidth);
3072 float sy = destH / static_cast<float>(bufferHeight);
3073 ui::Transform t;
3074 t.set(sx, 0, 0, sy);
3075 t.set(destRect.left, destRect.top);
3076 return assignTransform(&mDrawingState.transform, t);
3077}
3078
3079bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3080 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3081 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3082 return false;
3083 }
3084
3085 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3086
3087 mDrawingState.sequence++;
3088 mDrawingState.modified = true;
3089 setTransactionFlags(eTransactionNeeded);
3090
3091 return true;
3092}
3093
3094bool Layer::setPosition(float x, float y) {
3095 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3096 return false;
3097 }
3098
3099 mRequestedTransform.set(x, y);
3100
3101 mDrawingState.sequence++;
3102 mDrawingState.modified = true;
3103 setTransactionFlags(eTransactionNeeded);
3104
3105 return true;
3106}
3107
Dorin Drimuse5374e52023-08-02 17:52:43 +00003108void Layer::releasePreviousBuffer() {
3109 mReleasePreviousBuffer = true;
3110 if (!mBufferInfo.mBuffer ||
3111 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3112 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3113 // If mDrawingState has a buffer, and we are about to update again
3114 // before swapping to drawing state, then the first buffer will be
3115 // dropped and we should decrement the pending buffer count and
3116 // call any release buffer callbacks if set.
3117 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3118 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3119 mDrawingState.acquireFence);
3120 decrementPendingBufferCount();
3121 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3122 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3123 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX, systemTime());
3124 mDrawingState.bufferSurfaceFrameTX.reset();
3125 }
3126 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3127 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3128 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3129 mLastClientCompositionFence);
3130 mLastClientCompositionFence = nullptr;
3131 }
3132}
3133
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003134void Layer::resetDrawingStateBufferInfo() {
3135 mDrawingState.producerId = 0;
3136 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +00003137 mDrawingState.previousFrameNumber = 0;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003138 mDrawingState.releaseBufferListener = nullptr;
3139 mDrawingState.buffer = nullptr;
3140 mDrawingState.acquireFence = sp<Fence>::make(-1);
3141 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3142 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3143 mDrawingState.releaseBufferEndpoint = nullptr;
3144}
3145
Patrick Williamsbb25f802022-08-30 23:02:34 +00003146bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3147 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3148 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003149 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003150 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003151
3152 const bool frameNumberChanged =
3153 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3154 const uint64_t frameNumber =
3155 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003156 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003157
3158 if (mDrawingState.buffer) {
Dorin Drimuse5374e52023-08-02 17:52:43 +00003159 releasePreviousBuffer();
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003160 } else if (buffer) {
Vishnu Nairc09c0232023-03-02 03:22:35 +00003161 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3162 // we don't want to incorrectly classify a frame if we miss the desired present time.
3163 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003164 }
3165
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003166 mDrawingState.desiredPresentTime = desiredPresentTime;
3167 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3168 mDrawingState.latchedVsyncId = info.vsyncId;
Ady Abraham55269162023-05-09 11:26:06 -07003169 mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003170 mDrawingState.modified = true;
3171 if (!buffer) {
3172 resetDrawingStateBufferInfo();
3173 setTransactionFlags(eTransactionNeeded);
3174 mDrawingState.bufferSurfaceFrameTX = nullptr;
3175 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3176 return true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003177 } else {
3178 // release sideband stream if it exists and a non null buffer is being set
3179 if (mDrawingState.sidebandStream != nullptr) {
Dorin Drimus66ed1c42023-09-27 13:10:16 +00003180 setSidebandStream(nullptr, info, postTime);
Dorin Drimuse5374e52023-08-02 17:52:43 +00003181 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003182 }
3183
Vishnu Naird1f74982023-06-15 20:16:51 -07003184 if ((mDrawingState.producerId > bufferData.producerId) ||
3185 ((mDrawingState.producerId == bufferData.producerId) &&
3186 (mDrawingState.frameNumber > frameNumber))) {
3187 ALOGE("Out of order buffers detected for %s producedId=%d frameNumber=%" PRIu64
3188 " -> producedId=%d frameNumber=%" PRIu64,
3189 getDebugName(), mDrawingState.producerId, mDrawingState.frameNumber,
3190 bufferData.producerId, frameNumber);
3191 TransactionTraceWriter::getInstance().invoke("out_of_order_buffers_", /*overwrite=*/false);
3192 }
3193
liulijuneb489f62022-10-17 22:02:14 +08003194 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -07003195 mDrawingState.barrierProducerId =
3196 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003197 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -07003198 mDrawingState.barrierFrameNumber =
3199 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
3200
Patrick Williamsbb25f802022-08-30 23:02:34 +00003201 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3202 mDrawingState.buffer = std::move(buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003203 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3204 ? bufferData.acquireFence
3205 : Fence::NO_FENCE;
3206 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3207 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3208 // We latched this buffer unsiganled, so we need to pass the acquire fence
3209 // on the callback instead of just the acquire time, since it's unknown at
3210 // this point.
3211 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3212 } else {
3213 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3214 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003215 setTransactionFlags(eTransactionNeeded);
3216
3217 const int32_t layerId = getSequence();
3218 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3219 mOwnerUid, postTime, getGameMode());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003220
Lloyd Pique30db6402023-06-26 18:56:51 +00003221 if (mFlinger->mLegacyFrontEndEnabled) {
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003222 recordLayerHistoryBufferUpdate(getLayerProps(), systemTime());
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003223 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003224
3225 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3226
3227 if (dequeueTime && *dequeueTime != 0) {
3228 const uint64_t bufferId = mDrawingState.buffer->getId();
3229 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3230 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3231 FrameTracer::FrameEvent::DEQUEUE);
3232 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3233 FrameTracer::FrameEvent::QUEUE);
3234 }
3235
3236 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
Arthur Hungc70bee22023-06-02 01:35:52 +00003237
3238 // If the layer had been updated a TextureView, this would make sure the present time could be
3239 // same to TextureView update when it's a small dirty, and get the correct heuristic rate.
Jerry Chang36678002023-11-29 16:56:17 +00003240 if (mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00003241 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3242 mUsedVsyncIdForRefreshRateSelection = true;
3243 }
3244 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003245 return true;
3246}
3247
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003248void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3249 mDrawingState.desiredPresentTime = desiredPresentTime;
3250 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3251}
3252
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003253void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps, nsecs_t now) {
Ady Abraham55269162023-05-09 11:26:06 -07003254 ATRACE_CALL();
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003255 const nsecs_t presentTime = [&] {
Ady Abraham55269162023-05-09 11:26:06 -07003256 if (!mDrawingState.isAutoTimestamp) {
3257 ATRACE_FORMAT_INSTANT("desiredPresentTime");
3258 return mDrawingState.desiredPresentTime;
3259 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003260
Ady Abraham55269162023-05-09 11:26:06 -07003261 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3262 const auto prediction =
3263 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3264 mDrawingState.latchedVsyncId);
3265 if (prediction.has_value()) {
3266 ATRACE_FORMAT_INSTANT("predictedPresentTime");
Arthur Hungc70bee22023-06-02 01:35:52 +00003267 mMaxTimeForUseVsyncId = prediction->presentTime +
3268 scheduler::LayerHistory::kMaxPeriodForHistory.count();
Ady Abraham55269162023-05-09 11:26:06 -07003269 return prediction->presentTime;
3270 }
3271 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003272
Jerry Chang36678002023-11-29 16:56:17 +00003273 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00003274 return static_cast<nsecs_t>(0);
3275 }
3276
3277 // If the layer is not an application and didn't set an explicit rate or desiredPresentTime,
3278 // return "0" to tell the layer history that it will use the max refresh rate without
3279 // calculating the adaptive rate.
3280 if (mWindowType != WindowInfo::Type::APPLICATION &&
3281 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
3282 return static_cast<nsecs_t>(0);
3283 }
3284
3285 // Return the valid present time only when the layer potentially updated a TextureView so
3286 // LayerHistory could heuristically calculate the rate if the UI is continually updating.
3287 if (mUsedVsyncIdForRefreshRateSelection) {
3288 const auto prediction =
3289 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3290 mDrawingState.latchedVsyncId);
3291 if (prediction.has_value()) {
3292 if (mMaxTimeForUseVsyncId >= prediction->presentTime) {
3293 return prediction->presentTime;
3294 }
3295 mUsedVsyncIdForRefreshRateSelection = false;
3296 }
3297 }
3298
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003299 return static_cast<nsecs_t>(0);
3300 }();
Ady Abraham55269162023-05-09 11:26:06 -07003301
3302 if (ATRACE_ENABLED() && presentTime > 0) {
3303 const auto presentIn = TimePoint::fromNs(presentTime) - TimePoint::now();
3304 ATRACE_FORMAT_INSTANT("presentIn %s", to_string(presentIn).c_str());
3305 }
3306
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003307 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003308 scheduler::LayerHistory::LayerUpdateType::Buffer);
3309}
3310
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003311void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps, nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003312 const nsecs_t presentTime =
3313 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003314 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003315 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3316}
3317
Patrick Williamsbb25f802022-08-30 23:02:34 +00003318bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003319 if (mDrawingState.dataspace == dataspace) return false;
3320 mDrawingState.dataspace = dataspace;
3321 mDrawingState.modified = true;
3322 setTransactionFlags(eTransactionNeeded);
3323 return true;
3324}
3325
John Reck68796592023-01-25 13:47:12 -05003326bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07003327 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3328 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05003329 return false;
Sally Qi963049b2023-03-23 14:06:21 -07003330 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3331 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05003332 mDrawingState.modified = true;
3333 setTransactionFlags(eTransactionNeeded);
3334 return true;
3335}
3336
Alec Mouri1b0d4e12024-02-12 22:27:19 +00003337bool Layer::setDesiredHdrHeadroom(float desiredRatio) {
3338 if (mDrawingState.desiredHdrSdrRatio == desiredRatio) return false;
3339 mDrawingState.desiredHdrSdrRatio = desiredRatio;
3340 mDrawingState.modified = true;
3341 setTransactionFlags(eTransactionNeeded);
3342 return true;
3343}
3344
Alec Mourif4af03e2023-02-11 00:25:24 +00003345bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3346 if (mDrawingState.cachingHint == cachingHint) return false;
3347 mDrawingState.cachingHint = cachingHint;
3348 mDrawingState.modified = true;
3349 setTransactionFlags(eTransactionNeeded);
3350 return true;
3351}
3352
Patrick Williamsbb25f802022-08-30 23:02:34 +00003353bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3354 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3355 mDrawingState.hdrMetadata = hdrMetadata;
3356 mDrawingState.modified = true;
3357 setTransactionFlags(eTransactionNeeded);
3358 return true;
3359}
3360
3361bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003362 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003363 mDrawingState.surfaceDamageRegion = surfaceDamage;
3364 mDrawingState.modified = true;
3365 setTransactionFlags(eTransactionNeeded);
Arthur Hung69f95222023-10-04 07:39:02 +00003366 setIsSmallDirty(surfaceDamage, getTransform());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003367 return true;
3368}
3369
3370bool Layer::setApi(int32_t api) {
3371 if (mDrawingState.api == api) return false;
3372 mDrawingState.api = api;
3373 mDrawingState.modified = true;
3374 setTransactionFlags(eTransactionNeeded);
3375 return true;
3376}
3377
Dorin Drimuse5374e52023-08-02 17:52:43 +00003378bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream, const FrameTimelineInfo& info,
3379 nsecs_t postTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003380 if (mDrawingState.sidebandStream == sidebandStream) return false;
3381
3382 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3383 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3384 } else if (sidebandStream != nullptr) {
3385 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3386 }
3387
3388 mDrawingState.sidebandStream = sidebandStream;
3389 mDrawingState.modified = true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003390 if (sidebandStream != nullptr && mDrawingState.buffer != nullptr) {
3391 releasePreviousBuffer();
3392 resetDrawingStateBufferInfo();
3393 mDrawingState.bufferSurfaceFrameTX = nullptr;
3394 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3395 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003396 setTransactionFlags(eTransactionNeeded);
3397 if (!mSidebandStreamChanged.exchange(true)) {
3398 // mSidebandStreamChanged was false
3399 mFlinger->onLayerUpdate();
3400 }
3401 return true;
3402}
3403
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003404bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3405 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003406 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3407 if (handles.empty()) {
3408 mReleasePreviousBuffer = false;
3409 return false;
3410 }
3411
Pascal Muetschard81cef292023-02-06 12:18:52 +01003412 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003413 for (const auto& handle : handles) {
3414 // If this transaction set a buffer on this layer, release its previous buffer
3415 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3416
3417 // If this layer will be presented in this frame
3418 if (willPresent) {
3419 // If this transaction set an acquire fence on this layer, set its acquire time
3420 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3421 handle->frameNumber = mDrawingState.frameNumber;
Alec Mouri21d94322023-10-17 19:51:39 +00003422 handle->previousFrameNumber = mDrawingState.previousFrameNumber;
Melody Hsu793f8362024-01-08 20:00:35 +00003423 if (FlagManager::getInstance().ce_fence_promise() &&
Alec Mouri9892aac2023-12-11 21:16:59 +00003424 mPreviousReleaseBufferEndpoint == handle->listener) {
Melody Hsue4ef87f2024-03-26 23:54:45 +00003425 // Add fence from previous screenshot now so that it can be dispatched to the
Alec Mouri9892aac2023-12-11 21:16:59 +00003426 // client.
Melody Hsue4ef87f2024-03-26 23:54:45 +00003427 for (auto& [_, future] : mAdditionalPreviousReleaseFences) {
3428 handle->previousReleaseFences.emplace_back(std::move(future));
Alec Mouri9892aac2023-12-11 21:16:59 +00003429 }
3430 mAdditionalPreviousReleaseFences.clear();
Melody Hsu793f8362024-01-08 20:00:35 +00003431 } else if (FlagManager::getInstance().screenshot_fence_preservation() &&
3432 mPreviousReleaseBufferEndpoint == handle->listener) {
3433 // Add fences from previous screenshots now so that they can be dispatched to the
3434 // client.
3435 for (const auto& futureAndContinution : mPreviousReleaseFenceAndContinuations) {
3436 handle->previousSharedReleaseFences.emplace_back(futureAndContinution.chain());
3437 }
3438 mPreviousReleaseFenceAndContinuations.clear();
Alec Mouri9892aac2023-12-11 21:16:59 +00003439 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003440 // Store so latched time and release fence can be set
3441 mDrawingState.callbackHandles.push_back(handle);
3442
3443 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003444 // Queue this handle to be notified below.
3445 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003446 }
3447 }
3448
Pascal Muetschard81cef292023-02-06 12:18:52 +01003449 if (!remainingHandles.empty()) {
3450 // Notify the transaction completed threads these handles are done. These are only the
3451 // handles that were not added to the mDrawingState, which will be notified later.
3452 std::vector<JankData> jankData;
3453 transferAvailableJankData(remainingHandles, jankData);
3454 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3455 }
3456
Patrick Williamsbb25f802022-08-30 23:02:34 +00003457 mReleasePreviousBuffer = false;
3458 mCallbackHandleAcquireTimeOrFence = -1;
3459
3460 return willPresent;
3461}
3462
3463Rect Layer::getBufferSize(const State& /*s*/) const {
3464 // for buffer state layers we use the display frame size as the buffer size.
3465
3466 if (mBufferInfo.mBuffer == nullptr) {
3467 return Rect::INVALID_RECT;
3468 }
3469
3470 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3471 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3472
3473 // Undo any transformations on the buffer and return the result.
3474 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3475 std::swap(bufWidth, bufHeight);
3476 }
3477
3478 if (getTransformToDisplayInverse()) {
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003479 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003480 if (invTransform & ui::Transform::ROT_90) {
3481 std::swap(bufWidth, bufHeight);
3482 }
3483 }
3484
3485 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3486}
3487
3488FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3489 if (mBufferInfo.mBuffer == nullptr) {
3490 return parentBounds;
3491 }
3492
3493 return getBufferSize(getDrawingState()).toFloatRect();
3494}
3495
3496bool Layer::fenceHasSignaled() const {
3497 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3498 return true;
3499 }
3500
3501 const bool fenceSignaled =
3502 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3503 if (!fenceSignaled) {
3504 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3505 TimeStats::LatchSkipReason::LateAcquire);
3506 }
3507
3508 return fenceSignaled;
3509}
3510
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003511void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003512 for (const auto& handle : mDrawingState.callbackHandles) {
3513 handle->refreshStartTime = refreshStartTime;
3514 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003515}
3516
3517void Layer::setAutoRefresh(bool autoRefresh) {
3518 mDrawingState.autoRefresh = autoRefresh;
3519}
3520
3521bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3522 // 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 +00003523 auto* snapshot = editLayerSnapshot();
3524 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003525
3526 if (mSidebandStreamChanged.exchange(false)) {
3527 const State& s(getDrawingState());
3528 // mSidebandStreamChanged was true
3529 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003530 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003531 if (mSidebandStream != nullptr) {
3532 setTransactionFlags(eTransactionNeeded);
3533 mFlinger->setTransactionFlags(eTraversalNeeded);
3534 }
3535 recomputeVisibleRegions = true;
3536
3537 return true;
3538 }
3539 return false;
3540}
3541
3542bool Layer::hasFrameUpdate() const {
3543 const State& c(getDrawingState());
3544 return (mDrawingStateModified || mDrawingState.modified) &&
3545 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3546}
3547
Vishnu Naird47bcee2023-02-24 18:08:51 +00003548void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003549 const State& s(getDrawingState());
3550
3551 if (!s.buffer) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003552 if (bgColorOnly || mBufferInfo.mBuffer) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003553 for (auto& handle : mDrawingState.callbackHandles) {
3554 handle->latchTime = latchTime;
3555 }
3556 }
3557 return;
3558 }
3559
3560 for (auto& handle : mDrawingState.callbackHandles) {
3561 if (handle->frameNumber == mDrawingState.frameNumber) {
3562 handle->latchTime = latchTime;
3563 }
3564 }
3565
3566 const int32_t layerId = getSequence();
3567 const uint64_t bufferId = mDrawingState.buffer->getId();
3568 const uint64_t frameNumber = mDrawingState.frameNumber;
3569 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3570 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3571 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3572
3573 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3574 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3575 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3576 FrameTracer::FrameEvent::LATCH);
3577
3578 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3579 if (bufferSurfaceFrame != nullptr &&
3580 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3581 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3582 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3583 // are processing the next state.
3584 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3585 mDrawingState.acquireFenceTime->getSignalTime(),
3586 latchTime);
3587 mDrawingState.bufferSurfaceFrameTX.reset();
3588 }
3589
3590 std::deque<sp<CallbackHandle>> remainingHandles;
3591 mFlinger->getTransactionCallbackInvoker()
3592 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3593 mDrawingState.callbackHandles = remainingHandles;
3594
3595 mDrawingStateModified = false;
3596}
3597
3598void Layer::gatherBufferInfo() {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003599 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3600 mPreviousReleaseBufferEndpoint = mBufferInfo.mReleaseBufferEndpoint;
3601 if (!mDrawingState.buffer) {
3602 mBufferInfo = {};
3603 return;
3604 }
3605
3606 if ((!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer))) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003607 decrementPendingBufferCount();
3608 }
3609
Patrick Williamsbb25f802022-08-30 23:02:34 +00003610 mBufferInfo.mBuffer = mDrawingState.buffer;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003611 mBufferInfo.mReleaseBufferEndpoint = mDrawingState.releaseBufferEndpoint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003612 mBufferInfo.mFence = mDrawingState.acquireFence;
3613 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3614 mBufferInfo.mPixelFormat =
3615 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3616 mBufferInfo.mFrameLatencyNeeded = true;
3617 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3618 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3619 mBufferInfo.mFence = mDrawingState.acquireFence;
3620 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3621 auto lastDataspace = mBufferInfo.mDataspace;
3622 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003623 if (mBufferInfo.mBuffer != nullptr) {
3624 auto& mapper = GraphicBufferMapper::get();
3625 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
3626 // and don't need to possibly remaps buffers.
3627 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
3628 status_t err = OK;
3629 {
3630 ATRACE_NAME("getDataspace");
3631 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
3632 }
3633 if (err != OK || dataspace != mBufferInfo.mDataspace) {
3634 {
3635 ATRACE_NAME("setDataspace");
3636 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
3637 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
3638 }
3639
3640 // Some GPU drivers may cache gralloc metadata which means before we composite we need
3641 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
3642 // compatible with old vendors, with a ticking clock.
3643 static const int32_t kVendorVersion =
Alec Mouri8a06fb72023-11-16 22:07:13 +00003644 base::GetIntProperty("ro.board.api_level", __ANDROID_API_FUTURE__);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003645 if (const auto format =
3646 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
3647 mBufferInfo.mBuffer->getPixelFormat());
3648 err == OK && kVendorVersion < __ANDROID_API_U__ &&
3649 (format ==
3650 aidl::android::hardware::graphics::common::PixelFormat::
3651 IMPLEMENTATION_DEFINED ||
3652 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
3653 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
3654 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
3655 mBufferInfo.mBuffer->remapBuffer();
3656 }
3657 }
3658 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003659 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003660 mFlinger->mHdrLayerInfoChanged = true;
3661 }
Sally Qi963049b2023-03-23 14:06:21 -07003662 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3663 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05003664 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003665 }
3666 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3667 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3668 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3669 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3670 mBufferInfo.mApi = mDrawingState.api;
3671 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003672}
3673
3674Rect Layer::computeBufferCrop(const State& s) {
3675 if (s.buffer && !s.bufferCrop.isEmpty()) {
3676 Rect bufferCrop;
3677 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3678 return bufferCrop;
3679 } else if (s.buffer) {
3680 return s.buffer->getBounds();
3681 } else {
3682 return s.bufferCrop;
3683 }
3684}
3685
Melody Hsu12ecd082024-04-17 19:03:13 +00003686sp<Layer> Layer::createClone() {
Kean Mariotti4ba343c2023-04-19 13:31:02 +00003687 surfaceflinger::LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0,
3688 LayerMetadata());
Patrick Williams83f36b22022-09-14 17:57:35 +00003689 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003690 return layer;
3691}
3692
Patrick Williamsbb25f802022-08-30 23:02:34 +00003693void Layer::decrementPendingBufferCount() {
3694 int32_t pendingBuffers = --mPendingBufferTransactions;
3695 tracePendingBufferCount(pendingBuffers);
3696}
3697
3698void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3699 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3700}
3701
3702/*
3703 * We don't want to send the layer's transform to input, but rather the
3704 * parent's transform. This is because Layer's transform is
3705 * information about how the buffer is placed on screen. The parent's
3706 * transform makes more sense to send since it's information about how the
3707 * layer is placed on screen. This transform is used by input to determine
3708 * how to go from screen space back to window space.
3709 */
3710ui::Transform Layer::getInputTransform() const {
3711 if (!hasBufferOrSidebandStream()) {
3712 return getTransform();
3713 }
3714 sp<Layer> parent = mDrawingParent.promote();
3715 if (parent == nullptr) {
3716 return ui::Transform();
3717 }
3718
3719 return parent->getTransform();
3720}
3721
3722/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003723 * Returns the bounds used to fill the input frame and the touchable region.
3724 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003725 * Similar to getInputTransform, we need to update the bounds to include the transform.
3726 * This is because bounds don't include the buffer transform, where the input assumes
3727 * that's already included.
3728 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003729std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3730 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3731 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3732 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3733 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3734 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003735 }
3736
Vishnu Nairfed7c122023-03-18 01:54:43 +00003737 bool inputBoundsValid = croppedBufferSize.isValid();
3738 if (!inputBoundsValid) {
3739 /**
3740 * Input bounds are based on the layer crop or buffer size. But if we are using
3741 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3742 * we can use the parent bounds as the input bounds if the layer does not have buffer
3743 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3744 * use the parent bounds. A layer without a buffer can get input. So when a window is
3745 * initially added, its touchable region can fill its parent layer bounds and that can
3746 * have negative consequences.
3747 */
3748 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003749 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003750
3751 // Clamp surface inset to the input bounds.
3752 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3753 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3754 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3755
3756 // Apply the insets to the input bounds.
3757 inputBounds.left += xSurfaceInset;
3758 inputBounds.top += ySurfaceInset;
3759 inputBounds.right -= xSurfaceInset;
3760 inputBounds.bottom -= ySurfaceInset;
3761
3762 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003763}
3764
Ady Abraham005398b2023-06-05 13:59:41 -07003765bool Layer::isSimpleBufferUpdate(const layer_state_t& s) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003766 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3767
3768 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3769 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3770 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
Ady Abrahambb1ad762024-03-27 18:31:28 -07003771 layer_state_t::eLayerStackChanged | layer_state_t::eReparent |
3772 (FlagManager::getInstance().latch_unsignaled_with_auto_refresh_changed()
3773 ? 0
3774 : layer_state_t::eAutoRefreshChanged);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003775
Patrick Williamsbb25f802022-08-30 23:02:34 +00003776 if ((s.what & requiredFlags) != requiredFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003777 ATRACE_FORMAT_INSTANT("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3778 (s.what | requiredFlags) & ~s.what);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003779 return false;
3780 }
3781
3782 if (s.what & deniedFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003783 ATRACE_FORMAT_INSTANT("%s: false [has denied flags 0x%" PRIx64 "]", __func__,
3784 s.what & deniedFlags);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003785 return false;
3786 }
3787
Patrick Williamsbb25f802022-08-30 23:02:34 +00003788 if (s.what & layer_state_t::ePositionChanged) {
3789 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
Ady Abraham005398b2023-06-05 13:59:41 -07003790 ATRACE_FORMAT_INSTANT("%s: false [ePositionChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003791 return false;
3792 }
3793 }
3794
3795 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003796 if (mDrawingState.color.a != s.color.a) {
Ady Abraham005398b2023-06-05 13:59:41 -07003797 ATRACE_FORMAT_INSTANT("%s: false [eAlphaChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003798 return false;
3799 }
3800 }
3801
3802 if (s.what & layer_state_t::eColorTransformChanged) {
3803 if (mDrawingState.colorTransform != s.colorTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003804 ATRACE_FORMAT_INSTANT("%s: false [eColorTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003805 return false;
3806 }
3807 }
3808
3809 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003810 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Ady Abraham005398b2023-06-05 13:59:41 -07003811 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundColorChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003812 return false;
3813 }
3814 }
3815
3816 if (s.what & layer_state_t::eMatrixChanged) {
3817 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3818 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3819 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3820 mRequestedTransform.dsdy() != s.matrix.dsdy) {
Ady Abraham005398b2023-06-05 13:59:41 -07003821 ATRACE_FORMAT_INSTANT("%s: false [eMatrixChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003822 return false;
3823 }
3824 }
3825
3826 if (s.what & layer_state_t::eCornerRadiusChanged) {
3827 if (mDrawingState.cornerRadius != s.cornerRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003828 ATRACE_FORMAT_INSTANT("%s: false [eCornerRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003829 return false;
3830 }
3831 }
3832
3833 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3834 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
Ady Abraham005398b2023-06-05 13:59:41 -07003835 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003836 return false;
3837 }
3838 }
3839
Vishnu Nairbbceb462022-10-10 04:52:13 +00003840 if (s.what & layer_state_t::eBufferTransformChanged) {
3841 if (mDrawingState.bufferTransform != s.bufferTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003842 ATRACE_FORMAT_INSTANT("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003843 return false;
3844 }
3845 }
3846
3847 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3848 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
Ady Abraham005398b2023-06-05 13:59:41 -07003849 ATRACE_FORMAT_INSTANT("%s: false [eTransformToDisplayInverseChanged changed]",
3850 __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003851 return false;
3852 }
3853 }
3854
3855 if (s.what & layer_state_t::eCropChanged) {
3856 if (mDrawingState.crop != s.crop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003857 ATRACE_FORMAT_INSTANT("%s: false [eCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003858 return false;
3859 }
3860 }
3861
3862 if (s.what & layer_state_t::eDataspaceChanged) {
3863 if (mDrawingState.dataspace != s.dataspace) {
Ady Abraham005398b2023-06-05 13:59:41 -07003864 ATRACE_FORMAT_INSTANT("%s: false [eDataspaceChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003865 return false;
3866 }
3867 }
3868
3869 if (s.what & layer_state_t::eHdrMetadataChanged) {
3870 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
Ady Abraham005398b2023-06-05 13:59:41 -07003871 ATRACE_FORMAT_INSTANT("%s: false [eHdrMetadataChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003872 return false;
3873 }
3874 }
3875
3876 if (s.what & layer_state_t::eSidebandStreamChanged) {
3877 if (mDrawingState.sidebandStream != s.sidebandStream) {
Ady Abraham005398b2023-06-05 13:59:41 -07003878 ATRACE_FORMAT_INSTANT("%s: false [eSidebandStreamChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003879 return false;
3880 }
3881 }
3882
3883 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3884 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
Ady Abraham005398b2023-06-05 13:59:41 -07003885 ATRACE_FORMAT_INSTANT("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003886 return false;
3887 }
3888 }
3889
3890 if (s.what & layer_state_t::eShadowRadiusChanged) {
3891 if (mDrawingState.shadowRadius != s.shadowRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003892 ATRACE_FORMAT_INSTANT("%s: false [eShadowRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003893 return false;
3894 }
3895 }
3896
3897 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3898 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
Ady Abraham005398b2023-06-05 13:59:41 -07003899 ATRACE_FORMAT_INSTANT("%s: false [eFixedTransformHintChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003900 return false;
3901 }
3902 }
3903
3904 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3905 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
Ady Abraham005398b2023-06-05 13:59:41 -07003906 ATRACE_FORMAT_INSTANT("%s: false [eTrustedOverlayChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003907 return false;
3908 }
3909 }
3910
3911 if (s.what & layer_state_t::eStretchChanged) {
3912 StretchEffect temp = s.stretchEffect;
3913 temp.sanitize();
3914 if (mDrawingState.stretchEffect != temp) {
Ady Abraham005398b2023-06-05 13:59:41 -07003915 ATRACE_FORMAT_INSTANT("%s: false [eStretchChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003916 return false;
3917 }
3918 }
3919
3920 if (s.what & layer_state_t::eBufferCropChanged) {
3921 if (mDrawingState.bufferCrop != s.bufferCrop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003922 ATRACE_FORMAT_INSTANT("%s: false [eBufferCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003923 return false;
3924 }
3925 }
3926
3927 if (s.what & layer_state_t::eDestinationFrameChanged) {
3928 if (mDrawingState.destinationFrame != s.destinationFrame) {
Ady Abraham005398b2023-06-05 13:59:41 -07003929 ATRACE_FORMAT_INSTANT("%s: false [eDestinationFrameChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003930 return false;
3931 }
3932 }
3933
3934 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3935 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
Ady Abraham005398b2023-06-05 13:59:41 -07003936 ATRACE_FORMAT_INSTANT("%s: false [eDimmingEnabledChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003937 return false;
3938 }
3939 }
3940
John Reck68796592023-01-25 13:47:12 -05003941 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07003942 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
3943 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
Ady Abraham005398b2023-06-05 13:59:41 -07003944 ATRACE_FORMAT_INSTANT("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05003945 return false;
3946 }
3947 }
3948
Alec Mouri1b0d4e12024-02-12 22:27:19 +00003949 if (s.what & layer_state_t::eDesiredHdrHeadroomChanged) {
3950 if (mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
3951 ATRACE_FORMAT_INSTANT("%s: false [eDesiredHdrHeadroomChanged changed]", __func__);
3952 return false;
3953 }
3954 }
3955
Patrick Williamsbb25f802022-08-30 23:02:34 +00003956 return true;
3957}
3958
Vishnu Naire14c6b32022-08-06 04:20:15 +00003959sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003960 // 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 +00003961 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003962}
3963
Vishnu Naire14c6b32022-08-06 04:20:15 +00003964const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003965 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003966}
3967
Vishnu Naire14c6b32022-08-06 04:20:15 +00003968LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003969 return mSnapshot.get();
3970}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003971
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003972std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3973 return std::move(mSnapshot);
3974}
3975
3976void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3977 mSnapshot = std::move(snapshot);
3978}
3979
Patrick Williamsbb25f802022-08-30 23:02:34 +00003980const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003981 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003982}
3983
Patrick Williams7584c6a2022-10-29 02:10:58 +00003984sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003985 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003986 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3987 return result;
3988}
3989
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003990sp<LayerFE> Layer::getCompositionEngineLayerFE(
3991 const frontend::LayerHierarchy::TraversalPath& path) {
3992 for (auto& [p, layerFE] : mLayerFEs) {
3993 if (p == path) {
3994 return layerFE;
3995 }
3996 }
3997 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3998 mLayerFEs.emplace_back(path, layerFE);
3999 return layerFE;
4000}
4001
Patrick Williamsbb25f802022-08-30 23:02:34 +00004002void Layer::useSurfaceDamage() {
4003 if (mFlinger->mForceFullDamage) {
4004 surfaceDamageRegion = Region::INVALID_REGION;
4005 } else {
4006 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
4007 }
4008}
4009
4010void Layer::useEmptyDamage() {
4011 surfaceDamageRegion.clear();
4012}
4013
4014bool Layer::isOpaque(const Layer::State& s) const {
4015 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
4016 // layer's opaque flag.
4017 if (!hasSomethingToDraw()) {
4018 return false;
4019 }
4020
4021 // if the layer has the opaque flag, then we're always opaque
4022 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
4023 return true;
4024 }
4025
4026 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004027 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004028 return true;
4029 }
4030
4031 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
4032 return fillsColor() && getAlpha() == 1.0_hf;
4033}
4034
4035bool Layer::canReceiveInput() const {
4036 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
4037}
4038
4039bool Layer::isVisible() const {
4040 if (!hasSomethingToDraw()) {
4041 return false;
4042 }
4043
4044 if (isHiddenByPolicy()) {
4045 return false;
4046 }
4047
4048 return getAlpha() > 0.0f || hasBlur();
4049}
4050
Leon Scroggins III5b581492023-10-31 14:29:41 -04004051void Layer::onCompositionPresented(const DisplayDevice* display,
4052 const std::shared_ptr<FenceTime>& glDoneFence,
4053 const std::shared_ptr<FenceTime>& presentFence,
4054 const CompositorTiming& compositorTiming) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004055 // mFrameLatencyNeeded is true when a new frame was latched for the
4056 // composition.
4057 if (!mBufferInfo.mFrameLatencyNeeded) return;
4058
4059 for (const auto& handle : mDrawingState.callbackHandles) {
4060 handle->gpuCompositionDoneFence = glDoneFence;
4061 handle->compositorTiming = compositorTiming;
4062 }
4063
4064 // Update mFrameTracker.
4065 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
4066 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
4067
4068 const int32_t layerId = getSequence();
4069 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
4070
4071 const auto outputLayer = findOutputLayerForDisplay(display);
4072 if (outputLayer && outputLayer->requiresClientComposition()) {
4073 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
4074 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4075 clientCompositionTimestamp,
4076 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
4077 // Update the SurfaceFrames in the drawing state
4078 if (mDrawingState.bufferSurfaceFrameTX) {
4079 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
4080 }
4081 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
4082 surfaceFrame->setGpuComposition();
4083 }
4084 }
4085
4086 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
4087 if (frameReadyFence->isValid()) {
4088 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
4089 } else {
4090 // There was no fence for this frame, so assume that it was ready
4091 // to be presented at the desired present time.
4092 mFrameTracker.setFrameReadyTime(desiredPresentTime);
4093 }
4094
4095 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08004096 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004097 const std::optional<Fps> renderRate =
4098 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
4099
Alec Mouri7c1d8b52023-08-29 20:14:46 +00004100 const auto vote = frameRateToSetFrameRateVotePayload(getFrameRateForLayerTree());
Patrick Williamsbb25f802022-08-30 23:02:34 +00004101 const auto gameMode = getGameMode();
4102
4103 if (presentFence->isValid()) {
4104 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
4105 refreshRate, renderRate, vote, gameMode);
4106 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4107 presentFence,
4108 FrameTracer::FrameEvent::PRESENT_FENCE);
4109 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
4110 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
4111 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04004112 // The HWC doesn't support present fences, so use the present timestamp instead.
4113 const nsecs_t presentTimestamp =
4114 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
4115
4116 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
4117 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
4118 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
4119
Patrick Williamsbb25f802022-08-30 23:02:34 +00004120 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
4121 refreshRate, renderRate, vote, gameMode);
4122 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
4123 mCurrentFrameNumber, actualPresentTime,
4124 FrameTracer::FrameEvent::PRESENT_FENCE);
4125 mFrameTracker.setActualPresentTime(actualPresentTime);
4126 }
4127 }
4128
4129 mFrameTracker.advanceFrame();
4130 mBufferInfo.mFrameLatencyNeeded = false;
4131}
4132
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004133bool Layer::willReleaseBufferOnLatch() const {
4134 return !mDrawingState.buffer && mBufferInfo.mBuffer;
4135}
4136
Patrick Williamsbb25f802022-08-30 23:02:34 +00004137bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00004138 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
4139 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
4140}
4141
4142bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004143 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
4144 getDrawingState().frameNumber);
4145
4146 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
4147
4148 if (refreshRequired) {
4149 return refreshRequired;
4150 }
4151
4152 // If the head buffer's acquire fence hasn't signaled yet, return and
4153 // try again later
4154 if (!fenceHasSignaled()) {
4155 ATRACE_NAME("!fenceHasSignaled()");
4156 mFlinger->onLayerUpdate();
4157 return false;
4158 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00004159 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004160
4161 // Capture the old state of the layer for comparisons later
4162 BufferInfo oldBufferInfo = mBufferInfo;
4163 const bool oldOpacity = isOpaque(mDrawingState);
4164 mPreviousFrameNumber = mCurrentFrameNumber;
4165 mCurrentFrameNumber = mDrawingState.frameNumber;
4166 gatherBufferInfo();
4167
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004168 if (mBufferInfo.mBuffer) {
4169 // We latched a buffer that will be presented soon. Clear the previously presented layer
4170 // stack list.
4171 mPreviouslyPresentedLayerStacks.clear();
4172 }
4173
4174 if (mDrawingState.buffer == nullptr) {
4175 const bool bufferReleased = oldBufferInfo.mBuffer != nullptr;
4176 recomputeVisibleRegions = bufferReleased;
4177 return bufferReleased;
4178 }
4179
Patrick Williamsbb25f802022-08-30 23:02:34 +00004180 if (oldBufferInfo.mBuffer == nullptr) {
4181 // the first time we receive a buffer, we need to trigger a
4182 // geometry invalidation.
4183 recomputeVisibleRegions = true;
4184 }
4185
4186 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
4187 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
4188 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
4189 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
4190 recomputeVisibleRegions = true;
4191 }
4192
4193 if (oldBufferInfo.mBuffer != nullptr) {
4194 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
4195 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
4196 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
4197 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
4198 recomputeVisibleRegions = true;
4199 }
4200 }
4201
4202 if (oldOpacity != isOpaque(mDrawingState)) {
4203 recomputeVisibleRegions = true;
4204 }
4205
4206 return true;
4207}
4208
4209bool Layer::hasReadyFrame() const {
4210 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4211}
4212
4213bool Layer::isProtected() const {
4214 return (mBufferInfo.mBuffer != nullptr) &&
4215 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4216}
4217
Patrick Williamsbb25f802022-08-30 23:02:34 +00004218void Layer::latchAndReleaseBuffer() {
4219 if (hasReadyFrame()) {
4220 bool ignored = false;
4221 latchBuffer(ignored, systemTime());
4222 }
4223 releasePendingBuffer(systemTime());
4224}
4225
4226PixelFormat Layer::getPixelFormat() const {
4227 return mBufferInfo.mPixelFormat;
4228}
4229
4230bool Layer::getTransformToDisplayInverse() const {
4231 return mBufferInfo.mTransformToDisplayInverse;
4232}
4233
4234Rect Layer::getBufferCrop() const {
4235 // this is the crop rectangle that applies to the buffer
4236 // itself (as opposed to the window)
4237 if (!mBufferInfo.mCrop.isEmpty()) {
4238 // if the buffer crop is defined, we use that
4239 return mBufferInfo.mCrop;
4240 } else if (mBufferInfo.mBuffer != nullptr) {
4241 // otherwise we use the whole buffer
4242 return mBufferInfo.mBuffer->getBounds();
4243 } else {
4244 // if we don't have a buffer yet, we use an empty/invalid crop
4245 return Rect();
4246 }
4247}
4248
4249uint32_t Layer::getBufferTransform() const {
4250 return mBufferInfo.mTransform;
4251}
4252
4253ui::Dataspace Layer::getDataSpace() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004254 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4255}
4256
Alec Mouri89f5d4e2023-10-20 17:12:49 +00004257bool Layer::isFrontBuffered() const {
4258 if (mBufferInfo.mBuffer == nullptr) {
4259 return false;
4260 }
4261
4262 return mBufferInfo.mBuffer->getUsage() & AHARDWAREBUFFER_USAGE_FRONT_BUFFER;
4263}
4264
Patrick Williamsbb25f802022-08-30 23:02:34 +00004265ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4266 ui::Dataspace updatedDataspace = dataspace;
4267 // translate legacy dataspaces to modern dataspaces
4268 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00004269 // Treat unknown dataspaces as V0_sRGB
4270 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00004271 case ui::Dataspace::SRGB:
4272 updatedDataspace = ui::Dataspace::V0_SRGB;
4273 break;
4274 case ui::Dataspace::SRGB_LINEAR:
4275 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4276 break;
4277 case ui::Dataspace::JFIF:
4278 updatedDataspace = ui::Dataspace::V0_JFIF;
4279 break;
4280 case ui::Dataspace::BT601_625:
4281 updatedDataspace = ui::Dataspace::V0_BT601_625;
4282 break;
4283 case ui::Dataspace::BT601_525:
4284 updatedDataspace = ui::Dataspace::V0_BT601_525;
4285 break;
4286 case ui::Dataspace::BT709:
4287 updatedDataspace = ui::Dataspace::V0_BT709;
4288 break;
4289 default:
4290 break;
4291 }
4292
4293 return updatedDataspace;
4294}
4295
4296sp<GraphicBuffer> Layer::getBuffer() const {
4297 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4298}
4299
Vishnu Nairb76d99a2023-03-19 18:22:31 -07004300void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4301 mTransformHintLegacy = getFixedTransformHint();
4302 if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4303 mTransformHintLegacy = displayTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004304 }
4305}
4306
4307const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4308 return mBufferInfo.mBuffer;
4309}
4310
4311bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004312 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004313 return false;
4314 }
4315
4316 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004317 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004318 mDrawingState.modified = true;
4319 setTransactionFlags(eTransactionNeeded);
4320 return true;
4321}
4322
4323bool Layer::fillsColor() const {
4324 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4325 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4326}
4327
4328bool Layer::hasBlur() const {
4329 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4330}
4331
Vishnu Nairba354102022-08-01 00:14:18 +00004332void Layer::updateSnapshot(bool updateGeometry) {
4333 if (!getCompositionEngineLayerFE()) {
4334 return;
4335 }
4336
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004337 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004338 if (updateGeometry) {
4339 prepareBasicGeometryCompositionState();
4340 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004341 snapshot->roundedCorner = getRoundedCornerState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004342 snapshot->transformedBounds = mScreenBounds;
4343 if (mEffectiveShadowRadius > 0.f) {
4344 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4345
4346 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4347 // it if transparent regions are present. This may not be necessary since shadows are
4348 // typically cast by layers without transparent regions.
4349 snapshot->shadowSettings.boundaries = mBounds;
4350
4351 const float casterAlpha = snapshot->alpha;
4352 const bool casterIsOpaque =
4353 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4354
4355 // If the casting layer is translucent, we need to fill in the shadow underneath the
4356 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4357 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4358 snapshot->shadowSettings.ambientColor *= casterAlpha;
4359 snapshot->shadowSettings.spotColor *= casterAlpha;
4360 }
4361 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004362 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004363 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004364 snapshot->layerOpaqueFlagSet =
4365 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004366 sp<Layer> p = mDrawingParent.promote();
4367 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004368 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004369 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004370 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004371 }
4372 snapshot->bufferSize = getBufferSize(mDrawingState);
4373 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004374 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004375 preparePerFrameCompositionState();
4376}
4377
Vishnu Naire14c6b32022-08-06 04:20:15 +00004378void Layer::updateChildrenSnapshots(bool updateGeometry) {
4379 for (const sp<Layer>& child : mDrawingChildren) {
4380 child->updateSnapshot(updateGeometry);
4381 child->updateChildrenSnapshots(updateGeometry);
4382 }
4383}
4384
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004385void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4386 mSnapshot->layerMetadata = parentMetadata;
4387 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4388 for (const sp<Layer>& child : mDrawingChildren) {
4389 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4390 }
4391}
4392
4393void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4394 std::unordered_set<Layer*>& visited) {
4395 if (visited.find(this) != visited.end()) {
4396 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4397 return;
4398 }
4399 visited.insert(this);
4400
4401 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4402
4403 if (mDrawingState.zOrderRelatives.empty()) {
4404 return;
4405 }
4406 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4407 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4408 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4409 sp<Layer> relative = weakRelative.promote();
4410 if (!relative) {
4411 continue;
4412 }
4413 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4414 }
4415}
4416
Chavi Weingarten328a8312023-01-26 21:17:52 +00004417bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004418 TrustedPresentationListener const& listener) {
4419 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4420 mTrustedPresentationListener = listener;
4421 mTrustedPresentationThresholds = thresholds;
4422 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4423 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4424 mFlinger->mNumTrustedPresentationListeners++;
4425 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4426 mFlinger->mNumTrustedPresentationListeners--;
4427 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004428
4429 // Reset trusted presentation states to ensure we start the time again.
4430 mEnteredTrustedPresentationStateTime = -1;
4431 mLastReportedTrustedPresentationState = false;
4432 mLastComputedTrustedPresentationState = false;
4433
4434 // If there's a new trusted presentation listener, the code needs to go through the composite
4435 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4436 // we're already in the requested state.
4437 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004438}
4439
Vishnu Naira156f482023-02-22 00:23:38 +00004440void Layer::updateLastLatchTime(nsecs_t latchTime) {
4441 mLastLatchTime = latchTime;
4442}
4443
Arthur Hung69f95222023-10-04 07:39:02 +00004444void Layer::setIsSmallDirty(const Region& damageRegion,
4445 const ui::Transform& layerToDisplayTransform) {
4446 mSmallDirty = false;
Jerry Chang36678002023-11-29 16:56:17 +00004447 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00004448 return;
4449 }
4450
4451 if (mWindowType != WindowInfo::Type::APPLICATION &&
4452 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
4453 return;
4454 }
Arthur Hung69f95222023-10-04 07:39:02 +00004455
4456 Rect bounds = damageRegion.getBounds();
Arthur Hungc70bee22023-06-02 01:35:52 +00004457 if (!bounds.isValid()) {
4458 return;
4459 }
4460
Arthur Hung69f95222023-10-04 07:39:02 +00004461 // Transform to screen space.
4462 bounds = layerToDisplayTransform.transform(bounds);
4463
Arthur Hungc70bee22023-06-02 01:35:52 +00004464 // If the damage region is a small dirty, this could give the hint for the layer history that
4465 // it could suppress the heuristic rate when calculating.
Tony Huangf3621102023-09-04 17:14:22 +08004466 mSmallDirty = mFlinger->mScheduler->isSmallDirtyArea(mOwnerAppId,
Tony Huang9ac5e6e2023-08-24 09:01:44 +00004467 bounds.getWidth() * bounds.getHeight());
Arthur Hungc70bee22023-06-02 01:35:52 +00004468}
4469
Arthur Hung69f95222023-10-04 07:39:02 +00004470void Layer::setIsSmallDirty(frontend::LayerSnapshot* snapshot) {
4471 setIsSmallDirty(snapshot->surfaceDamage, snapshot->localTransform);
4472 snapshot->isSmallDirty = mSmallDirty;
4473}
4474
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004475} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004476
4477#if defined(__gl_h_)
4478#error "don't include gl/gl.h in this file"
4479#endif
4480
4481#if defined(__gl2_h_)
4482#error "don't include gl2/gl2.h in this file"
4483#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004484
4485// TODO(b/129481165): remove the #pragma below and fix conversion issues
4486#pragma clang diagnostic pop // ignored "-Wconversion"