blob: 7e8ed481809fee303e9e8dc8dad34019e627c02e [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 Hsu793f8362024-01-08 20:00:35 +000018#include "TransactionCallbackInvoker.h"
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
Alec Mourie60041e2019-06-14 18:59:51 -070027#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080028
[1;3C2b9fc252021-02-04 16:16:50 -080029#include <android-base/properties.h>
Yiwei Zhang5434a782018-12-05 18:06:32 -080030#include <android-base/stringprintf.h>
Vishnu Nair0f085c62019-08-30 08:49:12 -070031#include <binder/IPCThreadState.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000032#include <compositionengine/CompositionEngine.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080033#include <compositionengine/Display.h>
Lloyd Piquea83776c2019-01-29 18:42:32 -080034#include <compositionengine/LayerFECompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080035#include <compositionengine/OutputLayer.h>
36#include <compositionengine/impl/OutputLayerCompositionState.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070037#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070038#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070039#include <cutils/properties.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070040#include <ftl/enum.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080041#include <ftl/fake_guard.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080042#include <gui/BufferItem.h>
43#include <gui/LayerDebugInfo.h>
44#include <gui/Surface.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000045#include <gui/TraceUtils.h>
Alec Mourie60041e2019-06-14 18:59:51 -070046#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070047#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070049#include <stdint.h>
50#include <stdlib.h>
51#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000052#include <system/graphics-base-v1.0.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080053#include <ui/DebugUtils.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000054#include <ui/FloatRect.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080055#include <ui/GraphicBuffer.h>
Sally Qif6918d42023-08-07 15:28:30 -070056#include <ui/HdrRenderTypeUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080057#include <ui/PixelFormat.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000058#include <ui/Rect.h>
59#include <ui/Transform.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060#include <utils/Errors.h>
61#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080062#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080064#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065
Alec Mourie60041e2019-06-14 18:59:51 -070066#include <algorithm>
67#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070068#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070069#include <sstream>
70
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070071#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080072#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070073#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070074#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +000075#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000076#include "FrontEnd/LayerHandle.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080077#include "LayerProtoHelper.h"
Josh Gao194ff392022-09-08 16:19:29 -070078#include "MutexUtils.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080080#include "TimeStats/TimeStats.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070081#include "TunnelModeEnabledReporter.h"
Alec Mouri9892aac2023-12-11 21:16:59 +000082#include "Utils/FenceUtils.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070083
David Sodman41fdfc92017-11-06 16:09:56 -080084#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000085#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080087namespace android {
Alec Mouri9892aac2023-12-11 21:16:59 +000088using namespace std::chrono_literals;
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010089namespace {
90constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000091
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000092const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000093
Patrick Williamsbb25f802022-08-30 23:02:34 +000094bool assignTransform(ui::Transform* dst, ui::Transform& from) {
95 if (*dst == from) {
96 return false;
97 }
98 *dst = from;
99 return true;
100}
101
102TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
103 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
104 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
105 const auto frameRateCompatibility = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700106 switch (frameRate.vote.type) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000107 case Layer::FrameRateCompatibility::Default:
108 return FrameRateCompatibility::Default;
109 case Layer::FrameRateCompatibility::ExactOrMultiple:
110 return FrameRateCompatibility::ExactOrMultiple;
111 default:
112 return FrameRateCompatibility::Undefined;
113 }
114 }();
115
116 const auto seamlessness = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700117 switch (frameRate.vote.seamlessness) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000118 case scheduler::Seamlessness::OnlySeamless:
119 return Seamlessness::ShouldBeSeamless;
120 case scheduler::Seamlessness::SeamedAndSeamless:
121 return Seamlessness::NotRequired;
122 default:
123 return Seamlessness::Undefined;
124 }
125 }();
126
Rachel Leece6e0042023-06-27 11:22:54 -0700127 return TimeStats::SetFrameRateVote{.frameRate = frameRate.vote.rate.getValue(),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000128 .frameRateCompatibility = frameRateCompatibility,
129 .seamlessness = seamlessness};
130}
131
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100132} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800133
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700134using namespace ftl::flag_operators;
135
Yiwei Zhang5434a782018-12-05 18:06:32 -0800136using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000137using frontend::LayerSnapshot;
138using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800139using gui::GameMode;
140using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500141using gui::WindowInfo;
Vishnu Nair494a2e42023-11-10 17:21:19 -0800142using ui::Size;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800143
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700144using PresentState = frametimeline::SurfaceFrame::PresentState;
145
Kean Mariotti4ba343c2023-04-19 13:31:02 +0000146Layer::Layer(const surfaceflinger::LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000147 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700148 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000149 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700150 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800151 mWindowType(static_cast<WindowInfo::Type>(
152 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000153 mLayerCreationFlags(args.flags),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000154 mBorderEnabled(false),
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000155 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000156 ALOGV("Creating Layer %s", getDebugName());
157
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700158 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700159 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
160 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
161 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700162 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
163 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700164 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700165 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700166 mDrawingState.z = 0;
167 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700168 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700169 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700170 mDrawingState.transform.set(0, 0);
171 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +0000172 mDrawingState.previousFrameNumber = 0;
Vishnu Nair63221212023-04-06 15:17:37 -0700173 mDrawingState.barrierFrameNumber = 0;
174 mDrawingState.producerId = 0;
175 mDrawingState.barrierProducerId = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700176 mDrawingState.bufferTransform = 0;
177 mDrawingState.transformToDisplayInverse = false;
Robert Carr6a160312021-05-17 12:08:20 -0700178 mDrawingState.acquireFence = sp<Fence>::make(-1);
179 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
Alec Mouri74c7ae12023-03-26 02:57:47 +0000180 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Robert Carr6a160312021-05-17 12:08:20 -0700181 mDrawingState.hdrMetadata.validTypes = 0;
182 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
183 mDrawingState.cornerRadius = 0.0f;
184 mDrawingState.backgroundBlurRadius = 0;
185 mDrawingState.api = -1;
186 mDrawingState.hasColorTransform = false;
187 mDrawingState.colorSpaceAgnostic = false;
188 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
189 mDrawingState.metadata = args.metadata;
190 mDrawingState.shadowRadius = 0.f;
191 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
192 mDrawingState.frameTimelineInfo = {};
193 mDrawingState.postTime = -1;
194 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000195 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700196 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700197 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000198 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Rachel Lee70f7b692023-11-22 11:24:02 -0800199 mDrawingState.frameRateSelectionStrategy = FrameRateSelectionStrategy::Propagate;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700200
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700201 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
202 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700203 mDrawingState.color.r = -1.0_hf;
204 mDrawingState.color.g = -1.0_hf;
205 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700206 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700207
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500208 mFrameTracker.setDisplayRefreshPeriod(
209 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700210
Vishnu Naircb8be502022-10-12 19:03:23 +0000211 mOwnerUid = args.ownerUid;
212 mOwnerPid = args.ownerPid;
Tony Huangf3621102023-09-04 17:14:22 +0800213 mOwnerAppId = mOwnerUid % PER_USER_RANGE;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000214
215 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
216 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
217 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000218
219 mSnapshot->sequence = sequence;
220 mSnapshot->name = getDebugName();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000221 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000222 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800223}
224
225void Layer::onFirstRef() {
226 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700227}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700228
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700229Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000230 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
231 "Layer destructor called off the main thread.");
232
Patrick Williamsbb25f802022-08-30 23:02:34 +0000233 // The original layer and the clone layer share the same texture and buffer. Therefore, only
234 // one of the layers, in this case the original layer, needs to handle the deletion. The
235 // original layer and the clone should be removed at the same time so there shouldn't be any
236 // issue with the clone layer trying to use the texture.
237 if (mBufferInfo.mBuffer != nullptr) {
238 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
239 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800240 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000241 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000242 const int32_t layerId = getSequence();
243 mFlinger->mTimeStats->onDestroy(layerId);
244 mFlinger->mFrameTracer->onDestroy(layerId);
245
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000246 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700247 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700248
249 if (mDrawingState.sidebandStream != nullptr) {
250 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
251 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700252 if (mHadClonedChild) {
Vishnu Nair3be61902023-04-26 19:47:29 -0700253 auto& roots = mFlinger->mLayerMirrorRoots;
254 roots.erase(std::remove(roots.begin(), roots.end(), this), roots.end());
Robert Carr6a0382d2021-07-01 15:57:17 -0700255 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000256 if (hasTrustedPresentationListener()) {
257 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000258 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000259 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700260}
261
Mathias Agopian13127d82013-03-05 17:47:11 -0800262// ---------------------------------------------------------------------------
263// callbacks
264// ---------------------------------------------------------------------------
265
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700266void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700267 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700268 return;
269 }
Robert Carr2e102c92018-10-23 12:11:15 -0700270
Robert Carr6a160312021-05-17 12:08:20 -0700271 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700272 if (strongRelative == nullptr) {
273 setZOrderRelativeOf(nullptr);
274 return;
275 }
276
277 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700278 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700279 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800280 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700281 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700282}
283
284void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700285 if (!mRemovedFromDrawingState) {
286 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700287 mFlinger->mScheduler->deregisterLayer(this);
288 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000289 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000290
Ady Abrahamd11bade2022-08-01 16:18:03 -0700291 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700292}
Chia-I Wu38512252017-05-17 14:36:16 -0700293
chaviw68d4dab2020-06-08 15:07:32 -0700294sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000295 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700296 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700297 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700298 }
299 return parent->getRootLayer();
300}
301
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700302void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700303 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
304 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700305 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700306
Josh Gao194ff392022-09-08 16:19:29 -0700307 REQUIRE_MUTEX(mFlinger->mStateLock);
308 traverse(LayerVector::StateSet::Current,
309 [&](Layer* layer) REQUIRES(layer->mFlinger->mStateLock) {
310 layer->removeFromCurrentState();
311 layer->removeRelativeZ(layersInTree);
312 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700313}
314
chaviw61626f22018-11-15 16:26:27 -0800315void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700316 if (mRemovedFromDrawingState) {
317 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700318 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700319 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700320 }
chaviw61626f22018-11-15 16:26:27 -0800321
322 for (const auto& child : mCurrentChildren) {
323 child->addToCurrentState();
324 }
325}
326
Mathias Agopian13127d82013-03-05 17:47:11 -0800327// ---------------------------------------------------------------------------
328// set-up
329// ---------------------------------------------------------------------------
330
chaviw13fdc492017-06-27 12:40:18 -0700331bool Layer::getPremultipledAlpha() const {
332 return mPremultipliedAlpha;
333}
334
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700335sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800336 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700337 if (mGetHandleCalled) {
338 ALOGE("Get handle called twice" );
339 return nullptr;
340 }
341 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700342 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000343 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800344}
345
346// ---------------------------------------------------------------------------
347// h/w composer set-up
348// ---------------------------------------------------------------------------
349
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700350static Rect reduce(const Rect& win, const Region& exclude) {
351 if (CC_LIKELY(exclude.isEmpty())) {
352 return win;
353 }
354 if (exclude.isRect()) {
355 return win.reduce(exclude.getBounds());
356 }
357 return Region(win).subtract(exclude).getBounds();
358}
359
Dan Stoza80d61162017-12-20 15:57:52 -0800360static FloatRect reduce(const FloatRect& win, const Region& exclude) {
361 if (CC_LIKELY(exclude.isEmpty())) {
362 return win;
363 }
364 // Convert through Rect (by rounding) for lack of FloatRegion
365 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
366}
367
Vishnu Nair4351ad52019-02-11 14:13:02 -0800368Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800369 if (!reduceTransparentRegion) {
370 return Rect{mScreenBounds};
371 }
372
373 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800374 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800375 // Transform to screen space.
376 bounds = t.transform(bounds);
377 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700378}
379
Vishnu Nair4351ad52019-02-11 14:13:02 -0800380FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000381 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800382 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700383}
384
Vishnu Nairf0c28512019-02-08 12:40:28 -0800385FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
386 // Subtract the transparent region and snap to the bounds.
387 return reduce(mBounds, activeTransparentRegion);
388}
389
Chavi Weingarten076acac2023-01-19 17:20:43 +0000390// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000391void Layer::updateTrustedPresentationState(const DisplayDevice* display,
392 const frontend::LayerSnapshot* snapshot,
393 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000394 if (!hasTrustedPresentationListener()) {
395 return;
396 }
397 const bool lastState = mLastComputedTrustedPresentationState;
398 mLastComputedTrustedPresentationState = false;
399
400 if (!leaveState) {
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000401 const auto outputLayer = findOutputLayerForDisplay(display, snapshot->path);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000402 if (outputLayer != nullptr) {
403 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
404 Region coveredRegion =
405 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
406 mLastComputedTrustedPresentationState =
407 computeTrustedPresentationState(snapshot->geomLayerBounds,
408 snapshot->sourceBounds(), coveredRegion,
409 snapshot->transformedBounds,
410 snapshot->alpha,
411 snapshot->geomLayerTransform,
412 mTrustedPresentationThresholds);
413 } else {
414 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
415 "TrustedPresentationState",
416 getDebugName());
417 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000418 }
419 }
420 const bool newState = mLastComputedTrustedPresentationState;
421 if (lastState && !newState) {
422 // We were in the trusted presentation state, but now we left it,
423 // emit the callback if needed
424 if (mLastReportedTrustedPresentationState) {
425 mLastReportedTrustedPresentationState = false;
426 mTrustedPresentationListener.invoke(false);
427 }
428 // Reset the timer
429 mEnteredTrustedPresentationStateTime = -1;
430 } else if (!lastState && newState) {
431 // We were not in the trusted presentation state, but we entered it, begin the timer
432 // and make sure this gets called at least once more!
433 mEnteredTrustedPresentationStateTime = time_in_ms;
434 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
435 }
436
437 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
438 if (!mLastReportedTrustedPresentationState && newState &&
439 (time_in_ms - mEnteredTrustedPresentationStateTime >
440 mTrustedPresentationThresholds.stabilityRequirementMs)) {
441 mLastReportedTrustedPresentationState = true;
442 mTrustedPresentationListener.invoke(true);
443 }
444}
445
446/**
447 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
448 * of how the parameters and thresholds are interpreted. The general spirit is
449 * to produce an upper bound on the amount of the buffer which was presented.
450 */
451bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
452 const Region& coveredRegion,
453 const FloatRect& screenBounds, float alpha,
454 const ui::Transform& effectiveTransform,
455 const TrustedPresentationThresholds& thresholds) {
456 if (alpha < thresholds.minAlpha) {
457 return false;
458 }
459 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
460 return false;
461 }
462 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
463 return false;
464 }
465
466 const float sx = effectiveTransform.dsdx();
467 const float sy = effectiveTransform.dsdy();
468 float fractionRendered = std::min(sx * sy, 1.0f);
469
470 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
471 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
472 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
473
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000474 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
475 // Compute the size of all the rects since they may be disconnected.
476 float coveredSize = 0;
477 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
478 float size = rect->width() * rect->height();
479 coveredSize += size;
480 }
481
482 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000483
484 if (fractionRendered < thresholds.minFractionRendered) {
485 return false;
486 }
487
488 return true;
489}
490
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700491void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
492 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800493 const State& s(getDrawingState());
494
495 // Calculate effective layer transform
496 mEffectiveTransform = parentTransform * getActiveTransform(s);
497
Garfield Tan2c1782c2022-02-16 15:25:05 -0800498 if (CC_UNLIKELY(!isTransformValid())) {
499 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
500 getDebugName());
501 return;
502 }
503
Vishnu Nair4351ad52019-02-11 14:13:02 -0800504 // Transform parent bounds to layer space
505 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
506
Vishnu Nairc652ff82019-03-15 12:48:54 -0700507 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800508 mSourceBounds = computeSourceBounds(parentBounds);
509
510 // Calculate bounds by croping diplay frame with layer crop and parent bounds
511 FloatRect bounds = mSourceBounds;
512 const Rect layerCrop = getCrop(s);
513 if (!layerCrop.isEmpty()) {
514 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
515 }
516 bounds = bounds.intersect(parentBounds);
517
518 mBounds = bounds;
519 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700520
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700521 // Use the layer's own shadow radius if set. Otherwise get the radius from
522 // parent.
523 if (s.shadowRadius > 0.f) {
524 mEffectiveShadowRadius = s.shadowRadius;
525 } else {
526 mEffectiveShadowRadius = parentShadowRadius;
527 }
528
529 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
530 // don't pass it to its children.
531 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
532
Vishnu Nair4351ad52019-02-11 14:13:02 -0800533 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700534 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800535 }
Vishnu Nairba354102022-08-01 00:14:18 +0000536
537 if (mPotentialCursor) {
538 prepareCursorCompositionState();
539 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800540}
541
Vishnu Nair60356342018-11-13 13:00:45 -0800542Rect Layer::getCroppedBufferSize(const State& s) const {
543 Rect size = getBufferSize(s);
544 Rect crop = getCrop(s);
545 if (!crop.isEmpty() && size.isValid()) {
546 size.intersect(crop, &size);
547 } else if (!crop.isEmpty()) {
548 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700549 }
Vishnu Nair60356342018-11-13 13:00:45 -0800550 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800551}
552
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700553void Layer::setupRoundedCornersCropCoordinates(Rect win,
554 const FloatRect& roundedCornersCrop) const {
555 // Translate win by the rounded corners rect coordinates, to have all values in
556 // layer coordinate space.
557 win.left -= roundedCornersCrop.left;
558 win.right -= roundedCornersCrop.left;
559 win.top -= roundedCornersCrop.top;
560 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700561}
562
Lloyd Piquede196652020-01-22 17:29:58 -0800563void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800564 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800565 const auto alpha = static_cast<float>(getAlpha());
566 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700567 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800568
569 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
570 if (!opaque || alpha != 1.0f) {
571 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
572 : Hwc2::IComposerClient::BlendMode::COVERAGE;
573 }
574
Alec Mourif4af03e2023-02-11 00:25:24 +0000575 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000576 auto* snapshot = editLayerSnapshot();
577 snapshot->outputFilter = getOutputFilter();
578 snapshot->isVisible = isVisible();
579 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
Vishnu Naird9e4f462023-10-06 04:05:45 +0000580 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800581
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000582 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800583 contentDirty = false;
584
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000585 snapshot->geomLayerBounds = mBounds;
586 snapshot->geomLayerTransform = getTransform();
587 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
588 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000589 snapshot->localTransform = getActiveTransform(drawingState);
590 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000591 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
592 snapshot->alpha = alpha;
Vishnu Nairc6384702023-07-31 12:22:20 -0700593 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
594 snapshot->blurRegions = getBlurRegions();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000595 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800596}
597
Lloyd Piquede196652020-01-22 17:29:58 -0800598void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800599 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000600 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700601
Alec Mourif4af03e2023-02-11 00:25:24 +0000602 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000603 snapshot->geomBufferSize = getBufferSize(drawingState);
604 snapshot->geomContentCrop = getBufferCrop();
605 snapshot->geomCrop = getCrop(drawingState);
606 snapshot->geomBufferTransform = getBufferTransform();
607 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
608 snapshot->geomUsesSourceCrop = usesSourceCrop();
609 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800610
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000611 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800612 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
613 for (const auto& [key, mandatory] : supportedMetadata) {
614 const auto& genericLayerMetadataCompatibilityMap =
615 mFlinger->getGenericLayerMetadataKeyMap();
616 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
617 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
618 continue;
619 }
620 const uint32_t id = compatIter->second;
621
622 auto it = drawingState.metadata.mMap.find(id);
623 if (it == std::end(drawingState.metadata.mMap)) {
624 continue;
625 }
626
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000627 snapshot->metadata.emplace(key,
628 compositionengine::GenericLayerMetadataEntry{mandatory,
629 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800630 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800631}
David Sodmanba340492018-08-05 21:51:33 -0700632
Lloyd Piquede196652020-01-22 17:29:58 -0800633void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800634 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000635 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000636 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800637
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000638 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800639
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000640 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
641 snapshot->dataspace = getDataSpace();
642 snapshot->colorTransform = getColorTransform();
643 snapshot->colorTransformIsIdentity = !hasColorTransform();
644 snapshot->surfaceDamage = surfaceDamageRegion;
645 snapshot->hasProtectedContent = isProtected();
646 snapshot->dimmingEnabled = isDimmingEnabled();
Sally Qi963049b2023-03-23 14:06:21 -0700647 snapshot->currentHdrSdrRatio = getCurrentHdrSdrRatio();
648 snapshot->desiredHdrSdrRatio = getDesiredHdrSdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000649 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800650
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700651 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700652
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000653 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800654
655 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400656 // Rounded corners no longer force client composition, since we may use a
657 // hole punch so that the layer will appear to have rounded corners.
Alec Mouri994761f2023-08-04 21:50:55 +0000658 if (drawShadows() || snapshot->stretchEffect.hasEffect()) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000659 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800660 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700661 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairc6384702023-07-31 12:22:20 -0700662 snapshot->blurRegions = getBlurRegions();
663 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400664
665 // Layer framerate is used in caching decisions.
666 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
667 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000668 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000669
670 if (hasBufferOrSidebandStream()) {
671 preparePerFrameBufferCompositionState();
672 } else {
673 preparePerFrameEffectsCompositionState();
674 }
675}
676
677void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000678 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000679 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000680 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000681 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
682 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000683 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
684 return;
685 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000686 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000687 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800688 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
689 snapshot->compositionType =
690 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000691 } else {
692 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000693 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
694 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000695 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
696 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
697 }
698
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000699 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000700 snapshot->acquireFence = mBufferInfo.mFence;
701 snapshot->frameNumber = mBufferInfo.mFrameNumber;
702 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000703}
704
705void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000706 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000707 auto* snapshot = editLayerSnapshot();
708 snapshot->color = getColor();
709 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000710 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800711}
712
Lloyd Piquede196652020-01-22 17:29:58 -0800713void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800714 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000715 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000716 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800717
718 // Apply the layer's transform, followed by the display's global transform
719 // Here we're guaranteed that the layer's transform preserves rects
720 Rect win = getCroppedBufferSize(drawingState);
721 // Subtract the transparent region and snap to the bounds
722 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
723 Rect frame(getTransform().transform(bounds));
724
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000725 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800726}
727
Lloyd Piquea83776c2019-01-29 18:42:32 -0800728const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700729 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800730}
731
Mathias Agopian13127d82013-03-05 17:47:11 -0800732// ---------------------------------------------------------------------------
733// drawing...
734// ---------------------------------------------------------------------------
735
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500736aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
737 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700738 const auto outputLayer = findOutputLayerForDisplay(&display);
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000739 return getCompositionType(outputLayer);
740}
741
742aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
743 const compositionengine::OutputLayer* outputLayer) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -0800744 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500745 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800746 }
747 if (outputLayer->getState().hwc) {
748 return (*outputLayer->getState().hwc).hwcCompositionType;
749 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500750 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800751 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800752}
753
Mathias Agopian13127d82013-03-05 17:47:11 -0800754// ----------------------------------------------------------------------------
755// local state
756// ----------------------------------------------------------------------------
757
David Sodman41fdfc92017-11-06 16:09:56 -0800758bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800759 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700760 if (s.flags & layer_state_t::eLayerSecure) {
761 return true;
762 }
763
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000764 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700765 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700766}
767
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100768void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
769 std::vector<JankData>& jankData) {
770 if (mPendingJankClassifications.empty() ||
771 !mPendingJankClassifications.front()->getJankType()) {
772 return;
773 }
774
775 bool includeJankData = false;
776 for (const auto& handle : handles) {
777 for (const auto& cb : handle->callbackIds) {
778 if (cb.includeJankData) {
779 includeJankData = true;
780 break;
781 }
782 }
783
784 if (includeJankData) {
785 jankData.reserve(mPendingJankClassifications.size());
786 break;
787 }
788 }
789
790 while (!mPendingJankClassifications.empty() &&
791 mPendingJankClassifications.front()->getJankType()) {
792 if (includeJankData) {
793 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
794 mPendingJankClassifications.front();
Pascal Muetschardac7bcd92023-10-03 15:05:36 +0200795 jankData.emplace_back(JankData(surfaceFrame->getToken(),
796 surfaceFrame->getJankType().value(),
797 surfaceFrame->getRenderRate().getPeriodNsecs()));
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100798 }
799 mPendingJankClassifications.pop_front();
800 }
801}
802
Mathias Agopian13127d82013-03-05 17:47:11 -0800803// ----------------------------------------------------------------------------
804// transaction
805// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800806
Vishnu Naira156f482023-02-22 00:23:38 +0000807uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700808 ATRACE_CALL();
809
Robert Carr0758e5d2021-03-11 22:15:04 -0800810 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700811 mDrawingStateModified = mDrawingState.modified;
812 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700813
Alec Mourib416efd2018-09-06 21:01:59 +0000814 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700815
Robert Carr6a160312021-05-17 12:08:20 -0700816 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800817 // invalidate and recompute the visible regions if needed
818 flags |= Layer::eVisibleRegion;
819 }
820
Robert Carr6a160312021-05-17 12:08:20 -0700821 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800822 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000823 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800824 flags |= eVisibleRegion;
825 this->contentDirty = true;
826
827 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700828 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800829 }
830
Arthur Hung9ed43392022-05-27 06:31:57 +0000831 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
832 mFlinger->mUpdateInputInfo = true;
833 }
834
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700835 commitTransaction();
Robert Carra1257842020-01-31 13:48:28 -0800836
Mathias Agopian13127d82013-03-05 17:47:11 -0800837 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800838}
839
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700840void Layer::commitTransaction() {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000841 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
842 // bufferSurfaceFrameTX will be presented in latchBuffer.
843 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
844 if (surfaceFrame->getPresentState() != PresentState::Presented) {
845 // With applyPendingStates, we could end up having presented surfaceframes from previous
846 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800847 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000848 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
849 }
850 }
Robert Carr6a160312021-05-17 12:08:20 -0700851 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700852}
853
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700854uint32_t Layer::clearTransactionFlags(uint32_t mask) {
855 const auto flags = mTransactionFlags & mask;
856 mTransactionFlags &= ~mask;
857 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800858}
859
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700860void Layer::setTransactionFlags(uint32_t mask) {
861 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800862}
863
Robert Carr1f0a16a2016-10-24 16:27:39 -0700864bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
865 ssize_t idx = mCurrentChildren.indexOf(childLayer);
866 if (idx < 0) {
867 return false;
868 }
869 if (childLayer->setLayer(z)) {
870 mCurrentChildren.removeAt(idx);
871 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800872 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700873 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800874 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700875}
876
Robert Carr503c7042017-09-27 15:06:08 -0700877bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
878 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
879 ssize_t idx = mCurrentChildren.indexOf(childLayer);
880 if (idx < 0) {
881 return false;
882 }
883 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
884 mCurrentChildren.removeAt(idx);
885 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800886 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700887 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800888 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700889}
890
Robert Carrae060832016-11-28 10:51:00 -0800891bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700892 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
893 mDrawingState.sequence++;
894 mDrawingState.z = z;
895 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700896
Robert Carra70e91c2021-06-11 13:59:52 -0700897 mFlinger->mSomeChildrenChanged = true;
898
Robert Carrdb66e622017-04-10 16:55:57 -0700899 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700900 if (mDrawingState.zOrderRelativeOf != nullptr) {
901 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700902 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700903 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700904 }
chaviw606e5cf2019-03-01 10:12:10 -0800905 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700906 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800907 setTransactionFlags(eTransactionNeeded);
908 return true;
909}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700910
Robert Carrdb66e622017-04-10 16:55:57 -0700911void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700912 mDrawingState.zOrderRelatives.remove(relative);
913 mDrawingState.sequence++;
914 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700915 setTransactionFlags(eTransactionNeeded);
916}
917
918void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700919 mDrawingState.zOrderRelatives.add(relative);
920 mDrawingState.modified = true;
921 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700922 setTransactionFlags(eTransactionNeeded);
923}
924
chaviw606e5cf2019-03-01 10:12:10 -0800925void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700926 mDrawingState.zOrderRelativeOf = relativeOf;
927 mDrawingState.sequence++;
928 mDrawingState.modified = true;
929 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700930
chaviw606e5cf2019-03-01 10:12:10 -0800931 setTransactionFlags(eTransactionNeeded);
932}
933
Robert Carr503d2bd2017-12-04 15:49:47 -0800934bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000935 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700936 if (relative == nullptr) {
937 return false;
938 }
939
Robert Carr6a160312021-05-17 12:08:20 -0700940 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
941 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800942 return false;
943 }
944
Robert Carr88b85e12022-03-21 15:47:35 -0700945 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
946 (relative->mDrawingState.zOrderRelativeOf == this)) {
947 ALOGE("Detected relative layer loop between %s and %s",
948 mName.c_str(), relative->mName.c_str());
949 ALOGE("Ignoring new call to set relative layer");
950 return false;
951 }
952
Robert Carra70e91c2021-06-11 13:59:52 -0700953 mFlinger->mSomeChildrenChanged = true;
954
Robert Carr6a160312021-05-17 12:08:20 -0700955 mDrawingState.sequence++;
956 mDrawingState.modified = true;
957 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700958
Robert Carr6a160312021-05-17 12:08:20 -0700959 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700960 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700961 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700962 }
chaviw606e5cf2019-03-01 10:12:10 -0800963 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700964 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700965
966 setTransactionFlags(eTransactionNeeded);
967
968 return true;
969}
970
Winson Chunga30f7c92021-06-29 15:42:56 -0700971bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
972 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
973 mDrawingState.isTrustedOverlay = isTrustedOverlay;
974 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000975 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700976 setTransactionFlags(eTransactionNeeded);
977 return true;
978}
979
980bool Layer::isTrustedOverlay() const {
981 if (getDrawingState().isTrustedOverlay) {
982 return true;
983 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000984 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700985 return (p != nullptr) && p->isTrustedOverlay();
986}
987
Dan Stoza9e56aa02015-11-02 13:00:03 -0800988bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700989 if (mDrawingState.color.a == alpha) return false;
990 mDrawingState.sequence++;
991 mDrawingState.color.a = alpha;
992 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800993 setTransactionFlags(eTransactionNeeded);
994 return true;
995}
chaviw13fdc492017-06-27 12:40:18 -0700996
Valerie Haudd0b7572019-01-29 14:59:27 -0800997bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700998 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700999 return false;
Valerie Hauaa194562019-02-05 16:21:38 -08001000 }
Robert Carr6a160312021-05-17 12:08:20 -07001001 mDrawingState.sequence++;
1002 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -08001003 setTransactionFlags(eTransactionNeeded);
1004
Robert Carr6a160312021-05-17 12:08:20 -07001005 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001006 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001007 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001008 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001009 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Kean Mariotti4ba343c2023-04-19 13:31:02 +00001010 surfaceflinger::LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
1011 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001012
Valerie Haudd0b7572019-01-29 14:59:27 -08001013 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001014 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001015 mFlinger->mLayersAdded = true;
1016 // set up SF to handle added color layer
1017 if (isRemovedFromCurrentState()) {
Josh Gao194ff392022-09-08 16:19:29 -07001018 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001019 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001020 }
1021 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001022 } else if (mDrawingState.bgColorLayer && alpha == 0) {
Josh Gao194ff392022-09-08 16:19:29 -07001023 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001024 mDrawingState.bgColorLayer->reparent(nullptr);
1025 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001026 return true;
1027 }
1028
Robert Carr6a160312021-05-17 12:08:20 -07001029 mDrawingState.bgColorLayer->setColor(color);
1030 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1031 mDrawingState.bgColorLayer->setAlpha(alpha);
1032 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001033
chaviw13fdc492017-06-27 12:40:18 -07001034 return true;
1035}
1036
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001037bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001038 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001039
Robert Carr6a160312021-05-17 12:08:20 -07001040 mDrawingState.sequence++;
1041 mDrawingState.cornerRadius = cornerRadius;
1042 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001043 setTransactionFlags(eTransactionNeeded);
1044 return true;
1045}
1046
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001047bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001048 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001049 // If we start or stop drawing blur then the layer's visibility state may change so increment
1050 // the magic sequence number.
1051 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1052 mDrawingState.sequence++;
1053 }
Robert Carr6a160312021-05-17 12:08:20 -07001054 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1055 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001056 setTransactionFlags(eTransactionNeeded);
1057 return true;
1058}
Marissa Wall61c58622018-07-18 10:12:20 -07001059
Mathias Agopian13127d82013-03-05 17:47:11 -08001060bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001061 mDrawingState.sequence++;
1062 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001063 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001064 setTransactionFlags(eTransactionNeeded);
1065 return true;
1066}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001067
Lucas Dupinc3800b82020-10-02 16:24:48 -07001068bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001069 // If we start or stop drawing blur then the layer's visibility state may change so increment
1070 // the magic sequence number.
1071 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1072 mDrawingState.sequence++;
1073 }
Robert Carr6a160312021-05-17 12:08:20 -07001074 mDrawingState.blurRegions = blurRegions;
1075 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001076 setTransactionFlags(eTransactionNeeded);
1077 return true;
1078}
1079
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001080bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001081 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1082 if (mDrawingState.flags == newFlags) return false;
1083 mDrawingState.sequence++;
1084 mDrawingState.flags = newFlags;
1085 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001086 setTransactionFlags(eTransactionNeeded);
1087 return true;
1088}
Robert Carr99e27f02016-06-16 15:18:02 -07001089
chaviw25714502021-02-11 10:01:08 -08001090bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001091 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001092 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001093 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001094
Robert Carr6a160312021-05-17 12:08:20 -07001095 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001096 setTransactionFlags(eTransactionNeeded);
1097 return true;
1098}
Robert Carr8d5227b2017-03-16 15:41:03 -07001099
Evan Roskyef876c92019-01-25 17:46:06 -08001100bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001101 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1102 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001103 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001104 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001105}
1106
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001107bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001108 if (mDrawingState.layerStack == layerStack) return false;
1109 mDrawingState.sequence++;
1110 mDrawingState.layerStack = layerStack;
1111 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001112 setTransactionFlags(eTransactionNeeded);
1113 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001114}
1115
Peiyong Linc502cb72019-03-01 15:00:23 -08001116bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001117 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001118 return false;
1119 }
Robert Carr6a160312021-05-17 12:08:20 -07001120 mDrawingState.sequence++;
1121 mDrawingState.colorSpaceAgnostic = agnostic;
1122 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001123 setTransactionFlags(eTransactionNeeded);
1124 return true;
1125}
1126
Sally Qi81d95e62022-03-21 19:41:33 -07001127bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1128 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1129
1130 mDrawingState.sequence++;
1131 mDrawingState.dimmingEnabled = dimmingEnabled;
1132 mDrawingState.modified = true;
1133 setTransactionFlags(eTransactionNeeded);
1134 return true;
1135}
1136
Ana Krulecc84d09b2019-11-02 23:10:29 +01001137bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001138 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1139 mDrawingState.frameRateSelectionPriority = priority;
1140 mDrawingState.sequence++;
1141 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001142 setTransactionFlags(eTransactionNeeded);
1143 return true;
1144}
1145
1146int32_t Layer::getFrameRateSelectionPriority() const {
1147 // Check if layer has priority set.
1148 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1149 return mDrawingState.frameRateSelectionPriority;
1150 }
1151 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001152 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001153 if (parent != nullptr) {
1154 return parent->getFrameRateSelectionPriority();
1155 }
1156
1157 return Layer::PRIORITY_UNSET;
1158}
1159
Andy Labrada096227e2022-06-15 16:58:11 +00001160bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1161 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1162 mDrawingState.defaultFrameRateCompatibility = compatibility;
1163 mDrawingState.modified = true;
Vishnu Nair80e8cfe2023-09-29 17:03:45 -07001164 mFlinger->mScheduler->setDefaultFrameRateCompatibility(sequence, compatibility);
Andy Labrada096227e2022-06-15 16:58:11 +00001165 setTransactionFlags(eTransactionNeeded);
1166 return true;
1167}
1168
Vishnu Nair3fbe3262023-09-29 17:07:00 -07001169scheduler::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
Andy Labrada096227e2022-06-15 16:58:11 +00001170 return mDrawingState.defaultFrameRateCompatibility;
1171}
1172
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001173bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1174 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1175};
1176
Vishnu Nair73908d12022-10-24 21:46:42 -07001177ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1178 bool useDrawing = state == LayerVector::StateSet::Drawing;
1179 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1180 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001181 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001182 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001183 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001184}
1185
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001186bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001187 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001188 return false;
1189 }
1190
Robert Carr6a160312021-05-17 12:08:20 -07001191 mDrawingState.sequence++;
1192 mDrawingState.shadowRadius = shadowRadius;
1193 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001194 setTransactionFlags(eTransactionNeeded);
1195 return true;
1196}
1197
Vishnu Nair6213bd92020-05-08 17:42:25 -07001198bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001199 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001200 return false;
1201 }
1202
Robert Carr6a160312021-05-17 12:08:20 -07001203 mDrawingState.sequence++;
1204 mDrawingState.fixedTransformHint = fixedTransformHint;
1205 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001206 setTransactionFlags(eTransactionNeeded);
1207 return true;
1208}
1209
John Reckcdb4ed72021-02-04 13:39:33 -05001210bool Layer::setStretchEffect(const StretchEffect& effect) {
1211 StretchEffect temp = effect;
1212 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001213 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001214 return false;
1215 }
Robert Carr6a160312021-05-17 12:08:20 -07001216 mDrawingState.sequence++;
1217 mDrawingState.stretchEffect = temp;
1218 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001219 setTransactionFlags(eTransactionNeeded);
1220 return true;
1221}
1222
John Reckc00c6692021-02-16 11:37:33 -05001223StretchEffect Layer::getStretchEffect() const {
1224 if (mDrawingState.stretchEffect.hasEffect()) {
1225 return mDrawingState.stretchEffect;
1226 }
1227
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001228 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001229 if (parent != nullptr) {
1230 auto effect = parent->getStretchEffect();
1231 if (effect.hasEffect()) {
1232 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1233 return effect;
1234 }
1235 }
1236 return StretchEffect{};
1237}
1238
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001239bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1240 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001241 return false;
1242 }
1243 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001244 mBorderWidth = width;
1245 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001246 return true;
1247}
1248
1249bool Layer::isBorderEnabled() {
1250 return mBorderEnabled;
1251}
1252
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001253float Layer::getBorderWidth() {
1254 return mBorderWidth;
1255}
1256
1257const half4& Layer::getBorderColor() {
1258 return mBorderColor;
1259}
1260
Rachel Lee0faad6c2023-09-08 13:34:34 -07001261bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool overrideChildren,
1262 bool* transactionNeeded) {
1263 // Gets the frame rate to propagate to children.
Ady Abrahama850c182021-08-04 13:04:37 -07001264 const auto frameRate = [&] {
Rachel Lee0faad6c2023-09-08 13:34:34 -07001265 if (overrideChildren && parentFrameRate.isValid()) {
1266 return parentFrameRate;
1267 }
1268
Rachel Leece6e0042023-06-27 11:22:54 -07001269 if (mDrawingState.frameRate.isValid()) {
Ady Abrahama850c182021-08-04 13:04:37 -07001270 return mDrawingState.frameRate;
1271 }
1272
1273 return parentFrameRate;
1274 }();
1275
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001276 auto now = systemTime();
1277 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate, now);
Ady Abrahama850c182021-08-04 13:04:37 -07001278
Rachel Leea021bb02023-11-20 21:51:09 -08001279 // The frame rate is propagated to the children by default, but some properties may override it.
Ady Abrahama850c182021-08-04 13:04:37 -07001280 bool childrenHaveFrameRate = false;
Rachel Leea021bb02023-11-20 21:51:09 -08001281 const bool overrideChildrenFrameRate = overrideChildren || shouldOverrideChildrenFrameRate();
1282 const bool canPropagateFrameRate = shouldPropagateFrameRate() || overrideChildrenFrameRate;
Ady Abrahama850c182021-08-04 13:04:37 -07001283 for (const sp<Layer>& child : mCurrentChildren) {
1284 childrenHaveFrameRate |=
Rachel Leea021bb02023-11-20 21:51:09 -08001285 child->propagateFrameRateForLayerTree(canPropagateFrameRate ? frameRate
1286 : FrameRate(),
1287 overrideChildrenFrameRate, transactionNeeded);
Ady Abrahama850c182021-08-04 13:04:37 -07001288 }
1289
Rachel Leece6e0042023-06-27 11:22:54 -07001290 // If we don't have a valid frame rate specification, but the children do, we set this
Ady Abrahama850c182021-08-04 13:04:37 -07001291 // layer as NoVote to allow the children to control the refresh rate
Rachel Leece6e0042023-06-27 11:22:54 -07001292 if (!frameRate.isValid() && childrenHaveFrameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001293 *transactionNeeded |=
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001294 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote),
1295 now);
Ady Abrahama850c182021-08-04 13:04:37 -07001296 }
1297
Rachel Leece6e0042023-06-27 11:22:54 -07001298 // We return whether this layer or its children has a vote. We ignore ExactOrMultiple votes for
Ady Abrahama850c182021-08-04 13:04:37 -07001299 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001300 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001301 const auto layerVotedWithDefaultCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001302 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Default;
1303 const auto layerVotedWithNoVote = frameRate.vote.type == FrameRateCompatibility::NoVote;
1304 const auto layerVotedWithCategory = frameRate.category != FrameRateCategory::Default;
Ady Abrahama850c182021-08-04 13:04:37 -07001305 const auto layerVotedWithExactCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001306 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Exact;
1307 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote || layerVotedWithCategory ||
Ady Abrahama850c182021-08-04 13:04:37 -07001308 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1309}
1310
Ady Abraham60e42ea2020-03-09 19:17:31 -07001311void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001312 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001313 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001314 while (auto parent = layer->getParent()) {
1315 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001316 }
Ady Abrahama850c182021-08-04 13:04:37 -07001317 return layer;
1318 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001319
Ady Abraham60e42ea2020-03-09 19:17:31 -07001320 bool transactionNeeded = false;
Rachel Lee0faad6c2023-09-08 13:34:34 -07001321 root->propagateFrameRateForLayerTree({}, false, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001322
Ady Abrahama850c182021-08-04 13:04:37 -07001323 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001324 if (transactionNeeded) {
1325 mFlinger->setTransactionFlags(eTraversalNeeded);
1326 }
1327}
1328
Rachel Leece6e0042023-06-27 11:22:54 -07001329bool Layer::setFrameRate(FrameRate::FrameRateVote frameRateVote) {
1330 if (mDrawingState.frameRate.vote == frameRateVote) {
Steven Thomas3172e202020-01-06 19:25:30 -08001331 return false;
1332 }
1333
Robert Carr6a160312021-05-17 12:08:20 -07001334 mDrawingState.sequence++;
Rachel Leece6e0042023-06-27 11:22:54 -07001335 mDrawingState.frameRate.vote = frameRateVote;
1336 mDrawingState.modified = true;
1337
1338 updateTreeHasFrameRateVote();
1339
1340 setTransactionFlags(eTransactionNeeded);
1341 return true;
1342}
1343
Rachel Lee67afbea2023-09-28 15:35:07 -07001344bool Layer::setFrameRateCategory(FrameRateCategory category, bool smoothSwitchOnly) {
1345 if (mDrawingState.frameRate.category == category &&
1346 mDrawingState.frameRate.categorySmoothSwitchOnly == smoothSwitchOnly) {
Rachel Leece6e0042023-06-27 11:22:54 -07001347 return false;
1348 }
1349
1350 mDrawingState.sequence++;
1351 mDrawingState.frameRate.category = category;
Rachel Lee67afbea2023-09-28 15:35:07 -07001352 mDrawingState.frameRate.categorySmoothSwitchOnly = smoothSwitchOnly;
Robert Carr6a160312021-05-17 12:08:20 -07001353 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001354
1355 updateTreeHasFrameRateVote();
1356
Steven Thomas3172e202020-01-06 19:25:30 -08001357 setTransactionFlags(eTransactionNeeded);
1358 return true;
1359}
1360
Rachel Lee58cc90d2023-09-05 18:50:20 -07001361bool Layer::setFrameRateSelectionStrategy(FrameRateSelectionStrategy strategy) {
1362 if (mDrawingState.frameRateSelectionStrategy == strategy) return false;
1363 mDrawingState.frameRateSelectionStrategy = strategy;
1364 mDrawingState.sequence++;
1365 mDrawingState.modified = true;
Rachel Leed7479502023-09-25 17:02:35 -07001366
1367 updateTreeHasFrameRateVote();
Rachel Lee58cc90d2023-09-05 18:50:20 -07001368 setTransactionFlags(eTransactionNeeded);
1369 return true;
1370}
1371
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001372void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1373 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001374 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001375
1376 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1377 // there are two transactions with the same token, the first one without a buffer and the
1378 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1379 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001380 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1381 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001382 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001383 mDrawingState.bufferSurfaceFrameTX = it->second;
1384 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1385 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1386 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001387 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001388 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001389 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1390 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001391
1392 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001393}
1394
1395void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1396 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001397 mDrawingState.frameTimelineInfo = info;
1398 mDrawingState.postTime = postTime;
1399 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001400 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001401
Robert Carr6a160312021-05-17 12:08:20 -07001402 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001403 bufferSurfaceFrameTX != nullptr) {
1404 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1405 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1406 // being used for BufferSurfaceFrame, don't create a new one.
1407 return;
1408 }
1409 }
1410 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1411 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1412 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001413 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1414 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001415 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001416 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001417 } else {
1418 if (it->second->getPresentState() == PresentState::Presented) {
1419 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1420 // have been from previous vsync.
1421 it->second = createSurfaceFrameForTransaction(info, postTime);
1422 }
1423 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001424
1425 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001426}
1427
1428void Layer::addSurfaceFrameDroppedForBuffer(
Ady Abraham5a3e3562023-06-07 10:32:08 -07001429 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t dropTime) {
1430 surfaceFrame->setDropTime(dropTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001431 surfaceFrame->setPresentState(PresentState::Dropped);
1432 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1433}
1434
1435void Layer::addSurfaceFramePresentedForBuffer(
1436 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1437 nsecs_t currentLatchTime) {
1438 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1439 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1440 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001441 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001442}
1443
1444std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1445 const FrameTimelineInfo& info, nsecs_t postTime) {
1446 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001447 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1448 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001449 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001450 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001451 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001452 // For Transactions, the post time is considered to be both queue and acquire fence time.
1453 surfaceFrame->setActualQueueTime(postTime);
1454 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001455 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1456 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001457 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001458 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001459 onSurfaceFrameCreated(surfaceFrame);
1460 return surfaceFrame;
1461}
1462
1463std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1464 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1465 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001466 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001467 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001468 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001469 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001470 // For buffers, acquire fence time will set during latch.
1471 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001472 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1473 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001474 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001475 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001476 onSurfaceFrameCreated(surfaceFrame);
1477 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001478}
1479
Ady Abraham5a3e3562023-06-07 10:32:08 -07001480void Layer::setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
1481 std::string debugName) {
1482 if (info.skippedFrameVsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
1483 return;
1484 }
1485
1486 FrameTimelineInfo skippedFrameTimelineInfo = info;
1487 skippedFrameTimelineInfo.vsyncId = info.skippedFrameVsyncId;
1488
1489 auto surfaceFrame =
1490 mFlinger->mFrameTimeline->createSurfaceFrameForToken(skippedFrameTimelineInfo,
1491 mOwnerPid, mOwnerUid,
1492 getSequence(), mName, debugName,
1493 /*isBuffer*/ false, getGameMode());
1494 surfaceFrame->setActualStartTime(skippedFrameTimelineInfo.skippedFrameStartTimeNanos);
1495 // For Transactions, the post time is considered to be both queue and acquire fence time.
1496 surfaceFrame->setActualQueueTime(postTime);
1497 surfaceFrame->setAcquireFenceTime(postTime);
1498 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1499 if (fps) {
1500 surfaceFrame->setRenderRate(*fps);
1501 }
1502 onSurfaceFrameCreated(surfaceFrame);
1503 addSurfaceFrameDroppedForBuffer(surfaceFrame, postTime);
1504}
1505
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001506bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate, nsecs_t now) {
Ady Abrahama850c182021-08-04 13:04:37 -07001507 if (mDrawingState.frameRateForLayerTree == frameRate) {
1508 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001509 }
1510
Ady Abrahama850c182021-08-04 13:04:37 -07001511 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001512
Ady Abrahama850c182021-08-04 13:04:37 -07001513 // TODO(b/195668952): we probably don't need to dirty visible regions here
1514 // or even store frameRateForLayerTree in mDrawingState
1515 mDrawingState.sequence++;
1516 mDrawingState.modified = true;
1517 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001518
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001519 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001520 ->recordLayerHistory(sequence, getLayerProps(), now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001521 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1522 return true;
1523}
Ady Abrahama850c182021-08-04 13:04:37 -07001524
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001525bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps,
1526 nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001527 if (mDrawingState.frameRateForLayerTree == frameRate) {
1528 return false;
1529 }
1530
1531 mDrawingState.frameRateForLayerTree = frameRate;
1532 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001533 ->recordLayerHistory(sequence, layerProps, now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001534 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001535 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001536}
1537
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001538Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1539 return getDrawingState().frameRateForLayerTree;
1540}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001541
Robert Carr1f0a16a2016-10-24 16:27:39 -07001542bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001543 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001544 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001545 if (parent != nullptr && parent->isHiddenByPolicy()) {
1546 return true;
1547 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001548 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1549 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1550 if (zOrderRelativeOf != nullptr) {
1551 if (zOrderRelativeOf->isHiddenByPolicy()) {
1552 return true;
1553 }
1554 }
1555 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001556 if (CC_UNLIKELY(!isTransformValid())) {
1557 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1558 return true;
1559 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001560 return s.flags & layer_state_t::eLayerHidden;
1561}
1562
David Sodman41fdfc92017-11-06 16:09:56 -08001563uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001564 // TODO: should we do something special if mSecure is set?
1565 if (mProtectedByApp) {
1566 // need a hardware-protected path to external video sink
1567 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001568 }
Riley Andrews03414a12014-07-01 14:22:59 -07001569 if (mPotentialCursor) {
1570 usage |= GraphicBuffer::USAGE_CURSOR;
1571 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001572 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001573 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001574}
1575
Vishnu Nair71fcf912022-10-18 09:14:20 -07001576void Layer::skipReportingTransformHint() {
1577 mSkipReportingTransformHint = true;
1578}
1579
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001580void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1581 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1582 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001583 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001584
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001585 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001586}
1587
Mathias Agopian13127d82013-03-05 17:47:11 -08001588// ----------------------------------------------------------------------------
1589// debugging
1590// ----------------------------------------------------------------------------
1591
Marissa Wall61c58622018-07-18 10:12:20 -07001592// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001593gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001594 using namespace std::string_literals;
1595
Huihong Luo05539a12022-02-23 10:29:40 -08001596 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001597 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001598 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001599 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001600 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001601 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001602
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001603 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001604 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001605 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001606 info.mX = ds.transform.tx();
1607 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001608 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001609 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001610 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001611 info.mFlags = ds.flags;
1612 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001613 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001614 info.mMatrix[0][0] = ds.transform[0][0];
1615 info.mMatrix[0][1] = ds.transform[0][1];
1616 info.mMatrix[1][0] = ds.transform[1][0];
1617 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001618 {
chaviwd62d3062019-09-04 14:48:02 -07001619 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001620 if (buffer != 0) {
1621 info.mActiveBufferWidth = buffer->getWidth();
1622 info.mActiveBufferHeight = buffer->getHeight();
1623 info.mActiveBufferStride = buffer->getStride();
1624 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001625 } else {
1626 info.mActiveBufferWidth = 0;
1627 info.mActiveBufferHeight = 0;
1628 info.mActiveBufferStride = 0;
1629 info.mActiveBufferFormat = 0;
1630 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001631 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001632 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001633 info.mIsOpaque = isOpaque(ds);
1634 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001635 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001636 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001637}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001638
Yiwei Zhang5434a782018-12-05 18:06:32 -08001639void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001640 result.append(kDumpTableRowLength, '-');
1641 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001642 result.append(" Layer name\n");
1643 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001644 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001645 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001646 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001647 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001648 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001649 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1650 result.append(kDumpTableRowLength, '-');
1651 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001652}
1653
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001654void Layer::miniDumpLegacy(std::string& result, const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001655 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001656 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001657 return;
1658 }
1659
Yiwei Zhang5434a782018-12-05 18:06:32 -08001660 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001661 if (mName.length() > 77) {
1662 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001663 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001664 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001665 shortened.append(mName, mName.length() - 36);
1666 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001667 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001668 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001669 }
1670
Yiwei Zhang5434a782018-12-05 18:06:32 -08001671 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001672
Alec Mourib416efd2018-09-06 21:01:59 +00001673 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001674 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001675
Chia-I Wu1e043612018-03-01 09:45:09 -08001676 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001677 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001678 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001679 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001680 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001681 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001682 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001683 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1684 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001685 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001686 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001687 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001688 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001689 const auto frameRate = getFrameRateForLayerTree();
Rachel Leece6e0042023-06-27 11:22:54 -07001690 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
1691 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.vote.rate).c_str(),
1692 ftl::enum_string(frameRate.vote.type).c_str(),
1693 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001694 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001695 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001696 }
Dan Stozae22aec72016-08-01 13:20:59 -07001697
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001698 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1699 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1700
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001701 result.append(kDumpTableRowLength, '-');
1702 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001703}
Dan Stozae22aec72016-08-01 13:20:59 -07001704
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001705void Layer::miniDump(std::string& result, const frontend::LayerSnapshot& snapshot,
1706 const DisplayDevice& display) const {
1707 const auto outputLayer = findOutputLayerForDisplay(&display, snapshot.path);
1708 if (!outputLayer) {
1709 return;
1710 }
1711
1712 StringAppendF(&result, " %s\n", snapshot.debugName.c_str());
1713 StringAppendF(&result, " %10zu | ", snapshot.globalZ);
1714 StringAppendF(&result, " %10d | ",
1715 snapshot.layerMetadata.getInt32(gui::METADATA_WINDOW_TYPE, 0));
1716 StringAppendF(&result, "%10s | ", toString(getCompositionType(outputLayer)).c_str());
1717 const auto& outputLayerState = outputLayer->getState();
1718 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1719 const Rect& frame = outputLayerState.displayFrame;
1720 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1721 const FloatRect& crop = outputLayerState.sourceCrop;
1722 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
1723 crop.bottom);
1724 const auto frameRate = snapshot.frameRate;
Ady Abraham77d406d2023-11-22 15:00:23 -08001725 std::string frameRateStr;
1726 if (frameRate.vote.rate.isValid()) {
1727 StringAppendF(&frameRateStr, "%.2f", frameRate.vote.rate.getValue());
1728 }
Rachel Leece6e0042023-06-27 11:22:54 -07001729 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
Ady Abraham77d406d2023-11-22 15:00:23 -08001730 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
Rachel Leece6e0042023-06-27 11:22:54 -07001731 ftl::enum_string(frameRate.vote.type).c_str(),
1732 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abraham77d406d2023-11-22 15:00:23 -08001733 } else if (frameRate.category != FrameRateCategory::Default) {
1734 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
1735 (std::string("Cat::") + ftl::enum_string(frameRate.category)).c_str(),
1736 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001737 } else {
1738 result.append(41, ' ');
1739 }
1740
1741 const auto focused = isLayerFocusedBasedOnPriority(snapshot.frameRateSelectionPriority);
1742 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1743
1744 result.append(kDumpTableRowLength, '-');
1745 result.append("\n");
1746}
1747
Yiwei Zhang5434a782018-12-05 18:06:32 -08001748void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001749 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001750}
1751
Svetoslavd85084b2014-03-20 10:28:31 -07001752void Layer::clearFrameStats() {
1753 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001754}
1755
Jamie Gennis6547ff42013-07-16 20:12:42 -07001756void Layer::logFrameStats() {
1757 mFrameTracker.logAndResetStats(mName);
1758}
1759
Svetoslavd85084b2014-03-20 10:28:31 -07001760void Layer::getFrameStats(FrameStats* outStats) const {
1761 mFrameTracker.getStats(outStats);
1762}
1763
Vishnu Nair76554eb2022-12-09 03:38:36 +00001764void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1765 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
Vishnu Nair3be61902023-04-26 19:47:29 -07001766 StringAppendF(&result, "Layer %s%s pid:%d uid:%d%s\n", getName().c_str(), hasBuffer.c_str(),
1767 mOwnerPid, mOwnerUid, isHandleAlive() ? " handleAlive" : "");
Vishnu Nair0f085c62019-08-30 08:49:12 -07001768}
1769
Brian Anderson5ea5e592016-12-01 16:54:33 -08001770void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001771 const int32_t layerId = getSequence();
1772 mFlinger->mTimeStats->onDestroy(layerId);
1773 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001774}
1775
Vishnu Nair787aa782023-03-17 13:46:46 -07001776size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001777 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001778 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001779 count += 1 + child->getChildrenCount();
1780 }
1781 return count;
1782}
1783
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001784void Layer::setGameModeForTree(GameMode gameMode) {
1785 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001786 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1787 gameMode =
1788 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001789 }
1790 setGameMode(gameMode);
1791 for (const sp<Layer>& child : mCurrentChildren) {
1792 child->setGameModeForTree(gameMode);
1793 }
1794}
1795
Robert Carr1f0a16a2016-10-24 16:27:39 -07001796void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001797 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001798 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001799
Robert Carr1f0a16a2016-10-24 16:27:39 -07001800 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001801 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001802 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001803 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001804}
1805
1806ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001807 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001808 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001809
Robert Carr1323c952019-01-28 18:13:27 -08001810 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001811 const auto removeResult = mCurrentChildren.remove(layer);
1812
1813 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001814 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001815 layer->updateTreeHasFrameRateVote();
1816
1817 return removeResult;
1818}
1819
Robert Carr15eae092018-03-23 13:43:53 -07001820void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001821 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001822 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001823 const float parentShadowRadius =
1824 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001825 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001826 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001827 }
1828}
1829
chaviwf1961f72017-09-18 16:41:07 -07001830bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001831 sp<Layer> newParent;
1832 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001833 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001834 if (newParent == nullptr) {
1835 ALOGE("Unable to promote Layer handle");
1836 return false;
1837 }
1838 if (newParent == this) {
1839 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1840 return false;
1841 }
1842 }
1843
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001844 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001845 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001846 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001847 }
1848
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001849 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001850 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001851 if (!newParent->isRemovedFromCurrentState()) {
1852 addToCurrentState();
1853 } else {
1854 onRemovedFromCurrentState();
1855 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001856 } else {
1857 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001858 }
1859
chaviw06178942017-07-27 10:25:59 -07001860 return true;
1861}
1862
Peiyong Lind3788632018-09-18 16:01:31 -07001863bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001864 static const mat4 identityMatrix = mat4();
1865
Robert Carr6a160312021-05-17 12:08:20 -07001866 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001867 return false;
1868 }
Robert Carr6a160312021-05-17 12:08:20 -07001869 ++mDrawingState.sequence;
1870 mDrawingState.colorTransform = matrix;
1871 mDrawingState.hasColorTransform = matrix != identityMatrix;
1872 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001873 setTransactionFlags(eTransactionNeeded);
1874 return true;
1875}
1876
chaviwf66724d2018-11-28 16:35:21 -08001877mat4 Layer::getColorTransform() const {
1878 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001879 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001880 colorTransform = parent->getColorTransform() * colorTransform;
1881 }
1882 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001883}
1884
1885bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001886 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001887 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001888 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1889 }
1890 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001891}
1892
Chia-I Wu11481472018-05-04 10:43:19 -07001893bool Layer::isLegacyDataSpace() const {
1894 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001895 return !(getDataSpace() &
1896 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1897 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001898}
1899
Robert Carr1f0a16a2016-10-24 16:27:39 -07001900void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001901 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001902}
1903
Robert Carr6a160312021-05-17 12:08:20 -07001904int32_t Layer::getZ(LayerVector::StateSet) const {
1905 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001906}
1907
Robert Carr1c5481e2019-07-01 14:42:27 -07001908bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001909 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001910 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001911 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001912}
1913
David Sodman41fdfc92017-11-06 16:09:56 -08001914__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001915 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001916 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1917 "makeTraversalList received invalid stateSet");
1918 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1919 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001920 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001921
Robert Carr29abff82017-12-04 13:51:20 -08001922 if (state.zOrderRelatives.size() == 0) {
1923 *outSkipRelativeZUsers = true;
1924 return children;
1925 }
1926
chaviwfd462612018-05-31 16:11:27 -07001927 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001928 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001929 sp<Layer> strongRelative = weakRelative.promote();
1930 if (strongRelative != nullptr) {
1931 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001932 }
1933 }
1934
Dan Stoza412903f2017-04-27 13:42:17 -07001935 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001936 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001937 continue;
1938 }
Robert Carrdb66e622017-04-10 16:55:57 -07001939 traverse.add(child);
1940 }
1941
1942 return traverse;
1943}
1944
Robert Carr1f0a16a2016-10-24 16:27:39 -07001945/**
Robert Carrdb66e622017-04-10 16:55:57 -07001946 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001947 */
Dan Stoza412903f2017-04-27 13:42:17 -07001948void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001949 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1950 // produce a new list for traversing, including our relatives, and not including our children
1951 // who are relatives of another surface. In the case that there are no relative Z,
1952 // makeTraversalList returns our children directly to avoid significant overhead.
1953 // However in this case we need to take the responsibility for filtering children which
1954 // are relatives of another surface here.
1955 bool skipRelativeZUsers = false;
1956 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001957
Robert Carr1f0a16a2016-10-24 16:27:39 -07001958 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001959 for (; i < list.size(); i++) {
1960 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001961 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1962 continue;
1963 }
1964
chaviw301b1d82019-11-06 13:15:09 -08001965 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001966 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001967 }
Dan Stoza412903f2017-04-27 13:42:17 -07001968 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001969 }
Robert Carr29abff82017-12-04 13:51:20 -08001970
Dan Stoza412903f2017-04-27 13:42:17 -07001971 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001972 for (; i < list.size(); i++) {
1973 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001974
Robert Carr29abff82017-12-04 13:51:20 -08001975 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1976 continue;
1977 }
Dan Stoza412903f2017-04-27 13:42:17 -07001978 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001979 }
1980}
1981
1982/**
Robert Carrdb66e622017-04-10 16:55:57 -07001983 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001984 */
Dan Stoza412903f2017-04-27 13:42:17 -07001985void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1986 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001987 // See traverseInZOrder for documentation.
1988 bool skipRelativeZUsers = false;
1989 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001990
Robert Carr1f0a16a2016-10-24 16:27:39 -07001991 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001992 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001993 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001994
1995 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1996 continue;
1997 }
1998
chaviw301b1d82019-11-06 13:15:09 -08001999 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002000 break;
2001 }
Dan Stoza412903f2017-04-27 13:42:17 -07002002 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002003 }
Dan Stoza412903f2017-04-27 13:42:17 -07002004 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08002005 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002006 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08002007
2008 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
2009 continue;
2010 }
2011
Dan Stoza412903f2017-04-27 13:42:17 -07002012 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002013 }
2014}
2015
Edgar Arriaga844fa672020-01-16 14:21:42 -08002016void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
2017 visitor(this);
2018 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07002019 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002020 for (const sp<Layer>& child : children) {
2021 child->traverse(state, visitor);
2022 }
2023}
2024
Vishnu Nair787aa782023-03-17 13:46:46 -07002025void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
2026 for (const sp<Layer>& child : mDrawingChildren) {
2027 visitor(child.get());
2028 }
2029}
2030
chaviw4b129c22018-04-09 16:19:43 -07002031LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
2032 const std::vector<Layer*>& layersInTree) {
2033 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2034 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07002035 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2036 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002037 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002038
chaviwfd462612018-05-31 16:11:27 -07002039 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07002040 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2041 sp<Layer> strongRelative = weakRelative.promote();
2042 // Only add relative layers that are also descendents of the top most parent of the tree.
2043 // If a relative layer is not a descendent, then it should be ignored.
2044 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
2045 traverse.add(strongRelative);
2046 }
2047 }
2048
2049 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07002050 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002051 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
2052 // descendent of the top most parent of the tree. If it's not a descendent, then just add
2053 // the child here since it won't be added later as a relative.
2054 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
2055 childState.zOrderRelativeOf.promote().get())) {
2056 continue;
2057 }
2058 traverse.add(child);
2059 }
2060
2061 return traverse;
2062}
2063
2064void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
2065 LayerVector::StateSet stateSet,
2066 const LayerVector::Visitor& visitor) {
2067 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07002068
2069 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07002070 for (; i < list.size(); i++) {
2071 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08002072 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07002073 break;
2074 }
chaviw4b129c22018-04-09 16:19:43 -07002075 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002076 }
chaviw4b129c22018-04-09 16:19:43 -07002077
chaviwa76b2712017-09-20 12:02:26 -07002078 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07002079 for (; i < list.size(); i++) {
2080 const auto& relative = list[i];
2081 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002082 }
2083}
2084
chaviw4b129c22018-04-09 16:19:43 -07002085std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2086 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2087 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2088
2089 std::vector<Layer*> layersInTree = {this};
2090 for (size_t i = 0; i < children.size(); i++) {
2091 const auto& child = children[i];
2092 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2093 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2094 }
2095
2096 return layersInTree;
2097}
2098
2099void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2100 const LayerVector::Visitor& visitor) {
2101 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2102 std::sort(layersInTree.begin(), layersInTree.end());
2103 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2104}
2105
Peiyong Linefefaac2018-08-17 12:27:51 -07002106ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08002107 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002108}
2109
Garfield Tan2c1782c2022-02-16 15:25:05 -08002110bool Layer::isTransformValid() const {
2111 float transformDet = getTransform().det();
2112 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2113}
2114
chaviw13fdc492017-06-27 12:40:18 -07002115half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002116 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002117
chaviw13fdc492017-06-27 12:40:18 -07002118 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2119 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002120}
Robert Carr6452f122017-03-21 10:41:29 -07002121
Vishnu Nair6213bd92020-05-08 17:42:25 -07002122ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002123 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002124 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2125 return fixedTransformHint;
2126 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002127 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002128 if (!p) return fixedTransformHint;
2129 return p->getFixedTransformHint();
2130}
2131
chaviw13fdc492017-06-27 12:40:18 -07002132half4 Layer::getColor() const {
2133 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002134 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002135}
Robert Carr6452f122017-03-21 10:41:29 -07002136
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002137int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002138 if (getDrawingState().backgroundBlurRadius == 0) {
2139 return 0;
2140 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002141
Vishnu Nair29810f72022-07-01 16:38:41 +00002142 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002143 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2144 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002145}
2146
Galia Peychevae0acf382021-04-12 21:22:34 +02002147const std::vector<BlurRegion> Layer::getBlurRegions() const {
2148 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002149 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002150 for (auto& region : regionsCopy) {
2151 region.alpha = region.alpha * layerAlpha;
2152 }
2153 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002154}
2155
Vishnu Naire14c6b32022-08-06 04:20:15 +00002156RoundedCornerState Layer::getRoundedCornerState() const {
Leon Scroggins IIIc1dbfcb2022-03-21 16:48:10 -04002157 // Today's DPUs cannot do rounded corners. If RenderEngine cannot render
2158 // protected content, remove rounded corners from protected content so it
2159 // can be rendered by the DPU.
2160 if (isProtected() && !mFlinger->getRenderEngine().supportsProtectedContent()) {
2161 return {};
2162 }
2163
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002164 // Get parent settings
2165 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002166 const auto& parent = mDrawingParent.promote();
2167 if (parent != nullptr) {
2168 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002169 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002170 ui::Transform t = getActiveTransform(getDrawingState());
2171 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002172 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002173 parentSettings.radius.x *= t.getScaleX();
2174 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002175 }
2176 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002177
2178 // Get layer settings
2179 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002180 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002181 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002182 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002183
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002184 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002185 // If the parent and the layer have rounded corner settings, use the parent settings if the
2186 // parent crop is entirely inside the layer crop.
2187 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2188 if (parentSettings.cropRect.left > layerCropRect.left &&
2189 parentSettings.cropRect.top > layerCropRect.top &&
2190 parentSettings.cropRect.right < layerCropRect.right &&
2191 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2192 return parentSettings;
2193 } else {
2194 return layerSettings;
2195 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002196 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002197 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002198 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002199 return parentSettings;
2200 }
2201 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002202}
2203
Robert Carr88b85e12022-03-21 15:47:35 -07002204bool Layer::findInHierarchy(const sp<Layer>& l) {
2205 if (l == this) {
2206 return true;
2207 }
2208 for (auto& child : mDrawingChildren) {
2209 if (child->findInHierarchy(l)) {
2210 return true;
2211 }
2212 }
2213 return false;
2214}
2215
Robert Carr1f0a16a2016-10-24 16:27:39 -07002216void Layer::commitChildList() {
2217 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2218 const auto& child = mCurrentChildren[i];
2219 child->commitChildList();
2220 }
2221 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002222 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002223 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2224 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2225 if (zOrderRelativeOf == nullptr) return;
2226 if (findInHierarchy(zOrderRelativeOf)) {
2227 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2228 zOrderRelativeOf->mName.c_str());
2229 ALOGE("Severing rel Z loop, potentially dangerous");
2230 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002231 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002232 }
2233 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002234}
2235
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002236
chaviw3277faf2021-05-19 16:45:23 -05002237void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002238 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002239 mDrawingState.touchableRegionCrop =
2240 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002241 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002242 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002243 setTransactionFlags(eTransactionNeeded);
2244}
2245
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002246perfetto::protos::LayerProto* Layer::writeToProto(perfetto::protos::LayersProto& layersProto,
2247 uint32_t traceFlags) {
2248 perfetto::protos::LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002249 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002250 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2251
Vishnu Nair00b90132021-11-05 14:03:40 -07002252 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nair2f65e972023-04-04 16:36:28 +00002253 ui::LayerStack layerStack =
2254 (mSnapshot) ? mSnapshot->outputFilter.layerStack : ui::INVALID_LAYER_STACK;
2255 writeCompositionStateToProto(layerProto, layerStack);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002256 }
2257
chaviw08f3cb22020-01-13 13:17:21 -08002258 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002259 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002260 }
chaviw6d89e2d2020-01-14 14:42:01 -08002261
2262 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002263}
2264
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002265void Layer::writeCompositionStateToProto(perfetto::protos::LayerProto* layerProto,
2266 ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002267 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002268 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +00002269
2270 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002271 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002272 const auto compositionType = getCompositionType(*display);
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002273 layerProto->set_hwc_composition_type(
2274 static_cast<perfetto::protos::HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +00002275 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +00002276 [&]() { return layerProto->mutable_visible_region(); });
2277 }
2278}
2279
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002280void Layer::writeToProtoDrawingState(perfetto::protos::LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002281 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002282 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002283 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002284 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002285 [&]() { return layerInfo->mutable_active_buffer(); });
2286 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2287 layerInfo->mutable_buffer_transform());
2288 }
2289 layerInfo->set_invalidate(contentDirty);
2290 layerInfo->set_is_protected(isProtected());
2291 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2292 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002293 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002294 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002295 layerInfo->set_corner_radius(
2296 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002297 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2298 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2299 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2300 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2301 [&]() { return layerInfo->mutable_position(); });
2302 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002303 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2304 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002305
Vishnu Nair00b90132021-11-05 14:03:40 -07002306 if (hasColorTransform()) {
2307 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002308 }
2309
Vishnu Nair60db8c02020-04-02 11:55:16 -07002310 LayerProtoHelper::writeToProto(mSourceBounds,
2311 [&]() { return layerInfo->mutable_source_bounds(); });
2312 LayerProtoHelper::writeToProto(mScreenBounds,
2313 [&]() { return layerInfo->mutable_screen_bounds(); });
2314 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2315 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2316 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002317}
2318
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002319void Layer::writeToProtoCommonState(perfetto::protos::LayerProto* layerInfo,
2320 LayerVector::StateSet stateSet, uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002321 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2322 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002323 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002324
chaviw766c9c52021-02-10 17:36:47 -08002325 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002326
Vishnu Nair00b90132021-11-05 14:03:40 -07002327 layerInfo->set_id(sequence);
2328 layerInfo->set_name(getName().c_str());
2329 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002330
Vishnu Nair00b90132021-11-05 14:03:40 -07002331 for (const auto& child : children) {
2332 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002333 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002334
Vishnu Nair00b90132021-11-05 14:03:40 -07002335 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2336 sp<Layer> strongRelative = weakRelative.promote();
2337 if (strongRelative != nullptr) {
2338 layerInfo->add_relatives(strongRelative->sequence);
2339 }
2340 }
2341
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002342 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002343 [&]() { return layerInfo->mutable_transparent_region(); });
2344
2345 layerInfo->set_layer_stack(getLayerStack().id);
2346 layerInfo->set_z(state.z);
2347
2348 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2349 return layerInfo->mutable_requested_position();
2350 });
2351
Vishnu Nair00b90132021-11-05 14:03:40 -07002352 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2353
2354 layerInfo->set_is_opaque(isOpaque(state));
2355
2356 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2357 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2358 LayerProtoHelper::writeToProto(state.color,
2359 [&]() { return layerInfo->mutable_requested_color(); });
2360 layerInfo->set_flags(state.flags);
2361
2362 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2363 layerInfo->mutable_requested_transform());
2364
2365 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2366 if (parent != nullptr) {
2367 layerInfo->set_parent(parent->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002368 }
2369
2370 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2371 if (zOrderRelativeOf != nullptr) {
2372 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002373 }
2374
2375 layerInfo->set_is_relative_of(state.isRelativeOf);
2376
2377 layerInfo->set_owner_uid(mOwnerUid);
2378
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002379 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002380 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002381 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002382 info = fillInputInfo(
2383 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002384 } else {
2385 info = state.inputInfo;
2386 }
2387
2388 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002389 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002390 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002391
Vishnu Nair00b90132021-11-05 14:03:40 -07002392 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002393 auto protoMap = layerInfo->mutable_metadata();
2394 for (const auto& entry : state.metadata.mMap) {
2395 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2396 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002397 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002398
2399 LayerProtoHelper::writeToProto(state.destinationFrame,
2400 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002401}
2402
Robert Carr2e102c92018-10-23 12:11:15 -07002403bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002404 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002405}
2406
Prabir Pradhan33da9462022-06-14 14:55:57 +00002407// Applies the given transform to the region, while protecting against overflows caused by any
2408// offsets. If applying the offset in the transform to any of the Rects in the region would result
2409// in an overflow, they are not added to the output Region.
2410static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2411 const std::string& debugWindowName) {
2412 // Round the translation using the same rounding strategy used by ui::Transform.
2413 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2414 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2415
2416 ui::Transform transformWithoutOffset = t;
2417 transformWithoutOffset.set(0.f, 0.f);
2418
2419 const Region transformed = transformWithoutOffset.transform(r);
2420
2421 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2422 Region ret;
2423 for (const auto& rect : transformed) {
2424 Rect newRect;
2425 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2426 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2427 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2428 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2429 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2430 debugWindowName.c_str());
2431 continue;
2432 }
2433 ret.orSelf(newRect);
2434 }
2435 return ret;
2436}
2437
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002438void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002439 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2440 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002441 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002442 }
2443
Chavi Weingarten7f019192023-08-08 20:39:01 +00002444 info.frame = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
chaviw1ff3d1e2020-07-01 15:53:47 -07002445
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002446 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002447 inputToLayer.set(inputBounds.left, inputBounds.top);
2448 const ui::Transform layerToScreen = getInputTransform();
2449 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002450
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002451 // InputDispatcher expects a display-to-input transform.
2452 info.transform = inputToDisplay.inverse();
2453
2454 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002455 info.touchableRegion =
2456 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002457}
2458
chaviw3277faf2021-05-19 16:45:23 -05002459void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002460 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002461 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002462 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002463 }
2464 if (p != nullptr) {
2465 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2466 }
2467}
2468
Vishnu Naira066d902021-09-13 18:40:17 -07002469gui::DropInputMode Layer::getDropInputMode() const {
2470 gui::DropInputMode mode = mDrawingState.dropInputMode;
2471 if (mode == gui::DropInputMode::ALL) {
2472 return mode;
2473 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002474 sp<Layer> parent = mDrawingParent.promote();
2475 if (parent) {
2476 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002477 if (parentMode != gui::DropInputMode::NONE) {
2478 return parentMode;
2479 }
2480 }
2481 return mode;
2482}
2483
2484void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002485 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002486 return;
2487 }
2488
2489 // Check if we need to drop input unconditionally
2490 gui::DropInputMode dropInputMode = getDropInputMode();
2491 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002492 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002493 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2494 return;
2495 }
2496
2497 // Check if we need to check if the window is obscured by parent
2498 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2499 return;
2500 }
2501
2502 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002503 sp<Layer> parent = mDrawingParent.promote();
2504 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002505 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002506 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2507 static_cast<float>(getAlpha()));
2508 }
2509
2510 // Check if the parent has cropped the buffer
2511 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2512 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002513 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002514 return;
2515 }
2516
2517 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2518 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2519 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2520 // match then the layer has not been cropped by its parents.
2521 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2522 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2523
2524 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002525 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002526 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2527 getDebugName());
2528 } else {
2529 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2530 // input if the window is obscured. This check should be done in surfaceflinger but the
2531 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2532 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002533 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002534 }
2535}
2536
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002537WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002538 if (!hasInputInfo()) {
2539 mDrawingState.inputInfo.name = getName();
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002540 mDrawingState.inputInfo.ownerUid = gui::Uid{mOwnerUid};
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00002541 mDrawingState.inputInfo.ownerPid = gui::Pid{mOwnerPid};
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002542 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002543 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002544 }
2545
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002546 const ui::Transform& displayTransform =
2547 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2548
chaviw3277faf2021-05-19 16:45:23 -05002549 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002550 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002551 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002552
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002553 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002554
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002555 if (displayArgs.transform == nullptr) {
2556 // Do not let the window receive touches if it is not associated with a valid display
2557 // transform. We still allow the window to receive keys and prevent ANRs.
2558 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2559 }
2560
Patrick Williams1caf3b72023-03-31 10:59:10 -05002561 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !isVisibleForInput());
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002562
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002563 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002564 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002565 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002566
Vishnu Nair16a938f2021-09-24 07:14:54 -07002567 // If the window will be blacked out on a display because the display does not have the secure
2568 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002569 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002570 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002571 }
2572
Vishnu Nairfed7c122023-03-18 01:54:43 +00002573 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002574 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002575 Rect inputBoundsInDisplaySpace;
2576 if (!cropLayer) {
2577 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2578 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2579 } else {
2580 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2581 inputBoundsInDisplaySpace =
2582 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2583 }
2584 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002585 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002586 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2587 Rect inputBoundsInDisplaySpace =
2588 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2589 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002590 }
2591
Winson Chunga30f7c92021-06-29 15:42:56 -07002592 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2593 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002594 if (isTrustedOverlay()) {
2595 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2596 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002597
chaviwaf87b3e2019-10-01 16:59:28 -07002598 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2599 // touches from going outside the cloned area.
2600 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002601 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002602 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2603 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002604 info.touchableRegion = info.touchableRegion.intersect(rect);
2605 }
2606 }
2607
Vishnu Nair494a2e42023-11-10 17:21:19 -08002608 Rect bufferSize = getBufferSize(getDrawingState());
2609 info.contentSize = Size(bufferSize.width(), bufferSize.height());
2610
Robert Carr720e5062018-07-30 17:45:14 -07002611 return info;
2612}
2613
Vishnu Nairfed7c122023-03-18 01:54:43 +00002614Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2615 const ui::Transform& screenToDisplay) {
2616 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2617 // frame and transform used for the layer, which determines the bounds and the coordinate space
2618 // within which the layer will receive input.
2619
2620 // Coordinate space definitions:
2621 // - display: The display device's coordinate space. Correlates to pixels on the display.
2622 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2623 // - layer: The coordinate space of this layer.
2624 // - input: The coordinate space in which this layer will receive input events. This could be
2625 // different than layer space if a surfaceInset is used, which changes the origin
2626 // of the input space.
2627
2628 // Crop the input bounds to ensure it is within the parent's bounds.
2629 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2630 const ui::Transform layerToScreen = getInputTransform();
2631 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2632 return Rect{layerToDisplay.transform(croppedInputBounds)};
2633}
2634
chaviwaf87b3e2019-10-01 16:59:28 -07002635sp<Layer> Layer::getClonedRoot() {
2636 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002637 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002638 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002639 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002640 return nullptr;
2641 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002642 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002643}
2644
Robert Carredd13602020-04-13 17:24:34 -07002645bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002646 return mDrawingState.inputInfo.token != nullptr ||
2647 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002648}
2649
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002650compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002651 const DisplayDevice* display) const {
2652 if (!display) return nullptr;
Lloyd Pique30db6402023-06-26 18:56:51 +00002653 if (!mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00002654 return display->getCompositionDisplay()->getOutputLayerForLayer(
2655 getCompositionEngineLayerFE());
2656 }
2657 sp<LayerFE> layerFE;
2658 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2659 for (auto& [p, layer] : mLayerFEs) {
2660 if (p == path) {
2661 layerFE = layer;
2662 }
2663 }
2664
2665 if (!layerFE) return nullptr;
2666 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002667}
2668
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002669compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
2670 const DisplayDevice* display, const frontend::LayerHierarchy::TraversalPath& path) const {
2671 if (!display) return nullptr;
Vishnu Naire9ee0002023-07-01 03:14:51 +00002672 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2673 return display->getCompositionDisplay()->getOutputLayerForLayer(
2674 getCompositionEngineLayerFE());
2675 }
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002676 sp<LayerFE> layerFE;
2677 for (auto& [p, layer] : mLayerFEs) {
2678 if (p == path) {
2679 layerFE = layer;
2680 }
2681 }
2682
2683 if (!layerFE) return nullptr;
2684 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
2685}
2686
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002687Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2688 const auto outputLayer = findOutputLayerForDisplay(display);
2689 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002690}
2691
Vishnu Nairde177252023-04-21 12:44:10 -07002692void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom, uint32_t mirrorRootId) {
Vishnu Nair83d91622023-12-08 23:00:22 +00002693 if (mFlinger->mLayerLifecycleManagerEnabled) return;
Vishnu Nairde177252023-04-21 12:44:10 -07002694 mSnapshot->path.id = clonedFrom->getSequence();
Vishnu Nair6f878312023-09-08 11:05:01 -07002695 mSnapshot->path.mirrorRootIds.emplace_back(mirrorRootId);
Vishnu Nairde177252023-04-21 12:44:10 -07002696
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002697 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002698 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002699 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2700 mPotentialCursor = clonedFrom->mPotentialCursor;
2701 mProtectedByApp = clonedFrom->mProtectedByApp;
2702 updateCloneBufferInfo();
2703}
2704
2705void Layer::updateCloneBufferInfo() {
2706 if (!isClone() || !isClonedFromAlive()) {
2707 return;
2708 }
2709
2710 sp<Layer> clonedFrom = getClonedFrom();
2711 mBufferInfo = clonedFrom->mBufferInfo;
2712 mSidebandStream = clonedFrom->mSidebandStream;
2713 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2714 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2715 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2716
2717 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2718 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2719 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2720 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2721 // the cloned drawingState again.
2722 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2723 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2724 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2725 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2726
2727 cloneDrawingState(clonedFrom.get());
2728
2729 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2730 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2731 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2732 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002733}
chaviw74b03172019-08-19 11:09:03 -07002734
Vishnu Nair3be61902023-04-26 19:47:29 -07002735bool Layer::updateMirrorInfo(const std::deque<Layer*>& cloneRootsPendingUpdates) {
chaviw74b03172019-08-19 11:09:03 -07002736 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2737 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2738 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2739 // that case, we want to delete the reference to the clone since we want it to get
2740 // destroyed. The root, this layer, will still be around since the client can continue
2741 // to hold a reference, but no cloned layers will be displayed.
2742 mClonedChild = nullptr;
Vishnu Nair3be61902023-04-26 19:47:29 -07002743 return true;
chaviw74b03172019-08-19 11:09:03 -07002744 }
2745
2746 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2747 // If the real layer exists and is in current state, add the clone as a child of the root.
2748 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2749 // copied to drawingState for the root layer. So the clonedChild is always removed from
2750 // drawingState and then needs to be added back each traversal.
2751 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2752 addChildToDrawing(mClonedChild);
2753 }
2754
2755 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002756 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002757 mClonedChild->updateClonedRelatives(clonedLayersMap);
Vishnu Nair3be61902023-04-26 19:47:29 -07002758
2759 for (Layer* root : cloneRootsPendingUpdates) {
2760 if (clonedLayersMap.find(sp<Layer>::fromExisting(root)) != clonedLayersMap.end()) {
2761 return false;
2762 }
2763 }
2764 return true;
chaviw74b03172019-08-19 11:09:03 -07002765}
2766
2767void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2768 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2769 // to the clone. If the real layer is no longer alive, continue traversing the children
2770 // since we may be able to pull out other children that are still alive.
2771 if (isClonedFromAlive()) {
2772 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002773 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002774 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002775 }
2776
2777 // The clone layer may have children in drawingState since they may have been created and
2778 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2779 // that already exist, since we can just re-use them.
2780 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2781 // not updated in the regular traversal. They are skipped since the root will lose the
2782 // reference to them when it copies its currentChildren to drawing.
2783 for (sp<Layer>& child : mDrawingChildren) {
2784 child->updateClonedDrawingState(clonedLayersMap);
2785 }
2786}
2787
2788void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2789 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2790 mDrawingChildren.clear();
2791
2792 if (!isClonedFromAlive()) {
2793 return;
2794 }
2795
2796 sp<Layer> clonedFrom = getClonedFrom();
2797 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2798 if (child == mirrorRoot) {
2799 // This is to avoid cyclical mirroring.
2800 continue;
2801 }
2802 sp<Layer> clonedChild = clonedLayersMap[child];
2803 if (clonedChild == nullptr) {
Vishnu Nairde177252023-04-21 12:44:10 -07002804 clonedChild = child->createClone(mirrorRoot->getSequence());
chaviw74b03172019-08-19 11:09:03 -07002805 clonedLayersMap[child] = clonedChild;
2806 }
2807 addChildToDrawing(clonedChild);
2808 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2809 }
2810}
2811
chaviwaf87b3e2019-10-01 16:59:28 -07002812void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2813 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2814 if (cropLayer != nullptr) {
2815 if (clonedLayersMap.count(cropLayer) == 0) {
2816 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2817 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002818 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002819 } else {
2820 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2821 mDrawingState.touchableRegionCrop = clonedCropLayer;
2822 }
2823 }
2824 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2825 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002826 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002827}
2828
2829void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002830 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002831 mDrawingState.zOrderRelatives.clear();
2832
2833 if (!isClonedFromAlive()) {
2834 return;
2835 }
2836
chaviwaf87b3e2019-10-01 16:59:28 -07002837 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002838 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002839 const sp<Layer>& relative = relativeWeak.promote();
2840 if (clonedLayersMap.count(relative) > 0) {
2841 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002842 mDrawingState.zOrderRelatives.add(clonedRelative);
2843 }
2844 }
2845
2846 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2847 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2848 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2849 // still traverse the children, but the layer with the missing relativeOf will not be shown
2850 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002851 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2852 if (clonedLayersMap.count(relativeOf) > 0) {
2853 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002854 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2855 }
2856
chaviwaf87b3e2019-10-01 16:59:28 -07002857 updateClonedInputInfo(clonedLayersMap);
2858
chaviw74b03172019-08-19 11:09:03 -07002859 for (sp<Layer>& child : mDrawingChildren) {
2860 child->updateClonedRelatives(clonedLayersMap);
2861 }
2862}
2863
2864void Layer::addChildToDrawing(const sp<Layer>& layer) {
2865 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002866 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002867}
2868
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002869bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002870 const State& s(mDrawingState);
2871 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2872 return true;
2873 }
2874
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002875 sp<Layer> parent = mDrawingParent.promote();
2876 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002877}
2878
Robert Carr6a0382d2021-07-01 15:57:17 -07002879void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2880 mClonedChild = clonedChild;
2881 mHadClonedChild = true;
Vishnu Nair3be61902023-04-26 19:47:29 -07002882 mFlinger->mLayerMirrorRoots.push_back(this);
Robert Carr6a0382d2021-07-01 15:57:17 -07002883}
2884
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002885bool Layer::setDropInputMode(gui::DropInputMode mode) {
2886 if (mDrawingState.dropInputMode == mode) {
2887 return false;
2888 }
2889 mDrawingState.dropInputMode = mode;
2890 return true;
2891}
2892
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002893void Layer::cloneDrawingState(const Layer* from) {
2894 mDrawingState = from->mDrawingState;
2895 // Skip callback info since they are not applicable for cloned layers.
2896 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002897 // TODO (b/238781169) currently broken for mirror layers because we do not
2898 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002899 mDrawingState.callbackHandles = {};
2900}
2901
Patrick Williamsbb25f802022-08-30 23:02:34 +00002902void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2903 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002904 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002905 if (!listener) {
2906 return;
2907 }
2908 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002909 uint32_t currentMaxAcquiredBufferCount =
2910 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002911 listener->onReleaseBuffer({buffer->getId(), framenumber},
2912 releaseFence ? releaseFence : Fence::NO_FENCE,
2913 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002914}
2915
Melody Hsu793f8362024-01-08 20:00:35 +00002916sp<CallbackHandle> Layer::findCallbackHandle() {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002917 // If we are displayed on multiple displays in a single composition cycle then we would
2918 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2919 // For example we can only use it if all the displays are client comp, and we need
2920 // to merge all the client comp fences. We could do this, but for now we just
2921 // disable the optimization when a layer is composed on multiple displays.
2922 if (mClearClientCompositionFenceOnLayerDisplayed) {
2923 mLastClientCompositionFence = nullptr;
2924 } else {
2925 mClearClientCompositionFenceOnLayerDisplayed = true;
2926 }
2927
2928 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2929 // buffer that was presented on this layer. The first transaction that came in this frame that
2930 // replaced the previous buffer on this layer needs this release fence, because the fence will
2931 // let the client know when that previous buffer is removed from the screen.
2932 //
2933 // Every other transaction on this layer does not need a release fence because no other
2934 // Transactions that were set on this layer this frame are going to have their preceding buffer
2935 // removed from the display this frame.
2936 //
2937 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2938 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2939 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2940 // the previous buffer will be released this frame. The third transaction also contains a
2941 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2942 // transaction will now no longer be presented so it is released immediately and the third
2943 // transaction doesn't need a previous release fence.
2944 sp<CallbackHandle> ch;
2945 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002946 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002947 ch = handle;
2948 break;
2949 }
2950 }
Melody Hsu793f8362024-01-08 20:00:35 +00002951 return ch;
2952}
2953
2954void Layer::prepareReleaseCallbacks(ftl::Future<FenceResult> futureFenceResult,
2955 ui::LayerStack layerStack) {
2956 sp<CallbackHandle> ch = findCallbackHandle();
2957
2958 if (ch != nullptr) {
2959 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2960 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2961 ch->name = mName;
2962 } else {
2963 // If we didn't get a release callback yet, e.g. some scenarios when capturing
2964 // screenshots asynchronously, then make sure we don't drop the fence.
2965 mAdditionalPreviousReleaseFences.emplace_back(std::move(futureFenceResult));
2966 std::vector<ftl::Future<FenceResult>> mergedFences;
2967 sp<Fence> prevFence = nullptr;
2968 // For a layer that's frequently screenshotted, try to merge fences to make sure we
2969 // don't grow unbounded.
2970 for (auto& futureReleaseFence : mAdditionalPreviousReleaseFences) {
2971 auto result = futureReleaseFence.wait_for(0s);
2972 if (result != std::future_status::ready) {
2973 mergedFences.emplace_back(std::move(futureReleaseFence));
2974 continue;
2975 }
2976 mergeFence(getDebugName(), futureReleaseFence.get().value_or(Fence::NO_FENCE),
2977 prevFence);
2978 }
2979 if (prevFence != nullptr) {
2980 mergedFences.emplace_back(ftl::yield(FenceResult(std::move(prevFence))));
2981 }
2982 mAdditionalPreviousReleaseFences.swap(mergedFences);
2983 }
2984
2985 if (mBufferInfo.mBuffer) {
2986 mPreviouslyPresentedLayerStacks.push_back(layerStack);
2987 }
2988
2989 if (mDrawingState.frameNumber > 0) {
2990 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
2991 }
2992}
2993
2994void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
2995 ui::LayerStack layerStack,
2996 std::function<FenceResult(FenceResult)>&& continuation) {
2997 sp<CallbackHandle> ch = findCallbackHandle();
Alec Mouri9892aac2023-12-11 21:16:59 +00002998
2999 if (!FlagManager::getInstance().screenshot_fence_preservation() && continuation) {
3000 futureFenceResult = ftl::Future(futureFenceResult).then(std::move(continuation)).share();
3001 }
3002
Patrick Williamsbb25f802022-08-30 23:02:34 +00003003 if (ch != nullptr) {
3004 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
Melody Hsu793f8362024-01-08 20:00:35 +00003005 ch->previousSharedReleaseFences.emplace_back(std::move(futureFenceResult));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003006 ch->name = mName;
Alec Mouri9892aac2023-12-11 21:16:59 +00003007 } else if (FlagManager::getInstance().screenshot_fence_preservation()) {
3008 // If we didn't get a release callback yet, e.g. some scenarios when capturing screenshots
3009 // asynchronously, then make sure we don't drop the fence.
Melody Hsu793f8362024-01-08 20:00:35 +00003010 mPreviousReleaseFenceAndContinuations.emplace_back(std::move(futureFenceResult),
3011 std::move(continuation));
Alec Mouri9892aac2023-12-11 21:16:59 +00003012 std::vector<FenceAndContinuation> mergedFences;
3013 sp<Fence> prevFence = nullptr;
3014 // For a layer that's frequently screenshotted, try to merge fences to make sure we don't
3015 // grow unbounded.
Melody Hsu793f8362024-01-08 20:00:35 +00003016 for (const auto& futureAndContinuation : mPreviousReleaseFenceAndContinuations) {
3017 auto result = futureAndContinuation.future.wait_for(0s);
Alec Mouri9892aac2023-12-11 21:16:59 +00003018 if (result != std::future_status::ready) {
Melody Hsu793f8362024-01-08 20:00:35 +00003019 mergedFences.emplace_back(futureAndContinuation);
Alec Mouri9892aac2023-12-11 21:16:59 +00003020 continue;
3021 }
3022
Melody Hsu793f8362024-01-08 20:00:35 +00003023 mergeFence(getDebugName(),
3024 futureAndContinuation.chain().get().value_or(Fence::NO_FENCE), prevFence);
Alec Mouri9892aac2023-12-11 21:16:59 +00003025 }
3026 if (prevFence != nullptr) {
3027 mergedFences.emplace_back(ftl::yield(FenceResult(std::move(prevFence))).share());
3028 }
3029
Melody Hsu793f8362024-01-08 20:00:35 +00003030 mPreviousReleaseFenceAndContinuations.swap(mergedFences);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003031 }
Alec Mouri9892aac2023-12-11 21:16:59 +00003032
Vishnu Nair316b7f42023-10-13 23:44:46 +00003033 if (mBufferInfo.mBuffer) {
3034 mPreviouslyPresentedLayerStacks.push_back(layerStack);
3035 }
Alec Mouri21d94322023-10-17 19:51:39 +00003036
3037 if (mDrawingState.frameNumber > 0) {
3038 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
3039 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003040}
3041
3042void Layer::onSurfaceFrameCreated(
3043 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
3044 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
3045 // Too many SurfaceFrames pending classification. The front of the deque is probably not
3046 // tracked by FrameTimeline and will never be presented. This will only result in a memory
3047 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01003048 if (hasBufferOrSidebandStreamInDrawing()) {
3049 // Only log for layers with a buffer, since we expect the jank data to be drained for
3050 // these, while there may be no jank listeners for bufferless layers.
3051 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
3052 mName.c_str());
3053 std::string miniDump = mPendingJankClassifications.front()->miniDump();
3054 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
3055 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003056 mPendingJankClassifications.pop_front();
3057 }
3058 mPendingJankClassifications.emplace_back(surfaceFrame);
3059}
3060
3061void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
3062 for (const auto& handle : mDrawingState.callbackHandles) {
Lloyd Pique30db6402023-06-26 18:56:51 +00003063 if (mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -07003064 handle->transformHint = mTransformHint;
3065 } else {
3066 handle->transformHint = mSkipReportingTransformHint
3067 ? std::nullopt
3068 : std::make_optional<uint32_t>(mTransformHintLegacy);
3069 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003070 handle->dequeueReadyTime = dequeueReadyTime;
3071 handle->currentMaxAcquiredBufferCount =
3072 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
3073 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
3074 handle->previousReleaseCallbackId.framenumber);
3075 }
3076
3077 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003078 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003079 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
3080 break;
3081 }
3082 }
3083
3084 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01003085 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003086 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
3087 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003088 mDrawingState.callbackHandles = {};
3089}
3090
3091bool Layer::willPresentCurrentTransaction() const {
3092 // Returns true if the most recent Transaction applied to CurrentState will be presented.
3093 return (getSidebandStreamChanged() || getAutoRefresh() ||
3094 (mDrawingState.modified &&
3095 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
3096}
3097
3098bool Layer::setTransform(uint32_t transform) {
3099 if (mDrawingState.bufferTransform == transform) return false;
3100 mDrawingState.bufferTransform = transform;
3101 mDrawingState.modified = true;
3102 setTransactionFlags(eTransactionNeeded);
3103 return true;
3104}
3105
3106bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
3107 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
3108 mDrawingState.sequence++;
3109 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
3110 mDrawingState.modified = true;
3111 setTransactionFlags(eTransactionNeeded);
3112 return true;
3113}
3114
3115bool Layer::setBufferCrop(const Rect& bufferCrop) {
3116 if (mDrawingState.bufferCrop == bufferCrop) return false;
3117
3118 mDrawingState.sequence++;
3119 mDrawingState.bufferCrop = bufferCrop;
3120
3121 mDrawingState.modified = true;
3122 setTransactionFlags(eTransactionNeeded);
3123 return true;
3124}
3125
3126bool Layer::setDestinationFrame(const Rect& destinationFrame) {
3127 if (mDrawingState.destinationFrame == destinationFrame) return false;
3128
3129 mDrawingState.sequence++;
3130 mDrawingState.destinationFrame = destinationFrame;
3131
3132 mDrawingState.modified = true;
3133 setTransactionFlags(eTransactionNeeded);
3134 return true;
3135}
3136
3137// Translate destination frame into scale and position. If a destination frame is not set, use the
3138// provided scale and position
3139bool Layer::updateGeometry() {
3140 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
3141 mDrawingState.destinationFrame.isEmpty()) {
3142 // If destination frame is not set, use the requested transform set via
3143 // Layer::setPosition and Layer::setMatrix.
3144 return assignTransform(&mDrawingState.transform, mRequestedTransform);
3145 }
3146
3147 Rect destRect = mDrawingState.destinationFrame;
3148 int32_t destW = destRect.width();
3149 int32_t destH = destRect.height();
3150 if (destRect.left < 0) {
3151 destRect.left = 0;
3152 destRect.right = destW;
3153 }
3154 if (destRect.top < 0) {
3155 destRect.top = 0;
3156 destRect.bottom = destH;
3157 }
3158
3159 if (!mDrawingState.buffer) {
3160 ui::Transform t;
3161 t.set(destRect.left, destRect.top);
3162 return assignTransform(&mDrawingState.transform, t);
3163 }
3164
3165 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3166 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3167 // Undo any transformations on the buffer.
3168 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3169 std::swap(bufferWidth, bufferHeight);
3170 }
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003171 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003172 if (mDrawingState.transformToDisplayInverse) {
3173 if (invTransform & ui::Transform::ROT_90) {
3174 std::swap(bufferWidth, bufferHeight);
3175 }
3176 }
3177
3178 float sx = destW / static_cast<float>(bufferWidth);
3179 float sy = destH / static_cast<float>(bufferHeight);
3180 ui::Transform t;
3181 t.set(sx, 0, 0, sy);
3182 t.set(destRect.left, destRect.top);
3183 return assignTransform(&mDrawingState.transform, t);
3184}
3185
3186bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3187 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3188 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3189 return false;
3190 }
3191
3192 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3193
3194 mDrawingState.sequence++;
3195 mDrawingState.modified = true;
3196 setTransactionFlags(eTransactionNeeded);
3197
3198 return true;
3199}
3200
3201bool Layer::setPosition(float x, float y) {
3202 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3203 return false;
3204 }
3205
3206 mRequestedTransform.set(x, y);
3207
3208 mDrawingState.sequence++;
3209 mDrawingState.modified = true;
3210 setTransactionFlags(eTransactionNeeded);
3211
3212 return true;
3213}
3214
Dorin Drimuse5374e52023-08-02 17:52:43 +00003215void Layer::releasePreviousBuffer() {
3216 mReleasePreviousBuffer = true;
3217 if (!mBufferInfo.mBuffer ||
3218 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3219 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3220 // If mDrawingState has a buffer, and we are about to update again
3221 // before swapping to drawing state, then the first buffer will be
3222 // dropped and we should decrement the pending buffer count and
3223 // call any release buffer callbacks if set.
3224 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3225 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3226 mDrawingState.acquireFence);
3227 decrementPendingBufferCount();
3228 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3229 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3230 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX, systemTime());
3231 mDrawingState.bufferSurfaceFrameTX.reset();
3232 }
3233 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3234 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3235 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3236 mLastClientCompositionFence);
3237 mLastClientCompositionFence = nullptr;
3238 }
3239}
3240
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003241void Layer::resetDrawingStateBufferInfo() {
3242 mDrawingState.producerId = 0;
3243 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +00003244 mDrawingState.previousFrameNumber = 0;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003245 mDrawingState.releaseBufferListener = nullptr;
3246 mDrawingState.buffer = nullptr;
3247 mDrawingState.acquireFence = sp<Fence>::make(-1);
3248 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3249 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3250 mDrawingState.releaseBufferEndpoint = nullptr;
3251}
3252
Patrick Williamsbb25f802022-08-30 23:02:34 +00003253bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3254 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3255 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003256 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003257 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003258
3259 const bool frameNumberChanged =
3260 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3261 const uint64_t frameNumber =
3262 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003263 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003264
3265 if (mDrawingState.buffer) {
Dorin Drimuse5374e52023-08-02 17:52:43 +00003266 releasePreviousBuffer();
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003267 } else if (buffer) {
Vishnu Nairc09c0232023-03-02 03:22:35 +00003268 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3269 // we don't want to incorrectly classify a frame if we miss the desired present time.
3270 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003271 }
3272
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003273 mDrawingState.desiredPresentTime = desiredPresentTime;
3274 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3275 mDrawingState.latchedVsyncId = info.vsyncId;
Ady Abraham55269162023-05-09 11:26:06 -07003276 mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003277 mDrawingState.modified = true;
3278 if (!buffer) {
3279 resetDrawingStateBufferInfo();
3280 setTransactionFlags(eTransactionNeeded);
3281 mDrawingState.bufferSurfaceFrameTX = nullptr;
3282 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3283 return true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003284 } else {
3285 // release sideband stream if it exists and a non null buffer is being set
3286 if (mDrawingState.sidebandStream != nullptr) {
Dorin Drimus66ed1c42023-09-27 13:10:16 +00003287 setSidebandStream(nullptr, info, postTime);
Dorin Drimuse5374e52023-08-02 17:52:43 +00003288 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003289 }
3290
Vishnu Naird1f74982023-06-15 20:16:51 -07003291 if ((mDrawingState.producerId > bufferData.producerId) ||
3292 ((mDrawingState.producerId == bufferData.producerId) &&
3293 (mDrawingState.frameNumber > frameNumber))) {
3294 ALOGE("Out of order buffers detected for %s producedId=%d frameNumber=%" PRIu64
3295 " -> producedId=%d frameNumber=%" PRIu64,
3296 getDebugName(), mDrawingState.producerId, mDrawingState.frameNumber,
3297 bufferData.producerId, frameNumber);
3298 TransactionTraceWriter::getInstance().invoke("out_of_order_buffers_", /*overwrite=*/false);
3299 }
3300
liulijuneb489f62022-10-17 22:02:14 +08003301 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -07003302 mDrawingState.barrierProducerId =
3303 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003304 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -07003305 mDrawingState.barrierFrameNumber =
3306 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
3307
Patrick Williamsbb25f802022-08-30 23:02:34 +00003308 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3309 mDrawingState.buffer = std::move(buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003310 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3311 ? bufferData.acquireFence
3312 : Fence::NO_FENCE;
3313 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3314 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3315 // We latched this buffer unsiganled, so we need to pass the acquire fence
3316 // on the callback instead of just the acquire time, since it's unknown at
3317 // this point.
3318 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3319 } else {
3320 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3321 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003322 setTransactionFlags(eTransactionNeeded);
3323
3324 const int32_t layerId = getSequence();
3325 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3326 mOwnerUid, postTime, getGameMode());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003327
Lloyd Pique30db6402023-06-26 18:56:51 +00003328 if (mFlinger->mLegacyFrontEndEnabled) {
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003329 recordLayerHistoryBufferUpdate(getLayerProps(), systemTime());
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003330 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003331
3332 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3333
3334 if (dequeueTime && *dequeueTime != 0) {
3335 const uint64_t bufferId = mDrawingState.buffer->getId();
3336 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3337 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3338 FrameTracer::FrameEvent::DEQUEUE);
3339 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3340 FrameTracer::FrameEvent::QUEUE);
3341 }
3342
3343 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
Arthur Hungc70bee22023-06-02 01:35:52 +00003344
3345 // If the layer had been updated a TextureView, this would make sure the present time could be
3346 // same to TextureView update when it's a small dirty, and get the correct heuristic rate.
Jerry Chang36678002023-11-29 16:56:17 +00003347 if (mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00003348 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3349 mUsedVsyncIdForRefreshRateSelection = true;
3350 }
3351 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003352 return true;
3353}
3354
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003355void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3356 mDrawingState.desiredPresentTime = desiredPresentTime;
3357 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3358}
3359
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003360void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps, nsecs_t now) {
Ady Abraham55269162023-05-09 11:26:06 -07003361 ATRACE_CALL();
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003362 const nsecs_t presentTime = [&] {
Ady Abraham55269162023-05-09 11:26:06 -07003363 if (!mDrawingState.isAutoTimestamp) {
3364 ATRACE_FORMAT_INSTANT("desiredPresentTime");
3365 return mDrawingState.desiredPresentTime;
3366 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003367
Ady Abraham55269162023-05-09 11:26:06 -07003368 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3369 const auto prediction =
3370 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3371 mDrawingState.latchedVsyncId);
3372 if (prediction.has_value()) {
3373 ATRACE_FORMAT_INSTANT("predictedPresentTime");
Arthur Hungc70bee22023-06-02 01:35:52 +00003374 mMaxTimeForUseVsyncId = prediction->presentTime +
3375 scheduler::LayerHistory::kMaxPeriodForHistory.count();
Ady Abraham55269162023-05-09 11:26:06 -07003376 return prediction->presentTime;
3377 }
3378 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003379
Jerry Chang36678002023-11-29 16:56:17 +00003380 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00003381 return static_cast<nsecs_t>(0);
3382 }
3383
3384 // If the layer is not an application and didn't set an explicit rate or desiredPresentTime,
3385 // return "0" to tell the layer history that it will use the max refresh rate without
3386 // calculating the adaptive rate.
3387 if (mWindowType != WindowInfo::Type::APPLICATION &&
3388 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
3389 return static_cast<nsecs_t>(0);
3390 }
3391
3392 // Return the valid present time only when the layer potentially updated a TextureView so
3393 // LayerHistory could heuristically calculate the rate if the UI is continually updating.
3394 if (mUsedVsyncIdForRefreshRateSelection) {
3395 const auto prediction =
3396 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3397 mDrawingState.latchedVsyncId);
3398 if (prediction.has_value()) {
3399 if (mMaxTimeForUseVsyncId >= prediction->presentTime) {
3400 return prediction->presentTime;
3401 }
3402 mUsedVsyncIdForRefreshRateSelection = false;
3403 }
3404 }
3405
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003406 return static_cast<nsecs_t>(0);
3407 }();
Ady Abraham55269162023-05-09 11:26:06 -07003408
3409 if (ATRACE_ENABLED() && presentTime > 0) {
3410 const auto presentIn = TimePoint::fromNs(presentTime) - TimePoint::now();
3411 ATRACE_FORMAT_INSTANT("presentIn %s", to_string(presentIn).c_str());
3412 }
3413
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003414 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003415 scheduler::LayerHistory::LayerUpdateType::Buffer);
3416}
3417
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003418void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps, nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003419 const nsecs_t presentTime =
3420 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003421 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003422 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3423}
3424
Patrick Williamsbb25f802022-08-30 23:02:34 +00003425bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003426 if (mDrawingState.dataspace == dataspace) return false;
3427 mDrawingState.dataspace = dataspace;
3428 mDrawingState.modified = true;
3429 setTransactionFlags(eTransactionNeeded);
3430 return true;
3431}
3432
John Reck68796592023-01-25 13:47:12 -05003433bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07003434 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3435 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05003436 return false;
Sally Qi963049b2023-03-23 14:06:21 -07003437 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3438 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05003439 mDrawingState.modified = true;
3440 setTransactionFlags(eTransactionNeeded);
3441 return true;
3442}
3443
Alec Mouri1b0d4e12024-02-12 22:27:19 +00003444bool Layer::setDesiredHdrHeadroom(float desiredRatio) {
3445 if (mDrawingState.desiredHdrSdrRatio == desiredRatio) return false;
3446 mDrawingState.desiredHdrSdrRatio = desiredRatio;
3447 mDrawingState.modified = true;
3448 setTransactionFlags(eTransactionNeeded);
3449 return true;
3450}
3451
Alec Mourif4af03e2023-02-11 00:25:24 +00003452bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3453 if (mDrawingState.cachingHint == cachingHint) return false;
3454 mDrawingState.cachingHint = cachingHint;
3455 mDrawingState.modified = true;
3456 setTransactionFlags(eTransactionNeeded);
3457 return true;
3458}
3459
Patrick Williamsbb25f802022-08-30 23:02:34 +00003460bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3461 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3462 mDrawingState.hdrMetadata = hdrMetadata;
3463 mDrawingState.modified = true;
3464 setTransactionFlags(eTransactionNeeded);
3465 return true;
3466}
3467
3468bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003469 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003470 mDrawingState.surfaceDamageRegion = surfaceDamage;
3471 mDrawingState.modified = true;
3472 setTransactionFlags(eTransactionNeeded);
Arthur Hung69f95222023-10-04 07:39:02 +00003473 setIsSmallDirty(surfaceDamage, getTransform());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003474 return true;
3475}
3476
3477bool Layer::setApi(int32_t api) {
3478 if (mDrawingState.api == api) return false;
3479 mDrawingState.api = api;
3480 mDrawingState.modified = true;
3481 setTransactionFlags(eTransactionNeeded);
3482 return true;
3483}
3484
Dorin Drimuse5374e52023-08-02 17:52:43 +00003485bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream, const FrameTimelineInfo& info,
3486 nsecs_t postTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003487 if (mDrawingState.sidebandStream == sidebandStream) return false;
3488
3489 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3490 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3491 } else if (sidebandStream != nullptr) {
3492 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3493 }
3494
3495 mDrawingState.sidebandStream = sidebandStream;
3496 mDrawingState.modified = true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003497 if (sidebandStream != nullptr && mDrawingState.buffer != nullptr) {
3498 releasePreviousBuffer();
3499 resetDrawingStateBufferInfo();
3500 mDrawingState.bufferSurfaceFrameTX = nullptr;
3501 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3502 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003503 setTransactionFlags(eTransactionNeeded);
3504 if (!mSidebandStreamChanged.exchange(true)) {
3505 // mSidebandStreamChanged was false
3506 mFlinger->onLayerUpdate();
3507 }
3508 return true;
3509}
3510
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003511bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3512 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003513 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3514 if (handles.empty()) {
3515 mReleasePreviousBuffer = false;
3516 return false;
3517 }
3518
Pascal Muetschard81cef292023-02-06 12:18:52 +01003519 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003520 for (const auto& handle : handles) {
3521 // If this transaction set a buffer on this layer, release its previous buffer
3522 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3523
3524 // If this layer will be presented in this frame
3525 if (willPresent) {
3526 // If this transaction set an acquire fence on this layer, set its acquire time
3527 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3528 handle->frameNumber = mDrawingState.frameNumber;
Alec Mouri21d94322023-10-17 19:51:39 +00003529 handle->previousFrameNumber = mDrawingState.previousFrameNumber;
Melody Hsu793f8362024-01-08 20:00:35 +00003530 if (FlagManager::getInstance().ce_fence_promise() &&
Alec Mouri9892aac2023-12-11 21:16:59 +00003531 mPreviousReleaseBufferEndpoint == handle->listener) {
3532 // Add fences from previous screenshots now so that they can be dispatched to the
3533 // client.
Melody Hsu793f8362024-01-08 20:00:35 +00003534 for (auto& futureReleaseFence : mAdditionalPreviousReleaseFences) {
3535 handle->previousReleaseFences.emplace_back(std::move(futureReleaseFence));
Alec Mouri9892aac2023-12-11 21:16:59 +00003536 }
3537 mAdditionalPreviousReleaseFences.clear();
Melody Hsu793f8362024-01-08 20:00:35 +00003538 } else if (FlagManager::getInstance().screenshot_fence_preservation() &&
3539 mPreviousReleaseBufferEndpoint == handle->listener) {
3540 // Add fences from previous screenshots now so that they can be dispatched to the
3541 // client.
3542 for (const auto& futureAndContinution : mPreviousReleaseFenceAndContinuations) {
3543 handle->previousSharedReleaseFences.emplace_back(futureAndContinution.chain());
3544 }
3545 mPreviousReleaseFenceAndContinuations.clear();
Alec Mouri9892aac2023-12-11 21:16:59 +00003546 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003547 // Store so latched time and release fence can be set
3548 mDrawingState.callbackHandles.push_back(handle);
3549
3550 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003551 // Queue this handle to be notified below.
3552 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003553 }
3554 }
3555
Pascal Muetschard81cef292023-02-06 12:18:52 +01003556 if (!remainingHandles.empty()) {
3557 // Notify the transaction completed threads these handles are done. These are only the
3558 // handles that were not added to the mDrawingState, which will be notified later.
3559 std::vector<JankData> jankData;
3560 transferAvailableJankData(remainingHandles, jankData);
3561 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3562 }
3563
Patrick Williamsbb25f802022-08-30 23:02:34 +00003564 mReleasePreviousBuffer = false;
3565 mCallbackHandleAcquireTimeOrFence = -1;
3566
3567 return willPresent;
3568}
3569
3570Rect Layer::getBufferSize(const State& /*s*/) const {
3571 // for buffer state layers we use the display frame size as the buffer size.
3572
3573 if (mBufferInfo.mBuffer == nullptr) {
3574 return Rect::INVALID_RECT;
3575 }
3576
3577 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3578 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3579
3580 // Undo any transformations on the buffer and return the result.
3581 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3582 std::swap(bufWidth, bufHeight);
3583 }
3584
3585 if (getTransformToDisplayInverse()) {
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003586 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003587 if (invTransform & ui::Transform::ROT_90) {
3588 std::swap(bufWidth, bufHeight);
3589 }
3590 }
3591
3592 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3593}
3594
3595FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3596 if (mBufferInfo.mBuffer == nullptr) {
3597 return parentBounds;
3598 }
3599
3600 return getBufferSize(getDrawingState()).toFloatRect();
3601}
3602
3603bool Layer::fenceHasSignaled() const {
3604 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3605 return true;
3606 }
3607
3608 const bool fenceSignaled =
3609 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3610 if (!fenceSignaled) {
3611 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3612 TimeStats::LatchSkipReason::LateAcquire);
3613 }
3614
3615 return fenceSignaled;
3616}
3617
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003618void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003619 for (const auto& handle : mDrawingState.callbackHandles) {
3620 handle->refreshStartTime = refreshStartTime;
3621 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003622}
3623
3624void Layer::setAutoRefresh(bool autoRefresh) {
3625 mDrawingState.autoRefresh = autoRefresh;
3626}
3627
3628bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3629 // 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 +00003630 auto* snapshot = editLayerSnapshot();
3631 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003632
3633 if (mSidebandStreamChanged.exchange(false)) {
3634 const State& s(getDrawingState());
3635 // mSidebandStreamChanged was true
3636 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003637 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003638 if (mSidebandStream != nullptr) {
3639 setTransactionFlags(eTransactionNeeded);
3640 mFlinger->setTransactionFlags(eTraversalNeeded);
3641 }
3642 recomputeVisibleRegions = true;
3643
3644 return true;
3645 }
3646 return false;
3647}
3648
3649bool Layer::hasFrameUpdate() const {
3650 const State& c(getDrawingState());
3651 return (mDrawingStateModified || mDrawingState.modified) &&
3652 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3653}
3654
Vishnu Naird47bcee2023-02-24 18:08:51 +00003655void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003656 const State& s(getDrawingState());
3657
3658 if (!s.buffer) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003659 if (bgColorOnly || mBufferInfo.mBuffer) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003660 for (auto& handle : mDrawingState.callbackHandles) {
3661 handle->latchTime = latchTime;
3662 }
3663 }
3664 return;
3665 }
3666
3667 for (auto& handle : mDrawingState.callbackHandles) {
3668 if (handle->frameNumber == mDrawingState.frameNumber) {
3669 handle->latchTime = latchTime;
3670 }
3671 }
3672
3673 const int32_t layerId = getSequence();
3674 const uint64_t bufferId = mDrawingState.buffer->getId();
3675 const uint64_t frameNumber = mDrawingState.frameNumber;
3676 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3677 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3678 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3679
3680 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3681 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3682 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3683 FrameTracer::FrameEvent::LATCH);
3684
3685 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3686 if (bufferSurfaceFrame != nullptr &&
3687 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3688 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3689 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3690 // are processing the next state.
3691 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3692 mDrawingState.acquireFenceTime->getSignalTime(),
3693 latchTime);
3694 mDrawingState.bufferSurfaceFrameTX.reset();
3695 }
3696
3697 std::deque<sp<CallbackHandle>> remainingHandles;
3698 mFlinger->getTransactionCallbackInvoker()
3699 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3700 mDrawingState.callbackHandles = remainingHandles;
3701
3702 mDrawingStateModified = false;
3703}
3704
3705void Layer::gatherBufferInfo() {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003706 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3707 mPreviousReleaseBufferEndpoint = mBufferInfo.mReleaseBufferEndpoint;
3708 if (!mDrawingState.buffer) {
3709 mBufferInfo = {};
3710 return;
3711 }
3712
3713 if ((!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer))) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003714 decrementPendingBufferCount();
3715 }
3716
Patrick Williamsbb25f802022-08-30 23:02:34 +00003717 mBufferInfo.mBuffer = mDrawingState.buffer;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003718 mBufferInfo.mReleaseBufferEndpoint = mDrawingState.releaseBufferEndpoint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003719 mBufferInfo.mFence = mDrawingState.acquireFence;
3720 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3721 mBufferInfo.mPixelFormat =
3722 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3723 mBufferInfo.mFrameLatencyNeeded = true;
3724 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3725 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3726 mBufferInfo.mFence = mDrawingState.acquireFence;
3727 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3728 auto lastDataspace = mBufferInfo.mDataspace;
3729 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003730 if (mBufferInfo.mBuffer != nullptr) {
3731 auto& mapper = GraphicBufferMapper::get();
3732 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
3733 // and don't need to possibly remaps buffers.
3734 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
3735 status_t err = OK;
3736 {
3737 ATRACE_NAME("getDataspace");
3738 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
3739 }
3740 if (err != OK || dataspace != mBufferInfo.mDataspace) {
3741 {
3742 ATRACE_NAME("setDataspace");
3743 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
3744 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
3745 }
3746
3747 // Some GPU drivers may cache gralloc metadata which means before we composite we need
3748 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
3749 // compatible with old vendors, with a ticking clock.
3750 static const int32_t kVendorVersion =
Alec Mouri8a06fb72023-11-16 22:07:13 +00003751 base::GetIntProperty("ro.board.api_level", __ANDROID_API_FUTURE__);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003752 if (const auto format =
3753 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
3754 mBufferInfo.mBuffer->getPixelFormat());
3755 err == OK && kVendorVersion < __ANDROID_API_U__ &&
3756 (format ==
3757 aidl::android::hardware::graphics::common::PixelFormat::
3758 IMPLEMENTATION_DEFINED ||
3759 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
3760 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
3761 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
3762 mBufferInfo.mBuffer->remapBuffer();
3763 }
3764 }
3765 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003766 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003767 mFlinger->mHdrLayerInfoChanged = true;
3768 }
Sally Qi963049b2023-03-23 14:06:21 -07003769 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3770 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05003771 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003772 }
3773 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3774 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3775 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3776 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3777 mBufferInfo.mApi = mDrawingState.api;
3778 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003779}
3780
3781Rect Layer::computeBufferCrop(const State& s) {
3782 if (s.buffer && !s.bufferCrop.isEmpty()) {
3783 Rect bufferCrop;
3784 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3785 return bufferCrop;
3786 } else if (s.buffer) {
3787 return s.buffer->getBounds();
3788 } else {
3789 return s.bufferCrop;
3790 }
3791}
3792
Vishnu Nairde177252023-04-21 12:44:10 -07003793sp<Layer> Layer::createClone(uint32_t mirrorRootId) {
Kean Mariotti4ba343c2023-04-19 13:31:02 +00003794 surfaceflinger::LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0,
3795 LayerMetadata());
Patrick Williams83f36b22022-09-14 17:57:35 +00003796 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Vishnu Nairde177252023-04-21 12:44:10 -07003797 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this), mirrorRootId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003798 return layer;
3799}
3800
Patrick Williamsbb25f802022-08-30 23:02:34 +00003801void Layer::decrementPendingBufferCount() {
3802 int32_t pendingBuffers = --mPendingBufferTransactions;
3803 tracePendingBufferCount(pendingBuffers);
3804}
3805
3806void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3807 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3808}
3809
3810/*
3811 * We don't want to send the layer's transform to input, but rather the
3812 * parent's transform. This is because Layer's transform is
3813 * information about how the buffer is placed on screen. The parent's
3814 * transform makes more sense to send since it's information about how the
3815 * layer is placed on screen. This transform is used by input to determine
3816 * how to go from screen space back to window space.
3817 */
3818ui::Transform Layer::getInputTransform() const {
3819 if (!hasBufferOrSidebandStream()) {
3820 return getTransform();
3821 }
3822 sp<Layer> parent = mDrawingParent.promote();
3823 if (parent == nullptr) {
3824 return ui::Transform();
3825 }
3826
3827 return parent->getTransform();
3828}
3829
3830/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003831 * Returns the bounds used to fill the input frame and the touchable region.
3832 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003833 * Similar to getInputTransform, we need to update the bounds to include the transform.
3834 * This is because bounds don't include the buffer transform, where the input assumes
3835 * that's already included.
3836 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003837std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3838 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3839 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3840 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3841 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3842 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003843 }
3844
Vishnu Nairfed7c122023-03-18 01:54:43 +00003845 bool inputBoundsValid = croppedBufferSize.isValid();
3846 if (!inputBoundsValid) {
3847 /**
3848 * Input bounds are based on the layer crop or buffer size. But if we are using
3849 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3850 * we can use the parent bounds as the input bounds if the layer does not have buffer
3851 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3852 * use the parent bounds. A layer without a buffer can get input. So when a window is
3853 * initially added, its touchable region can fill its parent layer bounds and that can
3854 * have negative consequences.
3855 */
3856 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003857 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003858
3859 // Clamp surface inset to the input bounds.
3860 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3861 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3862 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3863
3864 // Apply the insets to the input bounds.
3865 inputBounds.left += xSurfaceInset;
3866 inputBounds.top += ySurfaceInset;
3867 inputBounds.right -= xSurfaceInset;
3868 inputBounds.bottom -= ySurfaceInset;
3869
3870 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003871}
3872
Ady Abraham005398b2023-06-05 13:59:41 -07003873bool Layer::isSimpleBufferUpdate(const layer_state_t& s) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003874 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3875
3876 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3877 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3878 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3879 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3880 layer_state_t::eReparent;
3881
Patrick Williamsbb25f802022-08-30 23:02:34 +00003882 if ((s.what & requiredFlags) != requiredFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003883 ATRACE_FORMAT_INSTANT("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3884 (s.what | requiredFlags) & ~s.what);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003885 return false;
3886 }
3887
3888 if (s.what & deniedFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003889 ATRACE_FORMAT_INSTANT("%s: false [has denied flags 0x%" PRIx64 "]", __func__,
3890 s.what & deniedFlags);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003891 return false;
3892 }
3893
Patrick Williamsbb25f802022-08-30 23:02:34 +00003894 if (s.what & layer_state_t::ePositionChanged) {
3895 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
Ady Abraham005398b2023-06-05 13:59:41 -07003896 ATRACE_FORMAT_INSTANT("%s: false [ePositionChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003897 return false;
3898 }
3899 }
3900
3901 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003902 if (mDrawingState.color.a != s.color.a) {
Ady Abraham005398b2023-06-05 13:59:41 -07003903 ATRACE_FORMAT_INSTANT("%s: false [eAlphaChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003904 return false;
3905 }
3906 }
3907
3908 if (s.what & layer_state_t::eColorTransformChanged) {
3909 if (mDrawingState.colorTransform != s.colorTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003910 ATRACE_FORMAT_INSTANT("%s: false [eColorTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003911 return false;
3912 }
3913 }
3914
3915 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003916 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Ady Abraham005398b2023-06-05 13:59:41 -07003917 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundColorChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003918 return false;
3919 }
3920 }
3921
3922 if (s.what & layer_state_t::eMatrixChanged) {
3923 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3924 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3925 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3926 mRequestedTransform.dsdy() != s.matrix.dsdy) {
Ady Abraham005398b2023-06-05 13:59:41 -07003927 ATRACE_FORMAT_INSTANT("%s: false [eMatrixChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003928 return false;
3929 }
3930 }
3931
3932 if (s.what & layer_state_t::eCornerRadiusChanged) {
3933 if (mDrawingState.cornerRadius != s.cornerRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003934 ATRACE_FORMAT_INSTANT("%s: false [eCornerRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003935 return false;
3936 }
3937 }
3938
3939 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3940 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
Ady Abraham005398b2023-06-05 13:59:41 -07003941 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003942 return false;
3943 }
3944 }
3945
Vishnu Nairbbceb462022-10-10 04:52:13 +00003946 if (s.what & layer_state_t::eBufferTransformChanged) {
3947 if (mDrawingState.bufferTransform != s.bufferTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003948 ATRACE_FORMAT_INSTANT("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003949 return false;
3950 }
3951 }
3952
3953 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3954 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
Ady Abraham005398b2023-06-05 13:59:41 -07003955 ATRACE_FORMAT_INSTANT("%s: false [eTransformToDisplayInverseChanged changed]",
3956 __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003957 return false;
3958 }
3959 }
3960
3961 if (s.what & layer_state_t::eCropChanged) {
3962 if (mDrawingState.crop != s.crop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003963 ATRACE_FORMAT_INSTANT("%s: false [eCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003964 return false;
3965 }
3966 }
3967
3968 if (s.what & layer_state_t::eDataspaceChanged) {
3969 if (mDrawingState.dataspace != s.dataspace) {
Ady Abraham005398b2023-06-05 13:59:41 -07003970 ATRACE_FORMAT_INSTANT("%s: false [eDataspaceChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003971 return false;
3972 }
3973 }
3974
3975 if (s.what & layer_state_t::eHdrMetadataChanged) {
3976 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
Ady Abraham005398b2023-06-05 13:59:41 -07003977 ATRACE_FORMAT_INSTANT("%s: false [eHdrMetadataChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003978 return false;
3979 }
3980 }
3981
3982 if (s.what & layer_state_t::eSidebandStreamChanged) {
3983 if (mDrawingState.sidebandStream != s.sidebandStream) {
Ady Abraham005398b2023-06-05 13:59:41 -07003984 ATRACE_FORMAT_INSTANT("%s: false [eSidebandStreamChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003985 return false;
3986 }
3987 }
3988
3989 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3990 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
Ady Abraham005398b2023-06-05 13:59:41 -07003991 ATRACE_FORMAT_INSTANT("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003992 return false;
3993 }
3994 }
3995
3996 if (s.what & layer_state_t::eShadowRadiusChanged) {
3997 if (mDrawingState.shadowRadius != s.shadowRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003998 ATRACE_FORMAT_INSTANT("%s: false [eShadowRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003999 return false;
4000 }
4001 }
4002
4003 if (s.what & layer_state_t::eFixedTransformHintChanged) {
4004 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
Ady Abraham005398b2023-06-05 13:59:41 -07004005 ATRACE_FORMAT_INSTANT("%s: false [eFixedTransformHintChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004006 return false;
4007 }
4008 }
4009
4010 if (s.what & layer_state_t::eTrustedOverlayChanged) {
4011 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
Ady Abraham005398b2023-06-05 13:59:41 -07004012 ATRACE_FORMAT_INSTANT("%s: false [eTrustedOverlayChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004013 return false;
4014 }
4015 }
4016
4017 if (s.what & layer_state_t::eStretchChanged) {
4018 StretchEffect temp = s.stretchEffect;
4019 temp.sanitize();
4020 if (mDrawingState.stretchEffect != temp) {
Ady Abraham005398b2023-06-05 13:59:41 -07004021 ATRACE_FORMAT_INSTANT("%s: false [eStretchChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004022 return false;
4023 }
4024 }
4025
4026 if (s.what & layer_state_t::eBufferCropChanged) {
4027 if (mDrawingState.bufferCrop != s.bufferCrop) {
Ady Abraham005398b2023-06-05 13:59:41 -07004028 ATRACE_FORMAT_INSTANT("%s: false [eBufferCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004029 return false;
4030 }
4031 }
4032
4033 if (s.what & layer_state_t::eDestinationFrameChanged) {
4034 if (mDrawingState.destinationFrame != s.destinationFrame) {
Ady Abraham005398b2023-06-05 13:59:41 -07004035 ATRACE_FORMAT_INSTANT("%s: false [eDestinationFrameChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004036 return false;
4037 }
4038 }
4039
4040 if (s.what & layer_state_t::eDimmingEnabledChanged) {
4041 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
Ady Abraham005398b2023-06-05 13:59:41 -07004042 ATRACE_FORMAT_INSTANT("%s: false [eDimmingEnabledChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004043 return false;
4044 }
4045 }
4046
John Reck68796592023-01-25 13:47:12 -05004047 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07004048 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
4049 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
Ady Abraham005398b2023-06-05 13:59:41 -07004050 ATRACE_FORMAT_INSTANT("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05004051 return false;
4052 }
4053 }
4054
Alec Mouri1b0d4e12024-02-12 22:27:19 +00004055 if (s.what & layer_state_t::eDesiredHdrHeadroomChanged) {
4056 if (mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
4057 ATRACE_FORMAT_INSTANT("%s: false [eDesiredHdrHeadroomChanged changed]", __func__);
4058 return false;
4059 }
4060 }
4061
Patrick Williamsbb25f802022-08-30 23:02:34 +00004062 return true;
4063}
4064
Vishnu Naire14c6b32022-08-06 04:20:15 +00004065sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004066 // 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 +00004067 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004068}
4069
Vishnu Naire14c6b32022-08-06 04:20:15 +00004070const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004071 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00004072}
4073
Vishnu Naire14c6b32022-08-06 04:20:15 +00004074LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004075 return mSnapshot.get();
4076}
Vishnu Naire14c6b32022-08-06 04:20:15 +00004077
Vishnu Nair3af0ec02023-02-10 04:13:48 +00004078std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
4079 return std::move(mSnapshot);
4080}
4081
4082void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
4083 mSnapshot = std::move(snapshot);
4084}
4085
Patrick Williamsbb25f802022-08-30 23:02:34 +00004086const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004087 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00004088}
4089
Patrick Williams7584c6a2022-10-29 02:10:58 +00004090sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00004091 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00004092 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
4093 return result;
4094}
4095
Vishnu Nair3af0ec02023-02-10 04:13:48 +00004096sp<LayerFE> Layer::getCompositionEngineLayerFE(
4097 const frontend::LayerHierarchy::TraversalPath& path) {
4098 for (auto& [p, layerFE] : mLayerFEs) {
4099 if (p == path) {
4100 return layerFE;
4101 }
4102 }
4103 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
4104 mLayerFEs.emplace_back(path, layerFE);
4105 return layerFE;
4106}
4107
Patrick Williamsbb25f802022-08-30 23:02:34 +00004108void Layer::useSurfaceDamage() {
4109 if (mFlinger->mForceFullDamage) {
4110 surfaceDamageRegion = Region::INVALID_REGION;
4111 } else {
4112 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
4113 }
4114}
4115
4116void Layer::useEmptyDamage() {
4117 surfaceDamageRegion.clear();
4118}
4119
4120bool Layer::isOpaque(const Layer::State& s) const {
4121 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
4122 // layer's opaque flag.
4123 if (!hasSomethingToDraw()) {
4124 return false;
4125 }
4126
4127 // if the layer has the opaque flag, then we're always opaque
4128 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
4129 return true;
4130 }
4131
4132 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004133 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004134 return true;
4135 }
4136
4137 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
4138 return fillsColor() && getAlpha() == 1.0_hf;
4139}
4140
4141bool Layer::canReceiveInput() const {
4142 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
4143}
4144
4145bool Layer::isVisible() const {
4146 if (!hasSomethingToDraw()) {
4147 return false;
4148 }
4149
4150 if (isHiddenByPolicy()) {
4151 return false;
4152 }
4153
4154 return getAlpha() > 0.0f || hasBlur();
4155}
4156
Leon Scroggins III5b581492023-10-31 14:29:41 -04004157void Layer::onCompositionPresented(const DisplayDevice* display,
4158 const std::shared_ptr<FenceTime>& glDoneFence,
4159 const std::shared_ptr<FenceTime>& presentFence,
4160 const CompositorTiming& compositorTiming) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004161 // mFrameLatencyNeeded is true when a new frame was latched for the
4162 // composition.
4163 if (!mBufferInfo.mFrameLatencyNeeded) return;
4164
4165 for (const auto& handle : mDrawingState.callbackHandles) {
4166 handle->gpuCompositionDoneFence = glDoneFence;
4167 handle->compositorTiming = compositorTiming;
4168 }
4169
4170 // Update mFrameTracker.
4171 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
4172 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
4173
4174 const int32_t layerId = getSequence();
4175 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
4176
4177 const auto outputLayer = findOutputLayerForDisplay(display);
4178 if (outputLayer && outputLayer->requiresClientComposition()) {
4179 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
4180 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4181 clientCompositionTimestamp,
4182 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
4183 // Update the SurfaceFrames in the drawing state
4184 if (mDrawingState.bufferSurfaceFrameTX) {
4185 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
4186 }
4187 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
4188 surfaceFrame->setGpuComposition();
4189 }
4190 }
4191
4192 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
4193 if (frameReadyFence->isValid()) {
4194 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
4195 } else {
4196 // There was no fence for this frame, so assume that it was ready
4197 // to be presented at the desired present time.
4198 mFrameTracker.setFrameReadyTime(desiredPresentTime);
4199 }
4200
4201 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08004202 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004203 const std::optional<Fps> renderRate =
4204 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
4205
Alec Mouri7c1d8b52023-08-29 20:14:46 +00004206 const auto vote = frameRateToSetFrameRateVotePayload(getFrameRateForLayerTree());
Patrick Williamsbb25f802022-08-30 23:02:34 +00004207 const auto gameMode = getGameMode();
4208
4209 if (presentFence->isValid()) {
4210 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
4211 refreshRate, renderRate, vote, gameMode);
4212 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4213 presentFence,
4214 FrameTracer::FrameEvent::PRESENT_FENCE);
4215 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
4216 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
4217 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04004218 // The HWC doesn't support present fences, so use the present timestamp instead.
4219 const nsecs_t presentTimestamp =
4220 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
4221
4222 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
4223 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
4224 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
4225
Patrick Williamsbb25f802022-08-30 23:02:34 +00004226 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
4227 refreshRate, renderRate, vote, gameMode);
4228 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
4229 mCurrentFrameNumber, actualPresentTime,
4230 FrameTracer::FrameEvent::PRESENT_FENCE);
4231 mFrameTracker.setActualPresentTime(actualPresentTime);
4232 }
4233 }
4234
4235 mFrameTracker.advanceFrame();
4236 mBufferInfo.mFrameLatencyNeeded = false;
4237}
4238
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004239bool Layer::willReleaseBufferOnLatch() const {
4240 return !mDrawingState.buffer && mBufferInfo.mBuffer;
4241}
4242
Patrick Williamsbb25f802022-08-30 23:02:34 +00004243bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00004244 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
4245 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
4246}
4247
4248bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004249 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
4250 getDrawingState().frameNumber);
4251
4252 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
4253
4254 if (refreshRequired) {
4255 return refreshRequired;
4256 }
4257
4258 // If the head buffer's acquire fence hasn't signaled yet, return and
4259 // try again later
4260 if (!fenceHasSignaled()) {
4261 ATRACE_NAME("!fenceHasSignaled()");
4262 mFlinger->onLayerUpdate();
4263 return false;
4264 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00004265 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004266
4267 // Capture the old state of the layer for comparisons later
4268 BufferInfo oldBufferInfo = mBufferInfo;
4269 const bool oldOpacity = isOpaque(mDrawingState);
4270 mPreviousFrameNumber = mCurrentFrameNumber;
4271 mCurrentFrameNumber = mDrawingState.frameNumber;
4272 gatherBufferInfo();
4273
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004274 if (mBufferInfo.mBuffer) {
4275 // We latched a buffer that will be presented soon. Clear the previously presented layer
4276 // stack list.
4277 mPreviouslyPresentedLayerStacks.clear();
4278 }
4279
4280 if (mDrawingState.buffer == nullptr) {
4281 const bool bufferReleased = oldBufferInfo.mBuffer != nullptr;
4282 recomputeVisibleRegions = bufferReleased;
4283 return bufferReleased;
4284 }
4285
Patrick Williamsbb25f802022-08-30 23:02:34 +00004286 if (oldBufferInfo.mBuffer == nullptr) {
4287 // the first time we receive a buffer, we need to trigger a
4288 // geometry invalidation.
4289 recomputeVisibleRegions = true;
4290 }
4291
4292 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
4293 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
4294 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
4295 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
4296 recomputeVisibleRegions = true;
4297 }
4298
4299 if (oldBufferInfo.mBuffer != nullptr) {
4300 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
4301 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
4302 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
4303 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
4304 recomputeVisibleRegions = true;
4305 }
4306 }
4307
4308 if (oldOpacity != isOpaque(mDrawingState)) {
4309 recomputeVisibleRegions = true;
4310 }
4311
4312 return true;
4313}
4314
4315bool Layer::hasReadyFrame() const {
4316 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4317}
4318
4319bool Layer::isProtected() const {
4320 return (mBufferInfo.mBuffer != nullptr) &&
4321 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4322}
4323
Patrick Williamsbb25f802022-08-30 23:02:34 +00004324void Layer::latchAndReleaseBuffer() {
4325 if (hasReadyFrame()) {
4326 bool ignored = false;
4327 latchBuffer(ignored, systemTime());
4328 }
4329 releasePendingBuffer(systemTime());
4330}
4331
4332PixelFormat Layer::getPixelFormat() const {
4333 return mBufferInfo.mPixelFormat;
4334}
4335
4336bool Layer::getTransformToDisplayInverse() const {
4337 return mBufferInfo.mTransformToDisplayInverse;
4338}
4339
4340Rect Layer::getBufferCrop() const {
4341 // this is the crop rectangle that applies to the buffer
4342 // itself (as opposed to the window)
4343 if (!mBufferInfo.mCrop.isEmpty()) {
4344 // if the buffer crop is defined, we use that
4345 return mBufferInfo.mCrop;
4346 } else if (mBufferInfo.mBuffer != nullptr) {
4347 // otherwise we use the whole buffer
4348 return mBufferInfo.mBuffer->getBounds();
4349 } else {
4350 // if we don't have a buffer yet, we use an empty/invalid crop
4351 return Rect();
4352 }
4353}
4354
4355uint32_t Layer::getBufferTransform() const {
4356 return mBufferInfo.mTransform;
4357}
4358
4359ui::Dataspace Layer::getDataSpace() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004360 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4361}
4362
Alec Mouri89f5d4e2023-10-20 17:12:49 +00004363bool Layer::isFrontBuffered() const {
4364 if (mBufferInfo.mBuffer == nullptr) {
4365 return false;
4366 }
4367
4368 return mBufferInfo.mBuffer->getUsage() & AHARDWAREBUFFER_USAGE_FRONT_BUFFER;
4369}
4370
Patrick Williamsbb25f802022-08-30 23:02:34 +00004371ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4372 ui::Dataspace updatedDataspace = dataspace;
4373 // translate legacy dataspaces to modern dataspaces
4374 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00004375 // Treat unknown dataspaces as V0_sRGB
4376 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00004377 case ui::Dataspace::SRGB:
4378 updatedDataspace = ui::Dataspace::V0_SRGB;
4379 break;
4380 case ui::Dataspace::SRGB_LINEAR:
4381 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4382 break;
4383 case ui::Dataspace::JFIF:
4384 updatedDataspace = ui::Dataspace::V0_JFIF;
4385 break;
4386 case ui::Dataspace::BT601_625:
4387 updatedDataspace = ui::Dataspace::V0_BT601_625;
4388 break;
4389 case ui::Dataspace::BT601_525:
4390 updatedDataspace = ui::Dataspace::V0_BT601_525;
4391 break;
4392 case ui::Dataspace::BT709:
4393 updatedDataspace = ui::Dataspace::V0_BT709;
4394 break;
4395 default:
4396 break;
4397 }
4398
4399 return updatedDataspace;
4400}
4401
4402sp<GraphicBuffer> Layer::getBuffer() const {
4403 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4404}
4405
Vishnu Nairb76d99a2023-03-19 18:22:31 -07004406void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4407 mTransformHintLegacy = getFixedTransformHint();
4408 if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4409 mTransformHintLegacy = displayTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004410 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004411 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004412}
4413
4414const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4415 return mBufferInfo.mBuffer;
4416}
4417
4418bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004419 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004420 return false;
4421 }
4422
4423 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004424 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004425 mDrawingState.modified = true;
4426 setTransactionFlags(eTransactionNeeded);
4427 return true;
4428}
4429
4430bool Layer::fillsColor() const {
4431 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4432 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4433}
4434
4435bool Layer::hasBlur() const {
4436 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4437}
4438
Vishnu Nairba354102022-08-01 00:14:18 +00004439void Layer::updateSnapshot(bool updateGeometry) {
4440 if (!getCompositionEngineLayerFE()) {
4441 return;
4442 }
4443
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004444 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004445 if (updateGeometry) {
4446 prepareBasicGeometryCompositionState();
4447 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004448 snapshot->roundedCorner = getRoundedCornerState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004449 snapshot->transformedBounds = mScreenBounds;
4450 if (mEffectiveShadowRadius > 0.f) {
4451 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4452
4453 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4454 // it if transparent regions are present. This may not be necessary since shadows are
4455 // typically cast by layers without transparent regions.
4456 snapshot->shadowSettings.boundaries = mBounds;
4457
4458 const float casterAlpha = snapshot->alpha;
4459 const bool casterIsOpaque =
4460 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4461
4462 // If the casting layer is translucent, we need to fill in the shadow underneath the
4463 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4464 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4465 snapshot->shadowSettings.ambientColor *= casterAlpha;
4466 snapshot->shadowSettings.spotColor *= casterAlpha;
4467 }
4468 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004469 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004470 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004471 snapshot->layerOpaqueFlagSet =
4472 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004473 sp<Layer> p = mDrawingParent.promote();
4474 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004475 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004476 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004477 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004478 }
4479 snapshot->bufferSize = getBufferSize(mDrawingState);
4480 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004481 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004482 preparePerFrameCompositionState();
4483}
4484
Vishnu Naire14c6b32022-08-06 04:20:15 +00004485void Layer::updateChildrenSnapshots(bool updateGeometry) {
4486 for (const sp<Layer>& child : mDrawingChildren) {
4487 child->updateSnapshot(updateGeometry);
4488 child->updateChildrenSnapshots(updateGeometry);
4489 }
4490}
4491
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004492void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4493 mSnapshot->layerMetadata = parentMetadata;
4494 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4495 for (const sp<Layer>& child : mDrawingChildren) {
4496 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4497 }
4498}
4499
4500void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4501 std::unordered_set<Layer*>& visited) {
4502 if (visited.find(this) != visited.end()) {
4503 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4504 return;
4505 }
4506 visited.insert(this);
4507
4508 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4509
4510 if (mDrawingState.zOrderRelatives.empty()) {
4511 return;
4512 }
4513 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4514 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4515 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4516 sp<Layer> relative = weakRelative.promote();
4517 if (!relative) {
4518 continue;
4519 }
4520 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4521 }
4522}
4523
Chavi Weingarten328a8312023-01-26 21:17:52 +00004524bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004525 TrustedPresentationListener const& listener) {
4526 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4527 mTrustedPresentationListener = listener;
4528 mTrustedPresentationThresholds = thresholds;
4529 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4530 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4531 mFlinger->mNumTrustedPresentationListeners++;
4532 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4533 mFlinger->mNumTrustedPresentationListeners--;
4534 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004535
4536 // Reset trusted presentation states to ensure we start the time again.
4537 mEnteredTrustedPresentationStateTime = -1;
4538 mLastReportedTrustedPresentationState = false;
4539 mLastComputedTrustedPresentationState = false;
4540
4541 // If there's a new trusted presentation listener, the code needs to go through the composite
4542 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4543 // we're already in the requested state.
4544 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004545}
4546
Vishnu Naira156f482023-02-22 00:23:38 +00004547void Layer::updateLastLatchTime(nsecs_t latchTime) {
4548 mLastLatchTime = latchTime;
4549}
4550
Arthur Hung69f95222023-10-04 07:39:02 +00004551void Layer::setIsSmallDirty(const Region& damageRegion,
4552 const ui::Transform& layerToDisplayTransform) {
4553 mSmallDirty = false;
Jerry Chang36678002023-11-29 16:56:17 +00004554 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00004555 return;
4556 }
4557
4558 if (mWindowType != WindowInfo::Type::APPLICATION &&
4559 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
4560 return;
4561 }
Arthur Hung69f95222023-10-04 07:39:02 +00004562
4563 Rect bounds = damageRegion.getBounds();
Arthur Hungc70bee22023-06-02 01:35:52 +00004564 if (!bounds.isValid()) {
4565 return;
4566 }
4567
Arthur Hung69f95222023-10-04 07:39:02 +00004568 // Transform to screen space.
4569 bounds = layerToDisplayTransform.transform(bounds);
4570
Arthur Hungc70bee22023-06-02 01:35:52 +00004571 // If the damage region is a small dirty, this could give the hint for the layer history that
4572 // it could suppress the heuristic rate when calculating.
Tony Huangf3621102023-09-04 17:14:22 +08004573 mSmallDirty = mFlinger->mScheduler->isSmallDirtyArea(mOwnerAppId,
Tony Huang9ac5e6e2023-08-24 09:01:44 +00004574 bounds.getWidth() * bounds.getHeight());
Arthur Hungc70bee22023-06-02 01:35:52 +00004575}
4576
Arthur Hung69f95222023-10-04 07:39:02 +00004577void Layer::setIsSmallDirty(frontend::LayerSnapshot* snapshot) {
4578 setIsSmallDirty(snapshot->surfaceDamage, snapshot->localTransform);
4579 snapshot->isSmallDirty = mSmallDirty;
4580}
4581
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004582} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004583
4584#if defined(__gl_h_)
4585#error "don't include gl/gl.h in this file"
4586#endif
4587
4588#if defined(__gl2_h_)
4589#error "don't include gl2/gl2.h in this file"
4590#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004591
4592// TODO(b/129481165): remove the #pragma below and fix conversion issues
4593#pragma clang diagnostic pop // ignored "-Wconversion"