blob: d27bfd29ef790e52cfae6fb6c9e17e045b509747 [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
Linnan Li13bf76a2024-05-05 19:18:02 +080093ui::LogicalDisplayId toLogicalDisplayId(const ui::LayerStack& layerStack) {
94 return ui::LogicalDisplayId{static_cast<int32_t>(layerStack.id)};
95}
96
Patrick Williamsbb25f802022-08-30 23:02:34 +000097bool assignTransform(ui::Transform* dst, ui::Transform& from) {
98 if (*dst == from) {
99 return false;
100 }
101 *dst = from;
102 return true;
103}
104
105TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
106 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
107 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
108 const auto frameRateCompatibility = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700109 switch (frameRate.vote.type) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000110 case Layer::FrameRateCompatibility::Default:
111 return FrameRateCompatibility::Default;
112 case Layer::FrameRateCompatibility::ExactOrMultiple:
113 return FrameRateCompatibility::ExactOrMultiple;
114 default:
115 return FrameRateCompatibility::Undefined;
116 }
117 }();
118
119 const auto seamlessness = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700120 switch (frameRate.vote.seamlessness) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000121 case scheduler::Seamlessness::OnlySeamless:
122 return Seamlessness::ShouldBeSeamless;
123 case scheduler::Seamlessness::SeamedAndSeamless:
124 return Seamlessness::NotRequired;
125 default:
126 return Seamlessness::Undefined;
127 }
128 }();
129
Rachel Leece6e0042023-06-27 11:22:54 -0700130 return TimeStats::SetFrameRateVote{.frameRate = frameRate.vote.rate.getValue(),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000131 .frameRateCompatibility = frameRateCompatibility,
132 .seamlessness = seamlessness};
133}
134
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100135} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800136
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700137using namespace ftl::flag_operators;
138
Yiwei Zhang5434a782018-12-05 18:06:32 -0800139using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000140using frontend::LayerSnapshot;
141using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800142using gui::GameMode;
143using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500144using gui::WindowInfo;
Vishnu Nair494a2e42023-11-10 17:21:19 -0800145using ui::Size;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800146
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700147using PresentState = frametimeline::SurfaceFrame::PresentState;
148
Kean Mariotti4ba343c2023-04-19 13:31:02 +0000149Layer::Layer(const surfaceflinger::LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000150 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700151 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000152 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700153 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800154 mWindowType(static_cast<WindowInfo::Type>(
155 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000156 mLayerCreationFlags(args.flags),
Lloyd Pique70ddc672024-04-30 18:20:40 -0700157 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName, this)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000158 ALOGV("Creating Layer %s", getDebugName());
159
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700160 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700161 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
162 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
163 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700164 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
165 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700166 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700167 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700168 mDrawingState.z = 0;
169 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700170 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700171 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700172 mDrawingState.transform.set(0, 0);
173 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +0000174 mDrawingState.previousFrameNumber = 0;
Vishnu Nair63221212023-04-06 15:17:37 -0700175 mDrawingState.barrierFrameNumber = 0;
176 mDrawingState.producerId = 0;
177 mDrawingState.barrierProducerId = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700178 mDrawingState.bufferTransform = 0;
179 mDrawingState.transformToDisplayInverse = false;
Robert Carr6a160312021-05-17 12:08:20 -0700180 mDrawingState.acquireFence = sp<Fence>::make(-1);
181 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
Alec Mouri74c7ae12023-03-26 02:57:47 +0000182 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Robert Carr6a160312021-05-17 12:08:20 -0700183 mDrawingState.hdrMetadata.validTypes = 0;
184 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
185 mDrawingState.cornerRadius = 0.0f;
186 mDrawingState.backgroundBlurRadius = 0;
187 mDrawingState.api = -1;
188 mDrawingState.hasColorTransform = false;
189 mDrawingState.colorSpaceAgnostic = false;
190 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
191 mDrawingState.metadata = args.metadata;
192 mDrawingState.shadowRadius = 0.f;
193 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
194 mDrawingState.frameTimelineInfo = {};
195 mDrawingState.postTime = -1;
196 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000197 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700198 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700199 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000200 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Rachel Lee70f7b692023-11-22 11:24:02 -0800201 mDrawingState.frameRateSelectionStrategy = FrameRateSelectionStrategy::Propagate;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700202
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700203 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
204 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700205 mDrawingState.color.r = -1.0_hf;
206 mDrawingState.color.g = -1.0_hf;
207 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700208 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700209
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500210 mFrameTracker.setDisplayRefreshPeriod(
211 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700212
Vishnu Naircb8be502022-10-12 19:03:23 +0000213 mOwnerUid = args.ownerUid;
214 mOwnerPid = args.ownerPid;
Tony Huangf3621102023-09-04 17:14:22 +0800215 mOwnerAppId = mOwnerUid % PER_USER_RANGE;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000216
217 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
218 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
219 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000220
221 mSnapshot->sequence = sequence;
222 mSnapshot->name = getDebugName();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000223 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000224 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800225}
226
227void Layer::onFirstRef() {
228 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700229}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700230
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700231Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000232 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
233 "Layer destructor called off the main thread.");
234
Patrick Williamsbb25f802022-08-30 23:02:34 +0000235 // The original layer and the clone layer share the same texture and buffer. Therefore, only
236 // one of the layers, in this case the original layer, needs to handle the deletion. The
237 // original layer and the clone should be removed at the same time so there shouldn't be any
238 // issue with the clone layer trying to use the texture.
239 if (mBufferInfo.mBuffer != nullptr) {
240 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
241 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800242 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000243 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000244 const int32_t layerId = getSequence();
245 mFlinger->mTimeStats->onDestroy(layerId);
246 mFlinger->mFrameTracer->onDestroy(layerId);
247
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000248 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700249 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700250
251 if (mDrawingState.sidebandStream != nullptr) {
252 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
253 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700254 if (mHadClonedChild) {
Vishnu Nair3be61902023-04-26 19:47:29 -0700255 auto& roots = mFlinger->mLayerMirrorRoots;
256 roots.erase(std::remove(roots.begin(), roots.end(), this), roots.end());
Robert Carr6a0382d2021-07-01 15:57:17 -0700257 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000258 if (hasTrustedPresentationListener()) {
259 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000260 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000261 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700262}
263
Mathias Agopian13127d82013-03-05 17:47:11 -0800264// ---------------------------------------------------------------------------
265// callbacks
266// ---------------------------------------------------------------------------
267
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700268void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700269 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700270 return;
271 }
Robert Carr2e102c92018-10-23 12:11:15 -0700272
Robert Carr6a160312021-05-17 12:08:20 -0700273 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700274 if (strongRelative == nullptr) {
275 setZOrderRelativeOf(nullptr);
276 return;
277 }
278
279 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700280 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700281 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800282 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700283 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700284}
285
286void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700287 if (!mRemovedFromDrawingState) {
288 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700289 mFlinger->mScheduler->deregisterLayer(this);
290 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000291 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000292
Ady Abrahamd11bade2022-08-01 16:18:03 -0700293 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700294}
Chia-I Wu38512252017-05-17 14:36:16 -0700295
chaviw68d4dab2020-06-08 15:07:32 -0700296sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000297 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700298 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700299 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700300 }
301 return parent->getRootLayer();
302}
303
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700304void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700305 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
306 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700307 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700308
Josh Gao194ff392022-09-08 16:19:29 -0700309 REQUIRE_MUTEX(mFlinger->mStateLock);
310 traverse(LayerVector::StateSet::Current,
311 [&](Layer* layer) REQUIRES(layer->mFlinger->mStateLock) {
312 layer->removeFromCurrentState();
313 layer->removeRelativeZ(layersInTree);
314 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700315}
316
chaviw61626f22018-11-15 16:26:27 -0800317void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700318 if (mRemovedFromDrawingState) {
319 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700320 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700321 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700322 }
chaviw61626f22018-11-15 16:26:27 -0800323
324 for (const auto& child : mCurrentChildren) {
325 child->addToCurrentState();
326 }
327}
328
Mathias Agopian13127d82013-03-05 17:47:11 -0800329// ---------------------------------------------------------------------------
330// set-up
331// ---------------------------------------------------------------------------
332
chaviw13fdc492017-06-27 12:40:18 -0700333bool Layer::getPremultipledAlpha() const {
334 return mPremultipliedAlpha;
335}
336
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700337sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800338 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700339 if (mGetHandleCalled) {
340 ALOGE("Get handle called twice" );
341 return nullptr;
342 }
343 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700344 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000345 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800346}
347
348// ---------------------------------------------------------------------------
349// h/w composer set-up
350// ---------------------------------------------------------------------------
351
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700352static Rect reduce(const Rect& win, const Region& exclude) {
353 if (CC_LIKELY(exclude.isEmpty())) {
354 return win;
355 }
356 if (exclude.isRect()) {
357 return win.reduce(exclude.getBounds());
358 }
359 return Region(win).subtract(exclude).getBounds();
360}
361
Dan Stoza80d61162017-12-20 15:57:52 -0800362static FloatRect reduce(const FloatRect& win, const Region& exclude) {
363 if (CC_LIKELY(exclude.isEmpty())) {
364 return win;
365 }
366 // Convert through Rect (by rounding) for lack of FloatRegion
367 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
368}
369
Vishnu Nair4351ad52019-02-11 14:13:02 -0800370Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800371 if (!reduceTransparentRegion) {
372 return Rect{mScreenBounds};
373 }
374
375 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800376 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800377 // Transform to screen space.
378 bounds = t.transform(bounds);
379 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700380}
381
Vishnu Nair4351ad52019-02-11 14:13:02 -0800382FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000383 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800384 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700385}
386
Vishnu Nairf0c28512019-02-08 12:40:28 -0800387FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
388 // Subtract the transparent region and snap to the bounds.
389 return reduce(mBounds, activeTransparentRegion);
390}
391
Chavi Weingarten076acac2023-01-19 17:20:43 +0000392// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000393void Layer::updateTrustedPresentationState(const DisplayDevice* display,
394 const frontend::LayerSnapshot* snapshot,
395 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000396 if (!hasTrustedPresentationListener()) {
397 return;
398 }
399 const bool lastState = mLastComputedTrustedPresentationState;
400 mLastComputedTrustedPresentationState = false;
401
402 if (!leaveState) {
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000403 const auto outputLayer = findOutputLayerForDisplay(display, snapshot->path);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000404 if (outputLayer != nullptr) {
405 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
406 Region coveredRegion =
407 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
408 mLastComputedTrustedPresentationState =
409 computeTrustedPresentationState(snapshot->geomLayerBounds,
410 snapshot->sourceBounds(), coveredRegion,
411 snapshot->transformedBounds,
412 snapshot->alpha,
413 snapshot->geomLayerTransform,
414 mTrustedPresentationThresholds);
415 } else {
416 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
417 "TrustedPresentationState",
418 getDebugName());
419 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000420 }
421 }
422 const bool newState = mLastComputedTrustedPresentationState;
423 if (lastState && !newState) {
424 // We were in the trusted presentation state, but now we left it,
425 // emit the callback if needed
426 if (mLastReportedTrustedPresentationState) {
427 mLastReportedTrustedPresentationState = false;
428 mTrustedPresentationListener.invoke(false);
429 }
430 // Reset the timer
431 mEnteredTrustedPresentationStateTime = -1;
432 } else if (!lastState && newState) {
433 // We were not in the trusted presentation state, but we entered it, begin the timer
434 // and make sure this gets called at least once more!
435 mEnteredTrustedPresentationStateTime = time_in_ms;
436 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
437 }
438
439 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
440 if (!mLastReportedTrustedPresentationState && newState &&
441 (time_in_ms - mEnteredTrustedPresentationStateTime >
442 mTrustedPresentationThresholds.stabilityRequirementMs)) {
443 mLastReportedTrustedPresentationState = true;
444 mTrustedPresentationListener.invoke(true);
445 }
446}
447
448/**
449 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
450 * of how the parameters and thresholds are interpreted. The general spirit is
451 * to produce an upper bound on the amount of the buffer which was presented.
452 */
453bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
454 const Region& coveredRegion,
455 const FloatRect& screenBounds, float alpha,
456 const ui::Transform& effectiveTransform,
457 const TrustedPresentationThresholds& thresholds) {
458 if (alpha < thresholds.minAlpha) {
459 return false;
460 }
461 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
462 return false;
463 }
464 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
465 return false;
466 }
467
468 const float sx = effectiveTransform.dsdx();
469 const float sy = effectiveTransform.dsdy();
470 float fractionRendered = std::min(sx * sy, 1.0f);
471
472 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
473 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
474 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
475
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000476 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
477 // Compute the size of all the rects since they may be disconnected.
478 float coveredSize = 0;
479 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
480 float size = rect->width() * rect->height();
481 coveredSize += size;
482 }
483
484 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000485
486 if (fractionRendered < thresholds.minFractionRendered) {
487 return false;
488 }
489
490 return true;
491}
492
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700493void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
494 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800495 const State& s(getDrawingState());
496
497 // Calculate effective layer transform
498 mEffectiveTransform = parentTransform * getActiveTransform(s);
499
Garfield Tan2c1782c2022-02-16 15:25:05 -0800500 if (CC_UNLIKELY(!isTransformValid())) {
501 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
502 getDebugName());
503 return;
504 }
505
Vishnu Nair4351ad52019-02-11 14:13:02 -0800506 // Transform parent bounds to layer space
507 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
508
Vishnu Nairc652ff82019-03-15 12:48:54 -0700509 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800510 mSourceBounds = computeSourceBounds(parentBounds);
511
512 // Calculate bounds by croping diplay frame with layer crop and parent bounds
513 FloatRect bounds = mSourceBounds;
514 const Rect layerCrop = getCrop(s);
515 if (!layerCrop.isEmpty()) {
516 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
517 }
518 bounds = bounds.intersect(parentBounds);
519
520 mBounds = bounds;
521 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700522
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700523 // Use the layer's own shadow radius if set. Otherwise get the radius from
524 // parent.
525 if (s.shadowRadius > 0.f) {
526 mEffectiveShadowRadius = s.shadowRadius;
527 } else {
528 mEffectiveShadowRadius = parentShadowRadius;
529 }
530
531 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
532 // don't pass it to its children.
533 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
534
Vishnu Nair4351ad52019-02-11 14:13:02 -0800535 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700536 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800537 }
Vishnu Nairba354102022-08-01 00:14:18 +0000538
539 if (mPotentialCursor) {
540 prepareCursorCompositionState();
541 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800542}
543
Vishnu Nair60356342018-11-13 13:00:45 -0800544Rect Layer::getCroppedBufferSize(const State& s) const {
545 Rect size = getBufferSize(s);
546 Rect crop = getCrop(s);
547 if (!crop.isEmpty() && size.isValid()) {
548 size.intersect(crop, &size);
549 } else if (!crop.isEmpty()) {
550 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700551 }
Vishnu Nair60356342018-11-13 13:00:45 -0800552 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800553}
554
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700555void Layer::setupRoundedCornersCropCoordinates(Rect win,
556 const FloatRect& roundedCornersCrop) const {
557 // Translate win by the rounded corners rect coordinates, to have all values in
558 // layer coordinate space.
559 win.left -= roundedCornersCrop.left;
560 win.right -= roundedCornersCrop.left;
561 win.top -= roundedCornersCrop.top;
562 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700563}
564
Lloyd Piquede196652020-01-22 17:29:58 -0800565void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800566 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800567 const auto alpha = static_cast<float>(getAlpha());
568 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700569 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800570
571 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
572 if (!opaque || alpha != 1.0f) {
573 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
574 : Hwc2::IComposerClient::BlendMode::COVERAGE;
575 }
576
Alec Mourif4af03e2023-02-11 00:25:24 +0000577 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000578 auto* snapshot = editLayerSnapshot();
579 snapshot->outputFilter = getOutputFilter();
580 snapshot->isVisible = isVisible();
581 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
Vishnu Naird9e4f462023-10-06 04:05:45 +0000582 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800583
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000584 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800585 contentDirty = false;
586
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000587 snapshot->geomLayerBounds = mBounds;
588 snapshot->geomLayerTransform = getTransform();
589 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
590 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000591 snapshot->localTransform = getActiveTransform(drawingState);
592 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000593 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
594 snapshot->alpha = alpha;
Vishnu Nairc6384702023-07-31 12:22:20 -0700595 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
596 snapshot->blurRegions = getBlurRegions();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000597 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800598}
599
Lloyd Piquede196652020-01-22 17:29:58 -0800600void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800601 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000602 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700603
Alec Mourif4af03e2023-02-11 00:25:24 +0000604 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000605 snapshot->geomBufferSize = getBufferSize(drawingState);
606 snapshot->geomContentCrop = getBufferCrop();
607 snapshot->geomCrop = getCrop(drawingState);
608 snapshot->geomBufferTransform = getBufferTransform();
609 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
610 snapshot->geomUsesSourceCrop = usesSourceCrop();
611 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800612
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000613 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800614 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
615 for (const auto& [key, mandatory] : supportedMetadata) {
616 const auto& genericLayerMetadataCompatibilityMap =
617 mFlinger->getGenericLayerMetadataKeyMap();
618 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
619 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
620 continue;
621 }
622 const uint32_t id = compatIter->second;
623
624 auto it = drawingState.metadata.mMap.find(id);
625 if (it == std::end(drawingState.metadata.mMap)) {
626 continue;
627 }
628
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000629 snapshot->metadata.emplace(key,
630 compositionengine::GenericLayerMetadataEntry{mandatory,
631 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800632 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800633}
David Sodmanba340492018-08-05 21:51:33 -0700634
Lloyd Piquede196652020-01-22 17:29:58 -0800635void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800636 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000637 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000638 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800639
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000640 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800641
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000642 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
643 snapshot->dataspace = getDataSpace();
644 snapshot->colorTransform = getColorTransform();
645 snapshot->colorTransformIsIdentity = !hasColorTransform();
646 snapshot->surfaceDamage = surfaceDamageRegion;
647 snapshot->hasProtectedContent = isProtected();
648 snapshot->dimmingEnabled = isDimmingEnabled();
Sally Qi963049b2023-03-23 14:06:21 -0700649 snapshot->currentHdrSdrRatio = getCurrentHdrSdrRatio();
650 snapshot->desiredHdrSdrRatio = getDesiredHdrSdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000651 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800652
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700653 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700654
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000655 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800656
657 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400658 // Rounded corners no longer force client composition, since we may use a
659 // hole punch so that the layer will appear to have rounded corners.
Alec Mouri994761f2023-08-04 21:50:55 +0000660 if (drawShadows() || snapshot->stretchEffect.hasEffect()) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000661 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800662 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700663 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairc6384702023-07-31 12:22:20 -0700664 snapshot->blurRegions = getBlurRegions();
665 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400666
667 // Layer framerate is used in caching decisions.
668 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
669 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000670 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000671
672 if (hasBufferOrSidebandStream()) {
673 preparePerFrameBufferCompositionState();
674 } else {
675 preparePerFrameEffectsCompositionState();
676 }
677}
678
679void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000680 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000681 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000682 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000683 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
684 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000685 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
686 return;
687 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000688 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000689 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800690 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
691 snapshot->compositionType =
692 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000693 } else {
694 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000695 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
696 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000697 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
698 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
699 }
700
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000701 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000702 snapshot->acquireFence = mBufferInfo.mFence;
703 snapshot->frameNumber = mBufferInfo.mFrameNumber;
704 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000705}
706
707void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000708 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000709 auto* snapshot = editLayerSnapshot();
710 snapshot->color = getColor();
711 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000712 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800713}
714
Lloyd Piquede196652020-01-22 17:29:58 -0800715void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800716 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000717 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000718 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800719
720 // Apply the layer's transform, followed by the display's global transform
721 // Here we're guaranteed that the layer's transform preserves rects
722 Rect win = getCroppedBufferSize(drawingState);
723 // Subtract the transparent region and snap to the bounds
724 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
725 Rect frame(getTransform().transform(bounds));
726
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000727 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800728}
729
Lloyd Piquea83776c2019-01-29 18:42:32 -0800730const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700731 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800732}
733
Mathias Agopian13127d82013-03-05 17:47:11 -0800734// ---------------------------------------------------------------------------
735// drawing...
736// ---------------------------------------------------------------------------
737
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500738aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
739 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700740 const auto outputLayer = findOutputLayerForDisplay(&display);
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000741 return getCompositionType(outputLayer);
742}
743
744aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
745 const compositionengine::OutputLayer* outputLayer) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -0800746 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500747 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800748 }
749 if (outputLayer->getState().hwc) {
750 return (*outputLayer->getState().hwc).hwcCompositionType;
751 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500752 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800753 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800754}
755
Mathias Agopian13127d82013-03-05 17:47:11 -0800756// ----------------------------------------------------------------------------
757// local state
758// ----------------------------------------------------------------------------
759
David Sodman41fdfc92017-11-06 16:09:56 -0800760bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800761 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700762 if (s.flags & layer_state_t::eLayerSecure) {
763 return true;
764 }
765
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000766 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700767 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700768}
769
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100770void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
771 std::vector<JankData>& jankData) {
772 if (mPendingJankClassifications.empty() ||
773 !mPendingJankClassifications.front()->getJankType()) {
774 return;
775 }
776
777 bool includeJankData = false;
778 for (const auto& handle : handles) {
779 for (const auto& cb : handle->callbackIds) {
780 if (cb.includeJankData) {
781 includeJankData = true;
782 break;
783 }
784 }
785
786 if (includeJankData) {
787 jankData.reserve(mPendingJankClassifications.size());
788 break;
789 }
790 }
791
792 while (!mPendingJankClassifications.empty() &&
793 mPendingJankClassifications.front()->getJankType()) {
794 if (includeJankData) {
795 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
796 mPendingJankClassifications.front();
Pascal Muetschardac7bcd92023-10-03 15:05:36 +0200797 jankData.emplace_back(JankData(surfaceFrame->getToken(),
798 surfaceFrame->getJankType().value(),
799 surfaceFrame->getRenderRate().getPeriodNsecs()));
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100800 }
801 mPendingJankClassifications.pop_front();
802 }
803}
804
Mathias Agopian13127d82013-03-05 17:47:11 -0800805// ----------------------------------------------------------------------------
806// transaction
807// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800808
Vishnu Naira156f482023-02-22 00:23:38 +0000809uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700810 ATRACE_CALL();
811
Robert Carr0758e5d2021-03-11 22:15:04 -0800812 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700813 mDrawingStateModified = mDrawingState.modified;
814 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700815
Alec Mourib416efd2018-09-06 21:01:59 +0000816 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700817
Robert Carr6a160312021-05-17 12:08:20 -0700818 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800819 // invalidate and recompute the visible regions if needed
820 flags |= Layer::eVisibleRegion;
821 }
822
Robert Carr6a160312021-05-17 12:08:20 -0700823 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800824 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000825 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800826 flags |= eVisibleRegion;
827 this->contentDirty = true;
828
829 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700830 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800831 }
832
Arthur Hung9ed43392022-05-27 06:31:57 +0000833 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
834 mFlinger->mUpdateInputInfo = true;
835 }
836
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700837 commitTransaction();
Robert Carra1257842020-01-31 13:48:28 -0800838
Mathias Agopian13127d82013-03-05 17:47:11 -0800839 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800840}
841
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700842void Layer::commitTransaction() {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000843 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
844 // bufferSurfaceFrameTX will be presented in latchBuffer.
845 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
846 if (surfaceFrame->getPresentState() != PresentState::Presented) {
847 // With applyPendingStates, we could end up having presented surfaceframes from previous
848 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800849 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000850 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
851 }
852 }
Robert Carr6a160312021-05-17 12:08:20 -0700853 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700854}
855
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700856uint32_t Layer::clearTransactionFlags(uint32_t mask) {
857 const auto flags = mTransactionFlags & mask;
858 mTransactionFlags &= ~mask;
859 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800860}
861
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700862void Layer::setTransactionFlags(uint32_t mask) {
863 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800864}
865
Robert Carr1f0a16a2016-10-24 16:27:39 -0700866bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
867 ssize_t idx = mCurrentChildren.indexOf(childLayer);
868 if (idx < 0) {
869 return false;
870 }
871 if (childLayer->setLayer(z)) {
872 mCurrentChildren.removeAt(idx);
873 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800874 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700875 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800876 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700877}
878
Robert Carr503c7042017-09-27 15:06:08 -0700879bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
880 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
881 ssize_t idx = mCurrentChildren.indexOf(childLayer);
882 if (idx < 0) {
883 return false;
884 }
885 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
886 mCurrentChildren.removeAt(idx);
887 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800888 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700889 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800890 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700891}
892
Robert Carrae060832016-11-28 10:51:00 -0800893bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700894 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
895 mDrawingState.sequence++;
896 mDrawingState.z = z;
897 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700898
Robert Carra70e91c2021-06-11 13:59:52 -0700899 mFlinger->mSomeChildrenChanged = true;
900
Robert Carrdb66e622017-04-10 16:55:57 -0700901 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700902 if (mDrawingState.zOrderRelativeOf != nullptr) {
903 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700904 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700905 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700906 }
chaviw606e5cf2019-03-01 10:12:10 -0800907 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700908 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800909 setTransactionFlags(eTransactionNeeded);
910 return true;
911}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700912
Robert Carrdb66e622017-04-10 16:55:57 -0700913void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700914 mDrawingState.zOrderRelatives.remove(relative);
915 mDrawingState.sequence++;
916 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700917 setTransactionFlags(eTransactionNeeded);
918}
919
920void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700921 mDrawingState.zOrderRelatives.add(relative);
922 mDrawingState.modified = true;
923 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700924 setTransactionFlags(eTransactionNeeded);
925}
926
chaviw606e5cf2019-03-01 10:12:10 -0800927void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700928 mDrawingState.zOrderRelativeOf = relativeOf;
929 mDrawingState.sequence++;
930 mDrawingState.modified = true;
931 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700932
chaviw606e5cf2019-03-01 10:12:10 -0800933 setTransactionFlags(eTransactionNeeded);
934}
935
Robert Carr503d2bd2017-12-04 15:49:47 -0800936bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000937 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700938 if (relative == nullptr) {
939 return false;
940 }
941
Robert Carr6a160312021-05-17 12:08:20 -0700942 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
943 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800944 return false;
945 }
946
Robert Carr88b85e12022-03-21 15:47:35 -0700947 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
948 (relative->mDrawingState.zOrderRelativeOf == this)) {
949 ALOGE("Detected relative layer loop between %s and %s",
950 mName.c_str(), relative->mName.c_str());
951 ALOGE("Ignoring new call to set relative layer");
952 return false;
953 }
954
Robert Carra70e91c2021-06-11 13:59:52 -0700955 mFlinger->mSomeChildrenChanged = true;
956
Robert Carr6a160312021-05-17 12:08:20 -0700957 mDrawingState.sequence++;
958 mDrawingState.modified = true;
959 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700960
Robert Carr6a160312021-05-17 12:08:20 -0700961 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700962 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700963 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700964 }
chaviw606e5cf2019-03-01 10:12:10 -0800965 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700966 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700967
968 setTransactionFlags(eTransactionNeeded);
969
970 return true;
971}
972
Winson Chunga30f7c92021-06-29 15:42:56 -0700973bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
974 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
975 mDrawingState.isTrustedOverlay = isTrustedOverlay;
976 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000977 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700978 setTransactionFlags(eTransactionNeeded);
979 return true;
980}
981
982bool Layer::isTrustedOverlay() const {
983 if (getDrawingState().isTrustedOverlay) {
984 return true;
985 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000986 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700987 return (p != nullptr) && p->isTrustedOverlay();
988}
989
Dan Stoza9e56aa02015-11-02 13:00:03 -0800990bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700991 if (mDrawingState.color.a == alpha) return false;
992 mDrawingState.sequence++;
993 mDrawingState.color.a = alpha;
994 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800995 setTransactionFlags(eTransactionNeeded);
996 return true;
997}
chaviw13fdc492017-06-27 12:40:18 -0700998
Valerie Haudd0b7572019-01-29 14:59:27 -0800999bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -07001000 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -07001001 return false;
Valerie Hauaa194562019-02-05 16:21:38 -08001002 }
Robert Carr6a160312021-05-17 12:08:20 -07001003 mDrawingState.sequence++;
1004 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -08001005 setTransactionFlags(eTransactionNeeded);
1006
Robert Carr6a160312021-05-17 12:08:20 -07001007 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001008 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001009 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001010 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001011 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Kean Mariotti4ba343c2023-04-19 13:31:02 +00001012 surfaceflinger::LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
1013 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001014
Valerie Haudd0b7572019-01-29 14:59:27 -08001015 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001016 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001017 mFlinger->mLayersAdded = true;
1018 // set up SF to handle added color layer
1019 if (isRemovedFromCurrentState()) {
Josh Gao194ff392022-09-08 16:19:29 -07001020 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001021 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001022 }
1023 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001024 } else if (mDrawingState.bgColorLayer && alpha == 0) {
Josh Gao194ff392022-09-08 16:19:29 -07001025 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001026 mDrawingState.bgColorLayer->reparent(nullptr);
1027 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001028 return true;
1029 }
1030
Robert Carr6a160312021-05-17 12:08:20 -07001031 mDrawingState.bgColorLayer->setColor(color);
1032 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1033 mDrawingState.bgColorLayer->setAlpha(alpha);
1034 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001035
chaviw13fdc492017-06-27 12:40:18 -07001036 return true;
1037}
1038
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001039bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001040 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001041
Robert Carr6a160312021-05-17 12:08:20 -07001042 mDrawingState.sequence++;
1043 mDrawingState.cornerRadius = cornerRadius;
1044 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001045 setTransactionFlags(eTransactionNeeded);
1046 return true;
1047}
1048
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001049bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001050 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001051 // If we start or stop drawing blur then the layer's visibility state may change so increment
1052 // the magic sequence number.
1053 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1054 mDrawingState.sequence++;
1055 }
Robert Carr6a160312021-05-17 12:08:20 -07001056 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1057 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001058 setTransactionFlags(eTransactionNeeded);
1059 return true;
1060}
Marissa Wall61c58622018-07-18 10:12:20 -07001061
Mathias Agopian13127d82013-03-05 17:47:11 -08001062bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001063 mDrawingState.sequence++;
1064 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001065 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001066 setTransactionFlags(eTransactionNeeded);
1067 return true;
1068}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001069
Lucas Dupinc3800b82020-10-02 16:24:48 -07001070bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001071 // If we start or stop drawing blur then the layer's visibility state may change so increment
1072 // the magic sequence number.
1073 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1074 mDrawingState.sequence++;
1075 }
Robert Carr6a160312021-05-17 12:08:20 -07001076 mDrawingState.blurRegions = blurRegions;
1077 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001078 setTransactionFlags(eTransactionNeeded);
1079 return true;
1080}
1081
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001082bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001083 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1084 if (mDrawingState.flags == newFlags) return false;
1085 mDrawingState.sequence++;
1086 mDrawingState.flags = newFlags;
1087 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001088 setTransactionFlags(eTransactionNeeded);
1089 return true;
1090}
Robert Carr99e27f02016-06-16 15:18:02 -07001091
chaviw25714502021-02-11 10:01:08 -08001092bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001093 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001094 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001095 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001096
Robert Carr6a160312021-05-17 12:08:20 -07001097 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001098 setTransactionFlags(eTransactionNeeded);
1099 return true;
1100}
Robert Carr8d5227b2017-03-16 15:41:03 -07001101
Evan Roskyef876c92019-01-25 17:46:06 -08001102bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001103 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1104 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001105 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001106 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001107}
1108
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001109bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001110 if (mDrawingState.layerStack == layerStack) return false;
1111 mDrawingState.sequence++;
1112 mDrawingState.layerStack = layerStack;
1113 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001114 setTransactionFlags(eTransactionNeeded);
1115 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001116}
1117
Peiyong Linc502cb72019-03-01 15:00:23 -08001118bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001119 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001120 return false;
1121 }
Robert Carr6a160312021-05-17 12:08:20 -07001122 mDrawingState.sequence++;
1123 mDrawingState.colorSpaceAgnostic = agnostic;
1124 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001125 setTransactionFlags(eTransactionNeeded);
1126 return true;
1127}
1128
Sally Qi81d95e62022-03-21 19:41:33 -07001129bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1130 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1131
1132 mDrawingState.sequence++;
1133 mDrawingState.dimmingEnabled = dimmingEnabled;
1134 mDrawingState.modified = true;
1135 setTransactionFlags(eTransactionNeeded);
1136 return true;
1137}
1138
Ana Krulecc84d09b2019-11-02 23:10:29 +01001139bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001140 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1141 mDrawingState.frameRateSelectionPriority = priority;
1142 mDrawingState.sequence++;
1143 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001144 setTransactionFlags(eTransactionNeeded);
1145 return true;
1146}
1147
1148int32_t Layer::getFrameRateSelectionPriority() const {
1149 // Check if layer has priority set.
1150 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1151 return mDrawingState.frameRateSelectionPriority;
1152 }
1153 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001154 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001155 if (parent != nullptr) {
1156 return parent->getFrameRateSelectionPriority();
1157 }
1158
1159 return Layer::PRIORITY_UNSET;
1160}
1161
Andy Labrada096227e2022-06-15 16:58:11 +00001162bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1163 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1164 mDrawingState.defaultFrameRateCompatibility = compatibility;
1165 mDrawingState.modified = true;
Vishnu Nair80e8cfe2023-09-29 17:03:45 -07001166 mFlinger->mScheduler->setDefaultFrameRateCompatibility(sequence, compatibility);
Andy Labrada096227e2022-06-15 16:58:11 +00001167 setTransactionFlags(eTransactionNeeded);
1168 return true;
1169}
1170
Vishnu Nair3fbe3262023-09-29 17:07:00 -07001171scheduler::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
Andy Labrada096227e2022-06-15 16:58:11 +00001172 return mDrawingState.defaultFrameRateCompatibility;
1173}
1174
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001175bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1176 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1177};
1178
Vishnu Nair73908d12022-10-24 21:46:42 -07001179ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1180 bool useDrawing = state == LayerVector::StateSet::Drawing;
1181 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1182 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001183 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001184 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001185 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001186}
1187
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001188bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001189 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001190 return false;
1191 }
1192
Robert Carr6a160312021-05-17 12:08:20 -07001193 mDrawingState.sequence++;
1194 mDrawingState.shadowRadius = shadowRadius;
1195 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001196 setTransactionFlags(eTransactionNeeded);
1197 return true;
1198}
1199
Vishnu Nair6213bd92020-05-08 17:42:25 -07001200bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001201 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001202 return false;
1203 }
1204
Robert Carr6a160312021-05-17 12:08:20 -07001205 mDrawingState.sequence++;
1206 mDrawingState.fixedTransformHint = fixedTransformHint;
1207 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001208 setTransactionFlags(eTransactionNeeded);
1209 return true;
1210}
1211
John Reckcdb4ed72021-02-04 13:39:33 -05001212bool Layer::setStretchEffect(const StretchEffect& effect) {
1213 StretchEffect temp = effect;
1214 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001215 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001216 return false;
1217 }
Robert Carr6a160312021-05-17 12:08:20 -07001218 mDrawingState.sequence++;
1219 mDrawingState.stretchEffect = temp;
1220 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001221 setTransactionFlags(eTransactionNeeded);
1222 return true;
1223}
1224
John Reckc00c6692021-02-16 11:37:33 -05001225StretchEffect Layer::getStretchEffect() const {
1226 if (mDrawingState.stretchEffect.hasEffect()) {
1227 return mDrawingState.stretchEffect;
1228 }
1229
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001230 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001231 if (parent != nullptr) {
1232 auto effect = parent->getStretchEffect();
1233 if (effect.hasEffect()) {
1234 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1235 return effect;
1236 }
1237 }
1238 return StretchEffect{};
1239}
1240
Rachel Lee0faad6c2023-09-08 13:34:34 -07001241bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool overrideChildren,
1242 bool* transactionNeeded) {
1243 // Gets the frame rate to propagate to children.
Ady Abrahama850c182021-08-04 13:04:37 -07001244 const auto frameRate = [&] {
Rachel Lee0faad6c2023-09-08 13:34:34 -07001245 if (overrideChildren && parentFrameRate.isValid()) {
1246 return parentFrameRate;
1247 }
1248
Rachel Leece6e0042023-06-27 11:22:54 -07001249 if (mDrawingState.frameRate.isValid()) {
Ady Abrahama850c182021-08-04 13:04:37 -07001250 return mDrawingState.frameRate;
1251 }
1252
1253 return parentFrameRate;
1254 }();
1255
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001256 auto now = systemTime();
1257 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate, now);
Ady Abrahama850c182021-08-04 13:04:37 -07001258
Rachel Leea021bb02023-11-20 21:51:09 -08001259 // The frame rate is propagated to the children by default, but some properties may override it.
Ady Abrahama850c182021-08-04 13:04:37 -07001260 bool childrenHaveFrameRate = false;
Rachel Leea021bb02023-11-20 21:51:09 -08001261 const bool overrideChildrenFrameRate = overrideChildren || shouldOverrideChildrenFrameRate();
1262 const bool canPropagateFrameRate = shouldPropagateFrameRate() || overrideChildrenFrameRate;
Ady Abrahama850c182021-08-04 13:04:37 -07001263 for (const sp<Layer>& child : mCurrentChildren) {
1264 childrenHaveFrameRate |=
Rachel Leea021bb02023-11-20 21:51:09 -08001265 child->propagateFrameRateForLayerTree(canPropagateFrameRate ? frameRate
1266 : FrameRate(),
1267 overrideChildrenFrameRate, transactionNeeded);
Ady Abrahama850c182021-08-04 13:04:37 -07001268 }
1269
Rachel Leece6e0042023-06-27 11:22:54 -07001270 // If we don't have a valid frame rate specification, but the children do, we set this
Ady Abrahama850c182021-08-04 13:04:37 -07001271 // layer as NoVote to allow the children to control the refresh rate
Rachel Leece6e0042023-06-27 11:22:54 -07001272 if (!frameRate.isValid() && childrenHaveFrameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001273 *transactionNeeded |=
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001274 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote),
1275 now);
Ady Abrahama850c182021-08-04 13:04:37 -07001276 }
1277
Rachel Leece6e0042023-06-27 11:22:54 -07001278 // We return whether this layer or its children has a vote. We ignore ExactOrMultiple votes for
Ady Abrahama850c182021-08-04 13:04:37 -07001279 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001280 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001281 const auto layerVotedWithDefaultCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001282 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Default;
1283 const auto layerVotedWithNoVote = frameRate.vote.type == FrameRateCompatibility::NoVote;
1284 const auto layerVotedWithCategory = frameRate.category != FrameRateCategory::Default;
Ady Abrahama850c182021-08-04 13:04:37 -07001285 const auto layerVotedWithExactCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001286 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Exact;
1287 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote || layerVotedWithCategory ||
Ady Abrahama850c182021-08-04 13:04:37 -07001288 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1289}
1290
Ady Abraham60e42ea2020-03-09 19:17:31 -07001291void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001292 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001293 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001294 while (auto parent = layer->getParent()) {
1295 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001296 }
Ady Abrahama850c182021-08-04 13:04:37 -07001297 return layer;
1298 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001299
Ady Abraham60e42ea2020-03-09 19:17:31 -07001300 bool transactionNeeded = false;
Rachel Lee0faad6c2023-09-08 13:34:34 -07001301 root->propagateFrameRateForLayerTree({}, false, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001302
Ady Abrahama850c182021-08-04 13:04:37 -07001303 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001304 if (transactionNeeded) {
1305 mFlinger->setTransactionFlags(eTraversalNeeded);
1306 }
1307}
1308
Rachel Leece6e0042023-06-27 11:22:54 -07001309bool Layer::setFrameRate(FrameRate::FrameRateVote frameRateVote) {
1310 if (mDrawingState.frameRate.vote == frameRateVote) {
Steven Thomas3172e202020-01-06 19:25:30 -08001311 return false;
1312 }
1313
Robert Carr6a160312021-05-17 12:08:20 -07001314 mDrawingState.sequence++;
Rachel Leece6e0042023-06-27 11:22:54 -07001315 mDrawingState.frameRate.vote = frameRateVote;
1316 mDrawingState.modified = true;
1317
1318 updateTreeHasFrameRateVote();
1319
1320 setTransactionFlags(eTransactionNeeded);
1321 return true;
1322}
1323
Rachel Lee67afbea2023-09-28 15:35:07 -07001324bool Layer::setFrameRateCategory(FrameRateCategory category, bool smoothSwitchOnly) {
1325 if (mDrawingState.frameRate.category == category &&
1326 mDrawingState.frameRate.categorySmoothSwitchOnly == smoothSwitchOnly) {
Rachel Leece6e0042023-06-27 11:22:54 -07001327 return false;
1328 }
1329
1330 mDrawingState.sequence++;
1331 mDrawingState.frameRate.category = category;
Rachel Lee67afbea2023-09-28 15:35:07 -07001332 mDrawingState.frameRate.categorySmoothSwitchOnly = smoothSwitchOnly;
Robert Carr6a160312021-05-17 12:08:20 -07001333 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001334
1335 updateTreeHasFrameRateVote();
1336
Steven Thomas3172e202020-01-06 19:25:30 -08001337 setTransactionFlags(eTransactionNeeded);
1338 return true;
1339}
1340
Rachel Lee58cc90d2023-09-05 18:50:20 -07001341bool Layer::setFrameRateSelectionStrategy(FrameRateSelectionStrategy strategy) {
1342 if (mDrawingState.frameRateSelectionStrategy == strategy) return false;
1343 mDrawingState.frameRateSelectionStrategy = strategy;
1344 mDrawingState.sequence++;
1345 mDrawingState.modified = true;
Rachel Leed7479502023-09-25 17:02:35 -07001346
1347 updateTreeHasFrameRateVote();
Rachel Lee58cc90d2023-09-05 18:50:20 -07001348 setTransactionFlags(eTransactionNeeded);
1349 return true;
1350}
1351
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001352void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1353 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001354 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001355
1356 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1357 // there are two transactions with the same token, the first one without a buffer and the
1358 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1359 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001360 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1361 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001362 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001363 mDrawingState.bufferSurfaceFrameTX = it->second;
1364 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1365 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1366 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001367 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001368 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001369 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1370 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001371
1372 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001373}
1374
1375void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1376 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001377 mDrawingState.frameTimelineInfo = info;
1378 mDrawingState.postTime = postTime;
1379 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001380 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001381
Robert Carr6a160312021-05-17 12:08:20 -07001382 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001383 bufferSurfaceFrameTX != nullptr) {
1384 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1385 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1386 // being used for BufferSurfaceFrame, don't create a new one.
1387 return;
1388 }
1389 }
1390 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1391 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1392 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001393 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1394 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001395 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001396 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001397 } else {
1398 if (it->second->getPresentState() == PresentState::Presented) {
1399 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1400 // have been from previous vsync.
1401 it->second = createSurfaceFrameForTransaction(info, postTime);
1402 }
1403 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001404
1405 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001406}
1407
1408void Layer::addSurfaceFrameDroppedForBuffer(
Ady Abraham5a3e3562023-06-07 10:32:08 -07001409 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t dropTime) {
1410 surfaceFrame->setDropTime(dropTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001411 surfaceFrame->setPresentState(PresentState::Dropped);
1412 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1413}
1414
1415void Layer::addSurfaceFramePresentedForBuffer(
1416 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1417 nsecs_t currentLatchTime) {
1418 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1419 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1420 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001421 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001422}
1423
1424std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1425 const FrameTimelineInfo& info, nsecs_t postTime) {
1426 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001427 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1428 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001429 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001430 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001431 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001432 // For Transactions, the post time is considered to be both queue and acquire fence time.
1433 surfaceFrame->setActualQueueTime(postTime);
1434 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001435 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1436 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001437 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001438 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001439 onSurfaceFrameCreated(surfaceFrame);
1440 return surfaceFrame;
1441}
1442
1443std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1444 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1445 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001446 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001447 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001448 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001449 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001450 // For buffers, acquire fence time will set during latch.
1451 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001452 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1453 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001454 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001455 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001456 onSurfaceFrameCreated(surfaceFrame);
1457 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001458}
1459
Ady Abraham5a3e3562023-06-07 10:32:08 -07001460void Layer::setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
1461 std::string debugName) {
1462 if (info.skippedFrameVsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
1463 return;
1464 }
1465
1466 FrameTimelineInfo skippedFrameTimelineInfo = info;
1467 skippedFrameTimelineInfo.vsyncId = info.skippedFrameVsyncId;
1468
1469 auto surfaceFrame =
1470 mFlinger->mFrameTimeline->createSurfaceFrameForToken(skippedFrameTimelineInfo,
1471 mOwnerPid, mOwnerUid,
1472 getSequence(), mName, debugName,
1473 /*isBuffer*/ false, getGameMode());
1474 surfaceFrame->setActualStartTime(skippedFrameTimelineInfo.skippedFrameStartTimeNanos);
1475 // For Transactions, the post time is considered to be both queue and acquire fence time.
1476 surfaceFrame->setActualQueueTime(postTime);
1477 surfaceFrame->setAcquireFenceTime(postTime);
1478 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1479 if (fps) {
1480 surfaceFrame->setRenderRate(*fps);
1481 }
1482 onSurfaceFrameCreated(surfaceFrame);
1483 addSurfaceFrameDroppedForBuffer(surfaceFrame, postTime);
1484}
1485
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001486bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate, nsecs_t now) {
Ady Abrahama850c182021-08-04 13:04:37 -07001487 if (mDrawingState.frameRateForLayerTree == frameRate) {
1488 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001489 }
1490
Ady Abrahama850c182021-08-04 13:04:37 -07001491 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001492
Ady Abrahama850c182021-08-04 13:04:37 -07001493 // TODO(b/195668952): we probably don't need to dirty visible regions here
1494 // or even store frameRateForLayerTree in mDrawingState
1495 mDrawingState.sequence++;
1496 mDrawingState.modified = true;
1497 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001498
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001499 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001500 ->recordLayerHistory(sequence, getLayerProps(), now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001501 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1502 return true;
1503}
Ady Abrahama850c182021-08-04 13:04:37 -07001504
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001505bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps,
1506 nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001507 if (mDrawingState.frameRateForLayerTree == frameRate) {
1508 return false;
1509 }
1510
1511 mDrawingState.frameRateForLayerTree = frameRate;
1512 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001513 ->recordLayerHistory(sequence, layerProps, now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001514 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001515 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001516}
1517
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001518Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1519 return getDrawingState().frameRateForLayerTree;
1520}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001521
Robert Carr1f0a16a2016-10-24 16:27:39 -07001522bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001523 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001524 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001525 if (parent != nullptr && parent->isHiddenByPolicy()) {
1526 return true;
1527 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001528 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1529 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1530 if (zOrderRelativeOf != nullptr) {
1531 if (zOrderRelativeOf->isHiddenByPolicy()) {
1532 return true;
1533 }
1534 }
1535 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001536 if (CC_UNLIKELY(!isTransformValid())) {
1537 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1538 return true;
1539 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001540 return s.flags & layer_state_t::eLayerHidden;
1541}
1542
David Sodman41fdfc92017-11-06 16:09:56 -08001543uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001544 // TODO: should we do something special if mSecure is set?
1545 if (mProtectedByApp) {
1546 // need a hardware-protected path to external video sink
1547 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001548 }
Riley Andrews03414a12014-07-01 14:22:59 -07001549 if (mPotentialCursor) {
1550 usage |= GraphicBuffer::USAGE_CURSOR;
1551 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001552 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001553 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001554}
1555
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001556void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1557 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1558 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001559 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001560
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001561 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001562}
1563
Mathias Agopian13127d82013-03-05 17:47:11 -08001564// ----------------------------------------------------------------------------
1565// debugging
1566// ----------------------------------------------------------------------------
1567
Yiwei Zhang5434a782018-12-05 18:06:32 -08001568void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001569 result.append(kDumpTableRowLength, '-');
1570 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001571 result.append(" Layer name\n");
1572 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001573 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001574 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001575 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001576 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001577 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001578 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1579 result.append(kDumpTableRowLength, '-');
1580 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001581}
1582
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001583void Layer::miniDumpLegacy(std::string& result, const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001584 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001585 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001586 return;
1587 }
1588
Yiwei Zhang5434a782018-12-05 18:06:32 -08001589 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001590 if (mName.length() > 77) {
1591 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001592 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001593 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001594 shortened.append(mName, mName.length() - 36);
1595 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001596 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001597 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001598 }
1599
Yiwei Zhang5434a782018-12-05 18:06:32 -08001600 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001601
Alec Mourib416efd2018-09-06 21:01:59 +00001602 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001603 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001604
Chia-I Wu1e043612018-03-01 09:45:09 -08001605 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001606 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001607 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001608 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001609 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001610 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001611 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001612 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1613 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001614 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001615 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001616 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001617 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001618 const auto frameRate = getFrameRateForLayerTree();
Rachel Leece6e0042023-06-27 11:22:54 -07001619 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
1620 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.vote.rate).c_str(),
1621 ftl::enum_string(frameRate.vote.type).c_str(),
1622 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001623 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001624 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001625 }
Dan Stozae22aec72016-08-01 13:20:59 -07001626
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001627 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1628 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1629
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001630 result.append(kDumpTableRowLength, '-');
1631 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001632}
Dan Stozae22aec72016-08-01 13:20:59 -07001633
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001634void Layer::miniDump(std::string& result, const frontend::LayerSnapshot& snapshot,
1635 const DisplayDevice& display) const {
1636 const auto outputLayer = findOutputLayerForDisplay(&display, snapshot.path);
1637 if (!outputLayer) {
1638 return;
1639 }
1640
1641 StringAppendF(&result, " %s\n", snapshot.debugName.c_str());
1642 StringAppendF(&result, " %10zu | ", snapshot.globalZ);
1643 StringAppendF(&result, " %10d | ",
1644 snapshot.layerMetadata.getInt32(gui::METADATA_WINDOW_TYPE, 0));
1645 StringAppendF(&result, "%10s | ", toString(getCompositionType(outputLayer)).c_str());
1646 const auto& outputLayerState = outputLayer->getState();
1647 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1648 const Rect& frame = outputLayerState.displayFrame;
1649 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1650 const FloatRect& crop = outputLayerState.sourceCrop;
1651 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
1652 crop.bottom);
1653 const auto frameRate = snapshot.frameRate;
Ady Abraham77d406d2023-11-22 15:00:23 -08001654 std::string frameRateStr;
1655 if (frameRate.vote.rate.isValid()) {
1656 StringAppendF(&frameRateStr, "%.2f", frameRate.vote.rate.getValue());
1657 }
Rachel Leece6e0042023-06-27 11:22:54 -07001658 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
Ady Abraham77d406d2023-11-22 15:00:23 -08001659 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
Rachel Leece6e0042023-06-27 11:22:54 -07001660 ftl::enum_string(frameRate.vote.type).c_str(),
1661 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abraham77d406d2023-11-22 15:00:23 -08001662 } else if (frameRate.category != FrameRateCategory::Default) {
1663 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
1664 (std::string("Cat::") + ftl::enum_string(frameRate.category)).c_str(),
1665 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001666 } else {
1667 result.append(41, ' ');
1668 }
1669
1670 const auto focused = isLayerFocusedBasedOnPriority(snapshot.frameRateSelectionPriority);
1671 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1672
1673 result.append(kDumpTableRowLength, '-');
1674 result.append("\n");
1675}
1676
Yiwei Zhang5434a782018-12-05 18:06:32 -08001677void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001678 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001679}
1680
Svetoslavd85084b2014-03-20 10:28:31 -07001681void Layer::clearFrameStats() {
1682 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001683}
1684
Jamie Gennis6547ff42013-07-16 20:12:42 -07001685void Layer::logFrameStats() {
1686 mFrameTracker.logAndResetStats(mName);
1687}
1688
Svetoslavd85084b2014-03-20 10:28:31 -07001689void Layer::getFrameStats(FrameStats* outStats) const {
1690 mFrameTracker.getStats(outStats);
1691}
1692
Vishnu Nair76554eb2022-12-09 03:38:36 +00001693void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1694 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
Vishnu Nair3be61902023-04-26 19:47:29 -07001695 StringAppendF(&result, "Layer %s%s pid:%d uid:%d%s\n", getName().c_str(), hasBuffer.c_str(),
1696 mOwnerPid, mOwnerUid, isHandleAlive() ? " handleAlive" : "");
Vishnu Nair0f085c62019-08-30 08:49:12 -07001697}
1698
Brian Anderson5ea5e592016-12-01 16:54:33 -08001699void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001700 const int32_t layerId = getSequence();
1701 mFlinger->mTimeStats->onDestroy(layerId);
1702 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001703}
1704
Vishnu Nair787aa782023-03-17 13:46:46 -07001705size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001706 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001707 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001708 count += 1 + child->getChildrenCount();
1709 }
1710 return count;
1711}
1712
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001713void Layer::setGameModeForTree(GameMode gameMode) {
1714 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001715 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1716 gameMode =
1717 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001718 }
1719 setGameMode(gameMode);
1720 for (const sp<Layer>& child : mCurrentChildren) {
1721 child->setGameModeForTree(gameMode);
1722 }
1723}
1724
Robert Carr1f0a16a2016-10-24 16:27:39 -07001725void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001726 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001727 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001728
Robert Carr1f0a16a2016-10-24 16:27:39 -07001729 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001730 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001731 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001732 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001733}
1734
1735ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001736 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001737 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001738
Robert Carr1323c952019-01-28 18:13:27 -08001739 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001740 const auto removeResult = mCurrentChildren.remove(layer);
1741
1742 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001743 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001744 layer->updateTreeHasFrameRateVote();
1745
1746 return removeResult;
1747}
1748
Robert Carr15eae092018-03-23 13:43:53 -07001749void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001750 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001751 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001752 const float parentShadowRadius =
1753 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001754 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001755 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001756 }
1757}
1758
chaviwf1961f72017-09-18 16:41:07 -07001759bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001760 sp<Layer> newParent;
1761 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001762 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001763 if (newParent == nullptr) {
1764 ALOGE("Unable to promote Layer handle");
1765 return false;
1766 }
1767 if (newParent == this) {
1768 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1769 return false;
1770 }
1771 }
1772
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001773 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001774 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001775 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001776 }
1777
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001778 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001779 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001780 if (!newParent->isRemovedFromCurrentState()) {
1781 addToCurrentState();
1782 } else {
1783 onRemovedFromCurrentState();
1784 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001785 } else {
1786 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001787 }
1788
chaviw06178942017-07-27 10:25:59 -07001789 return true;
1790}
1791
Peiyong Lind3788632018-09-18 16:01:31 -07001792bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001793 static const mat4 identityMatrix = mat4();
1794
Robert Carr6a160312021-05-17 12:08:20 -07001795 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001796 return false;
1797 }
Robert Carr6a160312021-05-17 12:08:20 -07001798 ++mDrawingState.sequence;
1799 mDrawingState.colorTransform = matrix;
1800 mDrawingState.hasColorTransform = matrix != identityMatrix;
1801 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001802 setTransactionFlags(eTransactionNeeded);
1803 return true;
1804}
1805
chaviwf66724d2018-11-28 16:35:21 -08001806mat4 Layer::getColorTransform() const {
1807 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001808 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001809 colorTransform = parent->getColorTransform() * colorTransform;
1810 }
1811 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001812}
1813
1814bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001815 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001816 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001817 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1818 }
1819 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001820}
1821
Chia-I Wu11481472018-05-04 10:43:19 -07001822bool Layer::isLegacyDataSpace() const {
1823 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001824 return !(getDataSpace() &
1825 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1826 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001827}
1828
Robert Carr1f0a16a2016-10-24 16:27:39 -07001829void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001830 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001831}
1832
Robert Carr6a160312021-05-17 12:08:20 -07001833int32_t Layer::getZ(LayerVector::StateSet) const {
1834 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001835}
1836
Robert Carr1c5481e2019-07-01 14:42:27 -07001837bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001838 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001839 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001840 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001841}
1842
David Sodman41fdfc92017-11-06 16:09:56 -08001843__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001844 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001845 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1846 "makeTraversalList received invalid stateSet");
1847 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1848 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001849 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001850
Robert Carr29abff82017-12-04 13:51:20 -08001851 if (state.zOrderRelatives.size() == 0) {
1852 *outSkipRelativeZUsers = true;
1853 return children;
1854 }
1855
chaviwfd462612018-05-31 16:11:27 -07001856 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001857 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001858 sp<Layer> strongRelative = weakRelative.promote();
1859 if (strongRelative != nullptr) {
1860 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001861 }
1862 }
1863
Dan Stoza412903f2017-04-27 13:42:17 -07001864 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001865 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001866 continue;
1867 }
Robert Carrdb66e622017-04-10 16:55:57 -07001868 traverse.add(child);
1869 }
1870
1871 return traverse;
1872}
1873
Robert Carr1f0a16a2016-10-24 16:27:39 -07001874/**
Robert Carrdb66e622017-04-10 16:55:57 -07001875 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001876 */
Dan Stoza412903f2017-04-27 13:42:17 -07001877void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001878 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1879 // produce a new list for traversing, including our relatives, and not including our children
1880 // who are relatives of another surface. In the case that there are no relative Z,
1881 // makeTraversalList returns our children directly to avoid significant overhead.
1882 // However in this case we need to take the responsibility for filtering children which
1883 // are relatives of another surface here.
1884 bool skipRelativeZUsers = false;
1885 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001886
Robert Carr1f0a16a2016-10-24 16:27:39 -07001887 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001888 for (; i < list.size(); i++) {
1889 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001890 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1891 continue;
1892 }
1893
chaviw301b1d82019-11-06 13:15:09 -08001894 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001895 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001896 }
Dan Stoza412903f2017-04-27 13:42:17 -07001897 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001898 }
Robert Carr29abff82017-12-04 13:51:20 -08001899
Dan Stoza412903f2017-04-27 13:42:17 -07001900 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001901 for (; i < list.size(); i++) {
1902 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001903
Robert Carr29abff82017-12-04 13:51:20 -08001904 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1905 continue;
1906 }
Dan Stoza412903f2017-04-27 13:42:17 -07001907 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001908 }
1909}
1910
1911/**
Robert Carrdb66e622017-04-10 16:55:57 -07001912 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001913 */
Dan Stoza412903f2017-04-27 13:42:17 -07001914void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1915 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001916 // See traverseInZOrder for documentation.
1917 bool skipRelativeZUsers = false;
1918 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001919
Robert Carr1f0a16a2016-10-24 16:27:39 -07001920 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001921 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001922 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001923
1924 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1925 continue;
1926 }
1927
chaviw301b1d82019-11-06 13:15:09 -08001928 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001929 break;
1930 }
Dan Stoza412903f2017-04-27 13:42:17 -07001931 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001932 }
Dan Stoza412903f2017-04-27 13:42:17 -07001933 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001934 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001935 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001936
1937 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1938 continue;
1939 }
1940
Dan Stoza412903f2017-04-27 13:42:17 -07001941 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001942 }
1943}
1944
Edgar Arriaga844fa672020-01-16 14:21:42 -08001945void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1946 visitor(this);
1947 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001948 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001949 for (const sp<Layer>& child : children) {
1950 child->traverse(state, visitor);
1951 }
1952}
1953
Vishnu Nair787aa782023-03-17 13:46:46 -07001954void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
1955 for (const sp<Layer>& child : mDrawingChildren) {
1956 visitor(child.get());
1957 }
1958}
1959
chaviw4b129c22018-04-09 16:19:43 -07001960LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1961 const std::vector<Layer*>& layersInTree) {
1962 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1963 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001964 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1965 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001966 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001967
chaviwfd462612018-05-31 16:11:27 -07001968 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001969 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1970 sp<Layer> strongRelative = weakRelative.promote();
1971 // Only add relative layers that are also descendents of the top most parent of the tree.
1972 // If a relative layer is not a descendent, then it should be ignored.
1973 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1974 traverse.add(strongRelative);
1975 }
1976 }
1977
1978 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001979 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001980 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1981 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1982 // the child here since it won't be added later as a relative.
1983 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1984 childState.zOrderRelativeOf.promote().get())) {
1985 continue;
1986 }
1987 traverse.add(child);
1988 }
1989
1990 return traverse;
1991}
1992
1993void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1994 LayerVector::StateSet stateSet,
1995 const LayerVector::Visitor& visitor) {
1996 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001997
1998 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001999 for (; i < list.size(); i++) {
2000 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08002001 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07002002 break;
2003 }
chaviw4b129c22018-04-09 16:19:43 -07002004 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002005 }
chaviw4b129c22018-04-09 16:19:43 -07002006
chaviwa76b2712017-09-20 12:02:26 -07002007 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07002008 for (; i < list.size(); i++) {
2009 const auto& relative = list[i];
2010 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002011 }
2012}
2013
chaviw4b129c22018-04-09 16:19:43 -07002014std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2015 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2016 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2017
2018 std::vector<Layer*> layersInTree = {this};
2019 for (size_t i = 0; i < children.size(); i++) {
2020 const auto& child = children[i];
2021 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2022 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2023 }
2024
2025 return layersInTree;
2026}
2027
2028void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2029 const LayerVector::Visitor& visitor) {
2030 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2031 std::sort(layersInTree.begin(), layersInTree.end());
2032 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2033}
2034
Peiyong Linefefaac2018-08-17 12:27:51 -07002035ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08002036 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002037}
2038
Garfield Tan2c1782c2022-02-16 15:25:05 -08002039bool Layer::isTransformValid() const {
2040 float transformDet = getTransform().det();
2041 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2042}
2043
chaviw13fdc492017-06-27 12:40:18 -07002044half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002045 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002046
chaviw13fdc492017-06-27 12:40:18 -07002047 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2048 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002049}
Robert Carr6452f122017-03-21 10:41:29 -07002050
Vishnu Nair6213bd92020-05-08 17:42:25 -07002051ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002052 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002053 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2054 return fixedTransformHint;
2055 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002056 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002057 if (!p) return fixedTransformHint;
2058 return p->getFixedTransformHint();
2059}
2060
chaviw13fdc492017-06-27 12:40:18 -07002061half4 Layer::getColor() const {
2062 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002063 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002064}
Robert Carr6452f122017-03-21 10:41:29 -07002065
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002066int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002067 if (getDrawingState().backgroundBlurRadius == 0) {
2068 return 0;
2069 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002070
Vishnu Nair29810f72022-07-01 16:38:41 +00002071 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002072 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2073 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002074}
2075
Galia Peychevae0acf382021-04-12 21:22:34 +02002076const std::vector<BlurRegion> Layer::getBlurRegions() const {
2077 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002078 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002079 for (auto& region : regionsCopy) {
2080 region.alpha = region.alpha * layerAlpha;
2081 }
2082 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002083}
2084
Vishnu Naire14c6b32022-08-06 04:20:15 +00002085RoundedCornerState Layer::getRoundedCornerState() const {
Leon Scroggins IIIc1dbfcb2022-03-21 16:48:10 -04002086 // Today's DPUs cannot do rounded corners. If RenderEngine cannot render
2087 // protected content, remove rounded corners from protected content so it
2088 // can be rendered by the DPU.
2089 if (isProtected() && !mFlinger->getRenderEngine().supportsProtectedContent()) {
2090 return {};
2091 }
2092
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002093 // Get parent settings
2094 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002095 const auto& parent = mDrawingParent.promote();
2096 if (parent != nullptr) {
2097 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002098 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002099 ui::Transform t = getActiveTransform(getDrawingState());
2100 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002101 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002102 parentSettings.radius.x *= t.getScaleX();
2103 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002104 }
2105 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002106
2107 // Get layer settings
2108 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002109 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002110 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002111 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002112
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002113 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002114 // If the parent and the layer have rounded corner settings, use the parent settings if the
2115 // parent crop is entirely inside the layer crop.
2116 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2117 if (parentSettings.cropRect.left > layerCropRect.left &&
2118 parentSettings.cropRect.top > layerCropRect.top &&
2119 parentSettings.cropRect.right < layerCropRect.right &&
2120 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2121 return parentSettings;
2122 } else {
2123 return layerSettings;
2124 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002125 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002126 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002127 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002128 return parentSettings;
2129 }
2130 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002131}
2132
Robert Carr88b85e12022-03-21 15:47:35 -07002133bool Layer::findInHierarchy(const sp<Layer>& l) {
2134 if (l == this) {
2135 return true;
2136 }
2137 for (auto& child : mDrawingChildren) {
2138 if (child->findInHierarchy(l)) {
2139 return true;
2140 }
2141 }
2142 return false;
2143}
2144
Robert Carr1f0a16a2016-10-24 16:27:39 -07002145void Layer::commitChildList() {
2146 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2147 const auto& child = mCurrentChildren[i];
2148 child->commitChildList();
2149 }
2150 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002151 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002152 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2153 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2154 if (zOrderRelativeOf == nullptr) return;
2155 if (findInHierarchy(zOrderRelativeOf)) {
2156 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2157 zOrderRelativeOf->mName.c_str());
2158 ALOGE("Severing rel Z loop, potentially dangerous");
2159 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002160 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002161 }
2162 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002163}
2164
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002165
chaviw3277faf2021-05-19 16:45:23 -05002166void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002167 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002168 mDrawingState.touchableRegionCrop =
2169 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002170 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002171 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002172 setTransactionFlags(eTransactionNeeded);
2173}
2174
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002175perfetto::protos::LayerProto* Layer::writeToProto(perfetto::protos::LayersProto& layersProto,
2176 uint32_t traceFlags) {
2177 perfetto::protos::LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002178 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002179 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2180
Vishnu Nair00b90132021-11-05 14:03:40 -07002181 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nair2f65e972023-04-04 16:36:28 +00002182 ui::LayerStack layerStack =
2183 (mSnapshot) ? mSnapshot->outputFilter.layerStack : ui::INVALID_LAYER_STACK;
2184 writeCompositionStateToProto(layerProto, layerStack);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002185 }
2186
chaviw08f3cb22020-01-13 13:17:21 -08002187 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002188 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002189 }
chaviw6d89e2d2020-01-14 14:42:01 -08002190
2191 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002192}
2193
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002194void Layer::writeCompositionStateToProto(perfetto::protos::LayerProto* layerProto,
2195 ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002196 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002197 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +00002198
2199 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002200 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002201 const auto compositionType = getCompositionType(*display);
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002202 layerProto->set_hwc_composition_type(
2203 static_cast<perfetto::protos::HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +00002204 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +00002205 [&]() { return layerProto->mutable_visible_region(); });
2206 }
2207}
2208
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002209void Layer::writeToProtoDrawingState(perfetto::protos::LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002210 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002211 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002212 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002213 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002214 [&]() { return layerInfo->mutable_active_buffer(); });
2215 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2216 layerInfo->mutable_buffer_transform());
2217 }
2218 layerInfo->set_invalidate(contentDirty);
2219 layerInfo->set_is_protected(isProtected());
2220 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2221 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002222 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002223 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002224 layerInfo->set_corner_radius(
2225 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002226 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2227 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2228 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2229 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2230 [&]() { return layerInfo->mutable_position(); });
2231 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002232 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2233 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002234
Vishnu Nair00b90132021-11-05 14:03:40 -07002235 if (hasColorTransform()) {
2236 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002237 }
2238
Vishnu Nair60db8c02020-04-02 11:55:16 -07002239 LayerProtoHelper::writeToProto(mSourceBounds,
2240 [&]() { return layerInfo->mutable_source_bounds(); });
2241 LayerProtoHelper::writeToProto(mScreenBounds,
2242 [&]() { return layerInfo->mutable_screen_bounds(); });
2243 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2244 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2245 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002246}
2247
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002248void Layer::writeToProtoCommonState(perfetto::protos::LayerProto* layerInfo,
2249 LayerVector::StateSet stateSet, uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002250 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2251 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002252 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002253
chaviw766c9c52021-02-10 17:36:47 -08002254 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002255
Vishnu Nair00b90132021-11-05 14:03:40 -07002256 layerInfo->set_id(sequence);
2257 layerInfo->set_name(getName().c_str());
2258 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002259
Vishnu Nair00b90132021-11-05 14:03:40 -07002260 for (const auto& child : children) {
2261 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002262 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002263
Vishnu Nair00b90132021-11-05 14:03:40 -07002264 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2265 sp<Layer> strongRelative = weakRelative.promote();
2266 if (strongRelative != nullptr) {
2267 layerInfo->add_relatives(strongRelative->sequence);
2268 }
2269 }
2270
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002271 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002272 [&]() { return layerInfo->mutable_transparent_region(); });
2273
2274 layerInfo->set_layer_stack(getLayerStack().id);
2275 layerInfo->set_z(state.z);
2276
2277 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2278 return layerInfo->mutable_requested_position();
2279 });
2280
Vishnu Nair00b90132021-11-05 14:03:40 -07002281 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2282
2283 layerInfo->set_is_opaque(isOpaque(state));
2284
2285 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2286 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2287 LayerProtoHelper::writeToProto(state.color,
2288 [&]() { return layerInfo->mutable_requested_color(); });
2289 layerInfo->set_flags(state.flags);
2290
2291 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2292 layerInfo->mutable_requested_transform());
2293
2294 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2295 if (parent != nullptr) {
2296 layerInfo->set_parent(parent->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002297 }
2298
2299 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2300 if (zOrderRelativeOf != nullptr) {
2301 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002302 }
2303
2304 layerInfo->set_is_relative_of(state.isRelativeOf);
2305
2306 layerInfo->set_owner_uid(mOwnerUid);
2307
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002308 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002309 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002310 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002311 info = fillInputInfo(
2312 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002313 } else {
2314 info = state.inputInfo;
2315 }
2316
2317 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002318 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002319 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002320
Vishnu Nair00b90132021-11-05 14:03:40 -07002321 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002322 auto protoMap = layerInfo->mutable_metadata();
2323 for (const auto& entry : state.metadata.mMap) {
2324 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2325 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002326 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002327
2328 LayerProtoHelper::writeToProto(state.destinationFrame,
2329 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002330}
2331
Robert Carr2e102c92018-10-23 12:11:15 -07002332bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002333 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002334}
2335
Prabir Pradhan33da9462022-06-14 14:55:57 +00002336// Applies the given transform to the region, while protecting against overflows caused by any
2337// offsets. If applying the offset in the transform to any of the Rects in the region would result
2338// in an overflow, they are not added to the output Region.
2339static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2340 const std::string& debugWindowName) {
2341 // Round the translation using the same rounding strategy used by ui::Transform.
2342 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2343 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2344
2345 ui::Transform transformWithoutOffset = t;
2346 transformWithoutOffset.set(0.f, 0.f);
2347
2348 const Region transformed = transformWithoutOffset.transform(r);
2349
2350 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2351 Region ret;
2352 for (const auto& rect : transformed) {
2353 Rect newRect;
2354 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2355 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2356 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2357 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2358 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2359 debugWindowName.c_str());
2360 continue;
2361 }
2362 ret.orSelf(newRect);
2363 }
2364 return ret;
2365}
2366
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002367void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002368 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2369 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002370 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002371 }
2372
Chavi Weingarten7f019192023-08-08 20:39:01 +00002373 info.frame = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
chaviw1ff3d1e2020-07-01 15:53:47 -07002374
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002375 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002376 inputToLayer.set(inputBounds.left, inputBounds.top);
2377 const ui::Transform layerToScreen = getInputTransform();
2378 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002379
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002380 // InputDispatcher expects a display-to-input transform.
2381 info.transform = inputToDisplay.inverse();
2382
2383 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002384 info.touchableRegion =
2385 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002386}
2387
chaviw3277faf2021-05-19 16:45:23 -05002388void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002389 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002390 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002391 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002392 }
2393 if (p != nullptr) {
2394 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2395 }
2396}
2397
Vishnu Naira066d902021-09-13 18:40:17 -07002398gui::DropInputMode Layer::getDropInputMode() const {
2399 gui::DropInputMode mode = mDrawingState.dropInputMode;
2400 if (mode == gui::DropInputMode::ALL) {
2401 return mode;
2402 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002403 sp<Layer> parent = mDrawingParent.promote();
2404 if (parent) {
2405 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002406 if (parentMode != gui::DropInputMode::NONE) {
2407 return parentMode;
2408 }
2409 }
2410 return mode;
2411}
2412
2413void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002414 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002415 return;
2416 }
2417
2418 // Check if we need to drop input unconditionally
2419 gui::DropInputMode dropInputMode = getDropInputMode();
2420 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002421 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002422 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2423 return;
2424 }
2425
2426 // Check if we need to check if the window is obscured by parent
2427 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2428 return;
2429 }
2430
2431 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002432 sp<Layer> parent = mDrawingParent.promote();
2433 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002434 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002435 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2436 static_cast<float>(getAlpha()));
2437 }
2438
2439 // Check if the parent has cropped the buffer
2440 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2441 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002442 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002443 return;
2444 }
2445
2446 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2447 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2448 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2449 // match then the layer has not been cropped by its parents.
2450 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2451 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2452
2453 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002454 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002455 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2456 getDebugName());
2457 } else {
2458 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2459 // input if the window is obscured. This check should be done in surfaceflinger but the
2460 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2461 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002462 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002463 }
2464}
2465
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002466WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002467 if (!hasInputInfo()) {
2468 mDrawingState.inputInfo.name = getName();
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002469 mDrawingState.inputInfo.ownerUid = gui::Uid{mOwnerUid};
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00002470 mDrawingState.inputInfo.ownerPid = gui::Pid{mOwnerPid};
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002471 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Linnan Li13bf76a2024-05-05 19:18:02 +08002472 mDrawingState.inputInfo.displayId = toLogicalDisplayId(getLayerStack());
chaviw7e72caf2020-12-02 16:50:43 -08002473 }
2474
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002475 const ui::Transform& displayTransform =
2476 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2477
chaviw3277faf2021-05-19 16:45:23 -05002478 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002479 info.id = sequence;
Linnan Li13bf76a2024-05-05 19:18:02 +08002480 info.displayId = toLogicalDisplayId(getLayerStack());
chaviw7e72caf2020-12-02 16:50:43 -08002481
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002482 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002483
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002484 if (displayArgs.transform == nullptr) {
2485 // Do not let the window receive touches if it is not associated with a valid display
2486 // transform. We still allow the window to receive keys and prevent ANRs.
2487 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2488 }
2489
Patrick Williams1caf3b72023-03-31 10:59:10 -05002490 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !isVisibleForInput());
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002491
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002492 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002493 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002494 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002495
Vishnu Nair16a938f2021-09-24 07:14:54 -07002496 // If the window will be blacked out on a display because the display does not have the secure
2497 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002498 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002499 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002500 }
2501
Vishnu Nairfed7c122023-03-18 01:54:43 +00002502 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002503 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002504 Rect inputBoundsInDisplaySpace;
2505 if (!cropLayer) {
2506 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2507 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2508 } else {
2509 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2510 inputBoundsInDisplaySpace =
2511 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2512 }
2513 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002514 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002515 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2516 Rect inputBoundsInDisplaySpace =
2517 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2518 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002519 }
2520
Winson Chunga30f7c92021-06-29 15:42:56 -07002521 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2522 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002523 if (isTrustedOverlay()) {
2524 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2525 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002526
chaviwaf87b3e2019-10-01 16:59:28 -07002527 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2528 // touches from going outside the cloned area.
2529 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002530 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002531 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2532 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002533 info.touchableRegion = info.touchableRegion.intersect(rect);
2534 }
2535 }
2536
Vishnu Nair494a2e42023-11-10 17:21:19 -08002537 Rect bufferSize = getBufferSize(getDrawingState());
2538 info.contentSize = Size(bufferSize.width(), bufferSize.height());
2539
Robert Carr720e5062018-07-30 17:45:14 -07002540 return info;
2541}
2542
Vishnu Nairfed7c122023-03-18 01:54:43 +00002543Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2544 const ui::Transform& screenToDisplay) {
2545 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2546 // frame and transform used for the layer, which determines the bounds and the coordinate space
2547 // within which the layer will receive input.
2548
2549 // Coordinate space definitions:
2550 // - display: The display device's coordinate space. Correlates to pixels on the display.
2551 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2552 // - layer: The coordinate space of this layer.
2553 // - input: The coordinate space in which this layer will receive input events. This could be
2554 // different than layer space if a surfaceInset is used, which changes the origin
2555 // of the input space.
2556
2557 // Crop the input bounds to ensure it is within the parent's bounds.
2558 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2559 const ui::Transform layerToScreen = getInputTransform();
2560 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2561 return Rect{layerToDisplay.transform(croppedInputBounds)};
2562}
2563
chaviwaf87b3e2019-10-01 16:59:28 -07002564sp<Layer> Layer::getClonedRoot() {
2565 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002566 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002567 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002568 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002569 return nullptr;
2570 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002571 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002572}
2573
Robert Carredd13602020-04-13 17:24:34 -07002574bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002575 return mDrawingState.inputInfo.token != nullptr ||
2576 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002577}
2578
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002579compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002580 const DisplayDevice* display) const {
2581 if (!display) return nullptr;
Lloyd Pique30db6402023-06-26 18:56:51 +00002582 if (!mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00002583 return display->getCompositionDisplay()->getOutputLayerForLayer(
2584 getCompositionEngineLayerFE());
2585 }
2586 sp<LayerFE> layerFE;
2587 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2588 for (auto& [p, layer] : mLayerFEs) {
2589 if (p == path) {
2590 layerFE = layer;
2591 }
2592 }
2593
2594 if (!layerFE) return nullptr;
2595 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002596}
2597
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002598compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
2599 const DisplayDevice* display, const frontend::LayerHierarchy::TraversalPath& path) const {
2600 if (!display) return nullptr;
Vishnu Naire9ee0002023-07-01 03:14:51 +00002601 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2602 return display->getCompositionDisplay()->getOutputLayerForLayer(
2603 getCompositionEngineLayerFE());
2604 }
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002605 sp<LayerFE> layerFE;
2606 for (auto& [p, layer] : mLayerFEs) {
2607 if (p == path) {
2608 layerFE = layer;
2609 }
2610 }
2611
2612 if (!layerFE) return nullptr;
2613 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
2614}
2615
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002616Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2617 const auto outputLayer = findOutputLayerForDisplay(display);
2618 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002619}
2620
Patrick Williamsbb25f802022-08-30 23:02:34 +00002621void Layer::updateCloneBufferInfo() {
2622 if (!isClone() || !isClonedFromAlive()) {
2623 return;
2624 }
2625
2626 sp<Layer> clonedFrom = getClonedFrom();
2627 mBufferInfo = clonedFrom->mBufferInfo;
2628 mSidebandStream = clonedFrom->mSidebandStream;
2629 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2630 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2631 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2632
2633 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2634 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2635 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2636 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2637 // the cloned drawingState again.
2638 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2639 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2640 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2641 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2642
2643 cloneDrawingState(clonedFrom.get());
2644
2645 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2646 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2647 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2648 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002649}
chaviw74b03172019-08-19 11:09:03 -07002650
Vishnu Nair3be61902023-04-26 19:47:29 -07002651bool Layer::updateMirrorInfo(const std::deque<Layer*>& cloneRootsPendingUpdates) {
chaviw74b03172019-08-19 11:09:03 -07002652 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2653 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2654 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2655 // that case, we want to delete the reference to the clone since we want it to get
2656 // destroyed. The root, this layer, will still be around since the client can continue
2657 // to hold a reference, but no cloned layers will be displayed.
2658 mClonedChild = nullptr;
Vishnu Nair3be61902023-04-26 19:47:29 -07002659 return true;
chaviw74b03172019-08-19 11:09:03 -07002660 }
2661
2662 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2663 // If the real layer exists and is in current state, add the clone as a child of the root.
2664 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2665 // copied to drawingState for the root layer. So the clonedChild is always removed from
2666 // drawingState and then needs to be added back each traversal.
2667 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2668 addChildToDrawing(mClonedChild);
2669 }
2670
2671 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002672 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002673 mClonedChild->updateClonedRelatives(clonedLayersMap);
Vishnu Nair3be61902023-04-26 19:47:29 -07002674
2675 for (Layer* root : cloneRootsPendingUpdates) {
2676 if (clonedLayersMap.find(sp<Layer>::fromExisting(root)) != clonedLayersMap.end()) {
2677 return false;
2678 }
2679 }
2680 return true;
chaviw74b03172019-08-19 11:09:03 -07002681}
2682
2683void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2684 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2685 // to the clone. If the real layer is no longer alive, continue traversing the children
2686 // since we may be able to pull out other children that are still alive.
2687 if (isClonedFromAlive()) {
2688 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002689 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002690 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002691 }
2692
2693 // The clone layer may have children in drawingState since they may have been created and
2694 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2695 // that already exist, since we can just re-use them.
2696 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2697 // not updated in the regular traversal. They are skipped since the root will lose the
2698 // reference to them when it copies its currentChildren to drawing.
2699 for (sp<Layer>& child : mDrawingChildren) {
2700 child->updateClonedDrawingState(clonedLayersMap);
2701 }
2702}
2703
2704void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2705 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2706 mDrawingChildren.clear();
2707
2708 if (!isClonedFromAlive()) {
2709 return;
2710 }
2711
2712 sp<Layer> clonedFrom = getClonedFrom();
2713 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2714 if (child == mirrorRoot) {
2715 // This is to avoid cyclical mirroring.
2716 continue;
2717 }
2718 sp<Layer> clonedChild = clonedLayersMap[child];
2719 if (clonedChild == nullptr) {
Melody Hsu12ecd082024-04-17 19:03:13 +00002720 clonedChild = child->createClone();
chaviw74b03172019-08-19 11:09:03 -07002721 clonedLayersMap[child] = clonedChild;
2722 }
2723 addChildToDrawing(clonedChild);
2724 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2725 }
2726}
2727
chaviwaf87b3e2019-10-01 16:59:28 -07002728void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2729 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2730 if (cropLayer != nullptr) {
2731 if (clonedLayersMap.count(cropLayer) == 0) {
2732 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2733 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002734 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002735 } else {
2736 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2737 mDrawingState.touchableRegionCrop = clonedCropLayer;
2738 }
2739 }
2740 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2741 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002742 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002743}
2744
2745void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002746 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002747 mDrawingState.zOrderRelatives.clear();
2748
2749 if (!isClonedFromAlive()) {
2750 return;
2751 }
2752
chaviwaf87b3e2019-10-01 16:59:28 -07002753 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002754 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002755 const sp<Layer>& relative = relativeWeak.promote();
2756 if (clonedLayersMap.count(relative) > 0) {
2757 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002758 mDrawingState.zOrderRelatives.add(clonedRelative);
2759 }
2760 }
2761
2762 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2763 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2764 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2765 // still traverse the children, but the layer with the missing relativeOf will not be shown
2766 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002767 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2768 if (clonedLayersMap.count(relativeOf) > 0) {
2769 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002770 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2771 }
2772
chaviwaf87b3e2019-10-01 16:59:28 -07002773 updateClonedInputInfo(clonedLayersMap);
2774
chaviw74b03172019-08-19 11:09:03 -07002775 for (sp<Layer>& child : mDrawingChildren) {
2776 child->updateClonedRelatives(clonedLayersMap);
2777 }
2778}
2779
2780void Layer::addChildToDrawing(const sp<Layer>& layer) {
2781 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002782 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002783}
2784
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002785bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002786 const State& s(mDrawingState);
2787 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2788 return true;
2789 }
2790
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002791 sp<Layer> parent = mDrawingParent.promote();
2792 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002793}
2794
Robert Carr6a0382d2021-07-01 15:57:17 -07002795void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2796 mClonedChild = clonedChild;
2797 mHadClonedChild = true;
Vishnu Nair3be61902023-04-26 19:47:29 -07002798 mFlinger->mLayerMirrorRoots.push_back(this);
Robert Carr6a0382d2021-07-01 15:57:17 -07002799}
2800
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002801bool Layer::setDropInputMode(gui::DropInputMode mode) {
2802 if (mDrawingState.dropInputMode == mode) {
2803 return false;
2804 }
2805 mDrawingState.dropInputMode = mode;
2806 return true;
2807}
2808
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002809void Layer::cloneDrawingState(const Layer* from) {
2810 mDrawingState = from->mDrawingState;
2811 // Skip callback info since they are not applicable for cloned layers.
2812 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002813 // TODO (b/238781169) currently broken for mirror layers because we do not
2814 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002815 mDrawingState.callbackHandles = {};
2816}
2817
Patrick Williamsbb25f802022-08-30 23:02:34 +00002818void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2819 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002820 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002821 if (!listener) {
2822 return;
2823 }
2824 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002825 uint32_t currentMaxAcquiredBufferCount =
2826 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002827 listener->onReleaseBuffer({buffer->getId(), framenumber},
2828 releaseFence ? releaseFence : Fence::NO_FENCE,
2829 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002830}
2831
Melody Hsu793f8362024-01-08 20:00:35 +00002832sp<CallbackHandle> Layer::findCallbackHandle() {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002833 // If we are displayed on multiple displays in a single composition cycle then we would
2834 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2835 // For example we can only use it if all the displays are client comp, and we need
2836 // to merge all the client comp fences. We could do this, but for now we just
2837 // disable the optimization when a layer is composed on multiple displays.
2838 if (mClearClientCompositionFenceOnLayerDisplayed) {
2839 mLastClientCompositionFence = nullptr;
2840 } else {
2841 mClearClientCompositionFenceOnLayerDisplayed = true;
2842 }
2843
2844 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2845 // buffer that was presented on this layer. The first transaction that came in this frame that
2846 // replaced the previous buffer on this layer needs this release fence, because the fence will
2847 // let the client know when that previous buffer is removed from the screen.
2848 //
2849 // Every other transaction on this layer does not need a release fence because no other
2850 // Transactions that were set on this layer this frame are going to have their preceding buffer
2851 // removed from the display this frame.
2852 //
2853 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2854 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2855 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2856 // the previous buffer will be released this frame. The third transaction also contains a
2857 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2858 // transaction will now no longer be presented so it is released immediately and the third
2859 // transaction doesn't need a previous release fence.
2860 sp<CallbackHandle> ch;
2861 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002862 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002863 ch = handle;
2864 break;
2865 }
2866 }
Melody Hsu793f8362024-01-08 20:00:35 +00002867 return ch;
2868}
2869
2870void Layer::prepareReleaseCallbacks(ftl::Future<FenceResult> futureFenceResult,
2871 ui::LayerStack layerStack) {
2872 sp<CallbackHandle> ch = findCallbackHandle();
2873
2874 if (ch != nullptr) {
2875 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2876 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2877 ch->name = mName;
2878 } else {
Melody Hsue4ef87f2024-03-26 23:54:45 +00002879 // If we didn't get a release callback yet (e.g. some scenarios when capturing
2880 // screenshots asynchronously) then make sure we don't drop the fence.
2881 // Older fences for the same layer stack can be dropped when a new fence arrives.
2882 // An assumption here is that RenderEngine performs work sequentially, so an
2883 // incoming fence will not fire before an existing fence.
2884 mAdditionalPreviousReleaseFences.emplace_or_replace(layerStack,
2885 std::move(futureFenceResult));
Melody Hsu793f8362024-01-08 20:00:35 +00002886 }
2887
2888 if (mBufferInfo.mBuffer) {
2889 mPreviouslyPresentedLayerStacks.push_back(layerStack);
2890 }
2891
2892 if (mDrawingState.frameNumber > 0) {
2893 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
2894 }
2895}
2896
2897void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
2898 ui::LayerStack layerStack,
2899 std::function<FenceResult(FenceResult)>&& continuation) {
2900 sp<CallbackHandle> ch = findCallbackHandle();
Alec Mouri9892aac2023-12-11 21:16:59 +00002901
2902 if (!FlagManager::getInstance().screenshot_fence_preservation() && continuation) {
2903 futureFenceResult = ftl::Future(futureFenceResult).then(std::move(continuation)).share();
2904 }
2905
Patrick Williamsbb25f802022-08-30 23:02:34 +00002906 if (ch != nullptr) {
2907 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
Melody Hsu793f8362024-01-08 20:00:35 +00002908 ch->previousSharedReleaseFences.emplace_back(std::move(futureFenceResult));
Patrick Williamsbb25f802022-08-30 23:02:34 +00002909 ch->name = mName;
Alec Mouri9892aac2023-12-11 21:16:59 +00002910 } else if (FlagManager::getInstance().screenshot_fence_preservation()) {
2911 // If we didn't get a release callback yet, e.g. some scenarios when capturing screenshots
2912 // asynchronously, then make sure we don't drop the fence.
Melody Hsu793f8362024-01-08 20:00:35 +00002913 mPreviousReleaseFenceAndContinuations.emplace_back(std::move(futureFenceResult),
2914 std::move(continuation));
Alec Mouri9892aac2023-12-11 21:16:59 +00002915 std::vector<FenceAndContinuation> mergedFences;
2916 sp<Fence> prevFence = nullptr;
2917 // For a layer that's frequently screenshotted, try to merge fences to make sure we don't
2918 // grow unbounded.
Melody Hsu793f8362024-01-08 20:00:35 +00002919 for (const auto& futureAndContinuation : mPreviousReleaseFenceAndContinuations) {
2920 auto result = futureAndContinuation.future.wait_for(0s);
Alec Mouri9892aac2023-12-11 21:16:59 +00002921 if (result != std::future_status::ready) {
Melody Hsu793f8362024-01-08 20:00:35 +00002922 mergedFences.emplace_back(futureAndContinuation);
Alec Mouri9892aac2023-12-11 21:16:59 +00002923 continue;
2924 }
2925
Melody Hsu793f8362024-01-08 20:00:35 +00002926 mergeFence(getDebugName(),
2927 futureAndContinuation.chain().get().value_or(Fence::NO_FENCE), prevFence);
Alec Mouri9892aac2023-12-11 21:16:59 +00002928 }
2929 if (prevFence != nullptr) {
2930 mergedFences.emplace_back(ftl::yield(FenceResult(std::move(prevFence))).share());
2931 }
2932
Melody Hsu793f8362024-01-08 20:00:35 +00002933 mPreviousReleaseFenceAndContinuations.swap(mergedFences);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002934 }
Alec Mouri9892aac2023-12-11 21:16:59 +00002935
Vishnu Nair316b7f42023-10-13 23:44:46 +00002936 if (mBufferInfo.mBuffer) {
2937 mPreviouslyPresentedLayerStacks.push_back(layerStack);
2938 }
Alec Mouri21d94322023-10-17 19:51:39 +00002939
2940 if (mDrawingState.frameNumber > 0) {
2941 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
2942 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002943}
2944
2945void Layer::onSurfaceFrameCreated(
2946 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2947 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2948 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2949 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2950 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002951 if (hasBufferOrSidebandStreamInDrawing()) {
2952 // Only log for layers with a buffer, since we expect the jank data to be drained for
2953 // these, while there may be no jank listeners for bufferless layers.
2954 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2955 mName.c_str());
2956 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2957 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2958 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002959 mPendingJankClassifications.pop_front();
2960 }
2961 mPendingJankClassifications.emplace_back(surfaceFrame);
2962}
2963
2964void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2965 for (const auto& handle : mDrawingState.callbackHandles) {
Melody Hsu9af30702024-04-17 18:23:43 +00002966 handle->transformHint = mTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002967 handle->dequeueReadyTime = dequeueReadyTime;
2968 handle->currentMaxAcquiredBufferCount =
2969 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2970 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2971 handle->previousReleaseCallbackId.framenumber);
2972 }
2973
2974 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002975 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002976 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2977 break;
2978 }
2979 }
2980
2981 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002982 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002983 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2984 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002985 mDrawingState.callbackHandles = {};
2986}
2987
2988bool Layer::willPresentCurrentTransaction() const {
2989 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2990 return (getSidebandStreamChanged() || getAutoRefresh() ||
2991 (mDrawingState.modified &&
2992 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2993}
2994
2995bool Layer::setTransform(uint32_t transform) {
2996 if (mDrawingState.bufferTransform == transform) return false;
2997 mDrawingState.bufferTransform = transform;
2998 mDrawingState.modified = true;
2999 setTransactionFlags(eTransactionNeeded);
3000 return true;
3001}
3002
3003bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
3004 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
3005 mDrawingState.sequence++;
3006 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
3007 mDrawingState.modified = true;
3008 setTransactionFlags(eTransactionNeeded);
3009 return true;
3010}
3011
3012bool Layer::setBufferCrop(const Rect& bufferCrop) {
3013 if (mDrawingState.bufferCrop == bufferCrop) return false;
3014
3015 mDrawingState.sequence++;
3016 mDrawingState.bufferCrop = bufferCrop;
3017
3018 mDrawingState.modified = true;
3019 setTransactionFlags(eTransactionNeeded);
3020 return true;
3021}
3022
3023bool Layer::setDestinationFrame(const Rect& destinationFrame) {
3024 if (mDrawingState.destinationFrame == destinationFrame) return false;
3025
3026 mDrawingState.sequence++;
3027 mDrawingState.destinationFrame = destinationFrame;
3028
3029 mDrawingState.modified = true;
3030 setTransactionFlags(eTransactionNeeded);
3031 return true;
3032}
3033
3034// Translate destination frame into scale and position. If a destination frame is not set, use the
3035// provided scale and position
3036bool Layer::updateGeometry() {
3037 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
3038 mDrawingState.destinationFrame.isEmpty()) {
3039 // If destination frame is not set, use the requested transform set via
3040 // Layer::setPosition and Layer::setMatrix.
3041 return assignTransform(&mDrawingState.transform, mRequestedTransform);
3042 }
3043
3044 Rect destRect = mDrawingState.destinationFrame;
3045 int32_t destW = destRect.width();
3046 int32_t destH = destRect.height();
3047 if (destRect.left < 0) {
3048 destRect.left = 0;
3049 destRect.right = destW;
3050 }
3051 if (destRect.top < 0) {
3052 destRect.top = 0;
3053 destRect.bottom = destH;
3054 }
3055
3056 if (!mDrawingState.buffer) {
3057 ui::Transform t;
3058 t.set(destRect.left, destRect.top);
3059 return assignTransform(&mDrawingState.transform, t);
3060 }
3061
3062 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3063 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3064 // Undo any transformations on the buffer.
3065 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3066 std::swap(bufferWidth, bufferHeight);
3067 }
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003068 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003069 if (mDrawingState.transformToDisplayInverse) {
3070 if (invTransform & ui::Transform::ROT_90) {
3071 std::swap(bufferWidth, bufferHeight);
3072 }
3073 }
3074
3075 float sx = destW / static_cast<float>(bufferWidth);
3076 float sy = destH / static_cast<float>(bufferHeight);
3077 ui::Transform t;
3078 t.set(sx, 0, 0, sy);
3079 t.set(destRect.left, destRect.top);
3080 return assignTransform(&mDrawingState.transform, t);
3081}
3082
3083bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3084 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3085 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3086 return false;
3087 }
3088
3089 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3090
3091 mDrawingState.sequence++;
3092 mDrawingState.modified = true;
3093 setTransactionFlags(eTransactionNeeded);
3094
3095 return true;
3096}
3097
3098bool Layer::setPosition(float x, float y) {
3099 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3100 return false;
3101 }
3102
3103 mRequestedTransform.set(x, y);
3104
3105 mDrawingState.sequence++;
3106 mDrawingState.modified = true;
3107 setTransactionFlags(eTransactionNeeded);
3108
3109 return true;
3110}
3111
Dorin Drimuse5374e52023-08-02 17:52:43 +00003112void Layer::releasePreviousBuffer() {
3113 mReleasePreviousBuffer = true;
3114 if (!mBufferInfo.mBuffer ||
3115 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3116 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3117 // If mDrawingState has a buffer, and we are about to update again
3118 // before swapping to drawing state, then the first buffer will be
3119 // dropped and we should decrement the pending buffer count and
3120 // call any release buffer callbacks if set.
3121 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3122 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3123 mDrawingState.acquireFence);
3124 decrementPendingBufferCount();
3125 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3126 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3127 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX, systemTime());
3128 mDrawingState.bufferSurfaceFrameTX.reset();
3129 }
3130 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3131 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3132 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3133 mLastClientCompositionFence);
3134 mLastClientCompositionFence = nullptr;
3135 }
3136}
3137
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003138void Layer::resetDrawingStateBufferInfo() {
3139 mDrawingState.producerId = 0;
3140 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +00003141 mDrawingState.previousFrameNumber = 0;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003142 mDrawingState.releaseBufferListener = nullptr;
3143 mDrawingState.buffer = nullptr;
3144 mDrawingState.acquireFence = sp<Fence>::make(-1);
3145 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3146 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3147 mDrawingState.releaseBufferEndpoint = nullptr;
3148}
3149
Patrick Williamsbb25f802022-08-30 23:02:34 +00003150bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3151 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
Nergi Rahardi39f510f2024-05-23 15:16:54 +09003152 bool isAutoTimestamp, const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003153 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003154
3155 const bool frameNumberChanged =
3156 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3157 const uint64_t frameNumber =
3158 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003159 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003160
3161 if (mDrawingState.buffer) {
Dorin Drimuse5374e52023-08-02 17:52:43 +00003162 releasePreviousBuffer();
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003163 } else if (buffer) {
Vishnu Nairc09c0232023-03-02 03:22:35 +00003164 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3165 // we don't want to incorrectly classify a frame if we miss the desired present time.
3166 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003167 }
3168
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003169 mDrawingState.desiredPresentTime = desiredPresentTime;
3170 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3171 mDrawingState.latchedVsyncId = info.vsyncId;
Ady Abraham55269162023-05-09 11:26:06 -07003172 mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003173 mDrawingState.modified = true;
3174 if (!buffer) {
3175 resetDrawingStateBufferInfo();
3176 setTransactionFlags(eTransactionNeeded);
3177 mDrawingState.bufferSurfaceFrameTX = nullptr;
3178 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3179 return true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003180 } else {
3181 // release sideband stream if it exists and a non null buffer is being set
3182 if (mDrawingState.sidebandStream != nullptr) {
Dorin Drimus66ed1c42023-09-27 13:10:16 +00003183 setSidebandStream(nullptr, info, postTime);
Dorin Drimuse5374e52023-08-02 17:52:43 +00003184 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003185 }
3186
Vishnu Naird1f74982023-06-15 20:16:51 -07003187 if ((mDrawingState.producerId > bufferData.producerId) ||
3188 ((mDrawingState.producerId == bufferData.producerId) &&
3189 (mDrawingState.frameNumber > frameNumber))) {
3190 ALOGE("Out of order buffers detected for %s producedId=%d frameNumber=%" PRIu64
3191 " -> producedId=%d frameNumber=%" PRIu64,
3192 getDebugName(), mDrawingState.producerId, mDrawingState.frameNumber,
3193 bufferData.producerId, frameNumber);
3194 TransactionTraceWriter::getInstance().invoke("out_of_order_buffers_", /*overwrite=*/false);
3195 }
3196
liulijuneb489f62022-10-17 22:02:14 +08003197 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -07003198 mDrawingState.barrierProducerId =
3199 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003200 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -07003201 mDrawingState.barrierFrameNumber =
3202 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
3203
Patrick Williamsbb25f802022-08-30 23:02:34 +00003204 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3205 mDrawingState.buffer = std::move(buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003206 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3207 ? bufferData.acquireFence
3208 : Fence::NO_FENCE;
3209 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3210 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3211 // We latched this buffer unsiganled, so we need to pass the acquire fence
3212 // on the callback instead of just the acquire time, since it's unknown at
3213 // this point.
3214 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3215 } else {
3216 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3217 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003218 setTransactionFlags(eTransactionNeeded);
3219
3220 const int32_t layerId = getSequence();
3221 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3222 mOwnerUid, postTime, getGameMode());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003223
Patrick Williamsbb25f802022-08-30 23:02:34 +00003224 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3225
Nergi Rahardi39f510f2024-05-23 15:16:54 +09003226 if (bufferData.dequeueTime > 0) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003227 const uint64_t bufferId = mDrawingState.buffer->getId();
3228 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
Nergi Rahardi39f510f2024-05-23 15:16:54 +09003229 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber,
3230 bufferData.dequeueTime,
Patrick Williamsbb25f802022-08-30 23:02:34 +00003231 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) {
Vishnu Nair9e0017e2024-05-22 19:02:44 +00003905 if (mDrawingState.isTrustedOverlay != (s.trustedOverlay == gui::TrustedOverlay::ENABLED)) {
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 {
Lloyd Pique70ddc672024-04-30 18:20:40 -07003985 auto result = mFlinger->getFactory().createLayerFE(mName, this);
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 }
Lloyd Pique70ddc672024-04-30 18:20:40 -07003997 auto layerFE = mFlinger->getFactory().createLayerFE(mName, this);
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003998 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"