blob: 63dba93792d4e31255d46ae7d88eea7aea6cb71e [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
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Dan Stoza9e56aa02015-11-02 13:00:03 -080021//#define LOG_NDEBUG 0
22#undef LOG_TAG
23#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080024#define ATRACE_TAG ATRACE_TAG_GRAPHICS
25
Alec Mourie60041e2019-06-14 18:59:51 -070026#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080027
[1;3C2b9fc252021-02-04 16:16:50 -080028#include <android-base/properties.h>
Yiwei Zhang5434a782018-12-05 18:06:32 -080029#include <android-base/stringprintf.h>
Vishnu Nair0f085c62019-08-30 08:49:12 -070030#include <binder/IPCThreadState.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000031#include <compositionengine/CompositionEngine.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080032#include <compositionengine/Display.h>
Lloyd Piquea83776c2019-01-29 18:42:32 -080033#include <compositionengine/LayerFECompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080034#include <compositionengine/OutputLayer.h>
35#include <compositionengine/impl/OutputLayerCompositionState.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070036#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070037#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070038#include <cutils/properties.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070039#include <ftl/enum.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080040#include <ftl/fake_guard.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080041#include <gui/BufferItem.h>
42#include <gui/LayerDebugInfo.h>
43#include <gui/Surface.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000044#include <gui/TraceUtils.h>
Alec Mourie60041e2019-06-14 18:59:51 -070045#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070046#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080047#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070048#include <stdint.h>
49#include <stdlib.h>
50#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000051#include <system/graphics-base-v1.0.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080052#include <ui/DebugUtils.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000053#include <ui/FloatRect.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080054#include <ui/GraphicBuffer.h>
Sally Qif6918d42023-08-07 15:28:30 -070055#include <ui/HdrRenderTypeUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080056#include <ui/PixelFormat.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000057#include <ui/Rect.h>
58#include <ui/Transform.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059#include <utils/Errors.h>
60#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080061#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080063#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Alec Mourie60041e2019-06-14 18:59:51 -070065#include <algorithm>
66#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070067#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070068#include <sstream>
69
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070070#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080071#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070072#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070073#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +000074#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000075#include "FrontEnd/LayerHandle.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080076#include "LayerProtoHelper.h"
Josh Gao194ff392022-09-08 16:19:29 -070077#include "MutexUtils.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080079#include "TimeStats/TimeStats.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070080#include "TunnelModeEnabledReporter.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070081
David Sodman41fdfc92017-11-06 16:09:56 -080082#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000083#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085namespace android {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010086namespace {
87constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000088
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000089const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000090
Patrick Williamsbb25f802022-08-30 23:02:34 +000091bool assignTransform(ui::Transform* dst, ui::Transform& from) {
92 if (*dst == from) {
93 return false;
94 }
95 *dst = from;
96 return true;
97}
98
99TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
100 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
101 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
102 const auto frameRateCompatibility = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700103 switch (frameRate.vote.type) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000104 case Layer::FrameRateCompatibility::Default:
105 return FrameRateCompatibility::Default;
106 case Layer::FrameRateCompatibility::ExactOrMultiple:
107 return FrameRateCompatibility::ExactOrMultiple;
108 default:
109 return FrameRateCompatibility::Undefined;
110 }
111 }();
112
113 const auto seamlessness = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700114 switch (frameRate.vote.seamlessness) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000115 case scheduler::Seamlessness::OnlySeamless:
116 return Seamlessness::ShouldBeSeamless;
117 case scheduler::Seamlessness::SeamedAndSeamless:
118 return Seamlessness::NotRequired;
119 default:
120 return Seamlessness::Undefined;
121 }
122 }();
123
Rachel Leece6e0042023-06-27 11:22:54 -0700124 return TimeStats::SetFrameRateVote{.frameRate = frameRate.vote.rate.getValue(),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000125 .frameRateCompatibility = frameRateCompatibility,
126 .seamlessness = seamlessness};
127}
128
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100129} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800130
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700131using namespace ftl::flag_operators;
132
Yiwei Zhang5434a782018-12-05 18:06:32 -0800133using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000134using frontend::LayerSnapshot;
135using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800136using gui::GameMode;
137using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500138using gui::WindowInfo;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800139
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700140using PresentState = frametimeline::SurfaceFrame::PresentState;
141
Kean Mariotti4ba343c2023-04-19 13:31:02 +0000142Layer::Layer(const surfaceflinger::LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000143 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700144 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000145 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700146 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800147 mWindowType(static_cast<WindowInfo::Type>(
148 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000149 mLayerCreationFlags(args.flags),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000150 mBorderEnabled(false),
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000151 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000152 ALOGV("Creating Layer %s", getDebugName());
153
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700154 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700155 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
156 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
157 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700158 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
159 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700160 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700161 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700162 mDrawingState.z = 0;
163 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700164 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700165 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700166 mDrawingState.transform.set(0, 0);
167 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +0000168 mDrawingState.previousFrameNumber = 0;
Vishnu Nair63221212023-04-06 15:17:37 -0700169 mDrawingState.barrierFrameNumber = 0;
170 mDrawingState.producerId = 0;
171 mDrawingState.barrierProducerId = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700172 mDrawingState.bufferTransform = 0;
173 mDrawingState.transformToDisplayInverse = false;
Robert Carr6a160312021-05-17 12:08:20 -0700174 mDrawingState.acquireFence = sp<Fence>::make(-1);
175 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
Alec Mouri74c7ae12023-03-26 02:57:47 +0000176 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Robert Carr6a160312021-05-17 12:08:20 -0700177 mDrawingState.hdrMetadata.validTypes = 0;
178 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
179 mDrawingState.cornerRadius = 0.0f;
180 mDrawingState.backgroundBlurRadius = 0;
181 mDrawingState.api = -1;
182 mDrawingState.hasColorTransform = false;
183 mDrawingState.colorSpaceAgnostic = false;
184 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
185 mDrawingState.metadata = args.metadata;
186 mDrawingState.shadowRadius = 0.f;
187 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
188 mDrawingState.frameTimelineInfo = {};
189 mDrawingState.postTime = -1;
190 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000191 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700192 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700193 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000194 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Rachel Lee58cc90d2023-09-05 18:50:20 -0700195 mDrawingState.frameRateSelectionStrategy = FrameRateSelectionStrategy::Self;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700196
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700197 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
198 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700199 mDrawingState.color.r = -1.0_hf;
200 mDrawingState.color.g = -1.0_hf;
201 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700202 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700203
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500204 mFrameTracker.setDisplayRefreshPeriod(
205 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700206
Vishnu Naircb8be502022-10-12 19:03:23 +0000207 mOwnerUid = args.ownerUid;
208 mOwnerPid = args.ownerPid;
Tony Huangf3621102023-09-04 17:14:22 +0800209 mOwnerAppId = mOwnerUid % PER_USER_RANGE;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000210
211 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
212 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
213 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000214
215 mSnapshot->sequence = sequence;
216 mSnapshot->name = getDebugName();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000217 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000218 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800219}
220
221void Layer::onFirstRef() {
222 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700223}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700224
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700225Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000226 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
227 "Layer destructor called off the main thread.");
228
Patrick Williamsbb25f802022-08-30 23:02:34 +0000229 // The original layer and the clone layer share the same texture and buffer. Therefore, only
230 // one of the layers, in this case the original layer, needs to handle the deletion. The
231 // original layer and the clone should be removed at the same time so there shouldn't be any
232 // issue with the clone layer trying to use the texture.
233 if (mBufferInfo.mBuffer != nullptr) {
234 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
235 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800236 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000237 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000238 const int32_t layerId = getSequence();
239 mFlinger->mTimeStats->onDestroy(layerId);
240 mFlinger->mFrameTracer->onDestroy(layerId);
241
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000242 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700243 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700244
245 if (mDrawingState.sidebandStream != nullptr) {
246 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
247 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700248 if (mHadClonedChild) {
Vishnu Nair3be61902023-04-26 19:47:29 -0700249 auto& roots = mFlinger->mLayerMirrorRoots;
250 roots.erase(std::remove(roots.begin(), roots.end(), this), roots.end());
Robert Carr6a0382d2021-07-01 15:57:17 -0700251 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000252 if (hasTrustedPresentationListener()) {
253 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000254 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000255 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700256}
257
Mathias Agopian13127d82013-03-05 17:47:11 -0800258// ---------------------------------------------------------------------------
259// callbacks
260// ---------------------------------------------------------------------------
261
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700262void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700263 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700264 return;
265 }
Robert Carr2e102c92018-10-23 12:11:15 -0700266
Robert Carr6a160312021-05-17 12:08:20 -0700267 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700268 if (strongRelative == nullptr) {
269 setZOrderRelativeOf(nullptr);
270 return;
271 }
272
273 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700274 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700275 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800276 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700277 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700278}
279
280void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700281 if (!mRemovedFromDrawingState) {
282 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700283 mFlinger->mScheduler->deregisterLayer(this);
284 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000285 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000286
Ady Abrahamd11bade2022-08-01 16:18:03 -0700287 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700288}
Chia-I Wu38512252017-05-17 14:36:16 -0700289
chaviw68d4dab2020-06-08 15:07:32 -0700290sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000291 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700292 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700293 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700294 }
295 return parent->getRootLayer();
296}
297
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700298void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700299 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
300 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700301 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700302
Josh Gao194ff392022-09-08 16:19:29 -0700303 REQUIRE_MUTEX(mFlinger->mStateLock);
304 traverse(LayerVector::StateSet::Current,
305 [&](Layer* layer) REQUIRES(layer->mFlinger->mStateLock) {
306 layer->removeFromCurrentState();
307 layer->removeRelativeZ(layersInTree);
308 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700309}
310
chaviw61626f22018-11-15 16:26:27 -0800311void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700312 if (mRemovedFromDrawingState) {
313 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700314 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700315 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700316 }
chaviw61626f22018-11-15 16:26:27 -0800317
318 for (const auto& child : mCurrentChildren) {
319 child->addToCurrentState();
320 }
321}
322
Mathias Agopian13127d82013-03-05 17:47:11 -0800323// ---------------------------------------------------------------------------
324// set-up
325// ---------------------------------------------------------------------------
326
chaviw13fdc492017-06-27 12:40:18 -0700327bool Layer::getPremultipledAlpha() const {
328 return mPremultipliedAlpha;
329}
330
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700331sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800332 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700333 if (mGetHandleCalled) {
334 ALOGE("Get handle called twice" );
335 return nullptr;
336 }
337 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700338 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000339 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800340}
341
342// ---------------------------------------------------------------------------
343// h/w composer set-up
344// ---------------------------------------------------------------------------
345
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700346static Rect reduce(const Rect& win, const Region& exclude) {
347 if (CC_LIKELY(exclude.isEmpty())) {
348 return win;
349 }
350 if (exclude.isRect()) {
351 return win.reduce(exclude.getBounds());
352 }
353 return Region(win).subtract(exclude).getBounds();
354}
355
Dan Stoza80d61162017-12-20 15:57:52 -0800356static FloatRect reduce(const FloatRect& win, const Region& exclude) {
357 if (CC_LIKELY(exclude.isEmpty())) {
358 return win;
359 }
360 // Convert through Rect (by rounding) for lack of FloatRegion
361 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
362}
363
Vishnu Nair4351ad52019-02-11 14:13:02 -0800364Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800365 if (!reduceTransparentRegion) {
366 return Rect{mScreenBounds};
367 }
368
369 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800370 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800371 // Transform to screen space.
372 bounds = t.transform(bounds);
373 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700374}
375
Vishnu Nair4351ad52019-02-11 14:13:02 -0800376FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000377 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800378 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700379}
380
Vishnu Nairf0c28512019-02-08 12:40:28 -0800381FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
382 // Subtract the transparent region and snap to the bounds.
383 return reduce(mBounds, activeTransparentRegion);
384}
385
Chavi Weingarten076acac2023-01-19 17:20:43 +0000386// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000387void Layer::updateTrustedPresentationState(const DisplayDevice* display,
388 const frontend::LayerSnapshot* snapshot,
389 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000390 if (!hasTrustedPresentationListener()) {
391 return;
392 }
393 const bool lastState = mLastComputedTrustedPresentationState;
394 mLastComputedTrustedPresentationState = false;
395
396 if (!leaveState) {
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000397 const auto outputLayer = findOutputLayerForDisplay(display, snapshot->path);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000398 if (outputLayer != nullptr) {
399 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
400 Region coveredRegion =
401 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
402 mLastComputedTrustedPresentationState =
403 computeTrustedPresentationState(snapshot->geomLayerBounds,
404 snapshot->sourceBounds(), coveredRegion,
405 snapshot->transformedBounds,
406 snapshot->alpha,
407 snapshot->geomLayerTransform,
408 mTrustedPresentationThresholds);
409 } else {
410 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
411 "TrustedPresentationState",
412 getDebugName());
413 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000414 }
415 }
416 const bool newState = mLastComputedTrustedPresentationState;
417 if (lastState && !newState) {
418 // We were in the trusted presentation state, but now we left it,
419 // emit the callback if needed
420 if (mLastReportedTrustedPresentationState) {
421 mLastReportedTrustedPresentationState = false;
422 mTrustedPresentationListener.invoke(false);
423 }
424 // Reset the timer
425 mEnteredTrustedPresentationStateTime = -1;
426 } else if (!lastState && newState) {
427 // We were not in the trusted presentation state, but we entered it, begin the timer
428 // and make sure this gets called at least once more!
429 mEnteredTrustedPresentationStateTime = time_in_ms;
430 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
431 }
432
433 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
434 if (!mLastReportedTrustedPresentationState && newState &&
435 (time_in_ms - mEnteredTrustedPresentationStateTime >
436 mTrustedPresentationThresholds.stabilityRequirementMs)) {
437 mLastReportedTrustedPresentationState = true;
438 mTrustedPresentationListener.invoke(true);
439 }
440}
441
442/**
443 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
444 * of how the parameters and thresholds are interpreted. The general spirit is
445 * to produce an upper bound on the amount of the buffer which was presented.
446 */
447bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
448 const Region& coveredRegion,
449 const FloatRect& screenBounds, float alpha,
450 const ui::Transform& effectiveTransform,
451 const TrustedPresentationThresholds& thresholds) {
452 if (alpha < thresholds.minAlpha) {
453 return false;
454 }
455 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
456 return false;
457 }
458 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
459 return false;
460 }
461
462 const float sx = effectiveTransform.dsdx();
463 const float sy = effectiveTransform.dsdy();
464 float fractionRendered = std::min(sx * sy, 1.0f);
465
466 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
467 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
468 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
469
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000470 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
471 // Compute the size of all the rects since they may be disconnected.
472 float coveredSize = 0;
473 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
474 float size = rect->width() * rect->height();
475 coveredSize += size;
476 }
477
478 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000479
480 if (fractionRendered < thresholds.minFractionRendered) {
481 return false;
482 }
483
484 return true;
485}
486
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700487void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
488 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800489 const State& s(getDrawingState());
490
491 // Calculate effective layer transform
492 mEffectiveTransform = parentTransform * getActiveTransform(s);
493
Garfield Tan2c1782c2022-02-16 15:25:05 -0800494 if (CC_UNLIKELY(!isTransformValid())) {
495 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
496 getDebugName());
497 return;
498 }
499
Vishnu Nair4351ad52019-02-11 14:13:02 -0800500 // Transform parent bounds to layer space
501 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
502
Vishnu Nairc652ff82019-03-15 12:48:54 -0700503 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800504 mSourceBounds = computeSourceBounds(parentBounds);
505
506 // Calculate bounds by croping diplay frame with layer crop and parent bounds
507 FloatRect bounds = mSourceBounds;
508 const Rect layerCrop = getCrop(s);
509 if (!layerCrop.isEmpty()) {
510 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
511 }
512 bounds = bounds.intersect(parentBounds);
513
514 mBounds = bounds;
515 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700516
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700517 // Use the layer's own shadow radius if set. Otherwise get the radius from
518 // parent.
519 if (s.shadowRadius > 0.f) {
520 mEffectiveShadowRadius = s.shadowRadius;
521 } else {
522 mEffectiveShadowRadius = parentShadowRadius;
523 }
524
525 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
526 // don't pass it to its children.
527 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
528
Vishnu Nair4351ad52019-02-11 14:13:02 -0800529 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700530 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800531 }
Vishnu Nairba354102022-08-01 00:14:18 +0000532
533 if (mPotentialCursor) {
534 prepareCursorCompositionState();
535 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800536}
537
Vishnu Nair60356342018-11-13 13:00:45 -0800538Rect Layer::getCroppedBufferSize(const State& s) const {
539 Rect size = getBufferSize(s);
540 Rect crop = getCrop(s);
541 if (!crop.isEmpty() && size.isValid()) {
542 size.intersect(crop, &size);
543 } else if (!crop.isEmpty()) {
544 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700545 }
Vishnu Nair60356342018-11-13 13:00:45 -0800546 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800547}
548
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700549void Layer::setupRoundedCornersCropCoordinates(Rect win,
550 const FloatRect& roundedCornersCrop) const {
551 // Translate win by the rounded corners rect coordinates, to have all values in
552 // layer coordinate space.
553 win.left -= roundedCornersCrop.left;
554 win.right -= roundedCornersCrop.left;
555 win.top -= roundedCornersCrop.top;
556 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700557}
558
Lloyd Piquede196652020-01-22 17:29:58 -0800559void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800560 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800561 const auto alpha = static_cast<float>(getAlpha());
562 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700563 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800564
565 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
566 if (!opaque || alpha != 1.0f) {
567 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
568 : Hwc2::IComposerClient::BlendMode::COVERAGE;
569 }
570
Alec Mourif4af03e2023-02-11 00:25:24 +0000571 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000572 auto* snapshot = editLayerSnapshot();
573 snapshot->outputFilter = getOutputFilter();
574 snapshot->isVisible = isVisible();
575 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
Vishnu Naird9e4f462023-10-06 04:05:45 +0000576 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800577
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000578 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800579 contentDirty = false;
580
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000581 snapshot->geomLayerBounds = mBounds;
582 snapshot->geomLayerTransform = getTransform();
583 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
584 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000585 snapshot->localTransform = getActiveTransform(drawingState);
586 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000587 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
588 snapshot->alpha = alpha;
Vishnu Nairc6384702023-07-31 12:22:20 -0700589 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
590 snapshot->blurRegions = getBlurRegions();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000591 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800592}
593
Lloyd Piquede196652020-01-22 17:29:58 -0800594void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800595 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000596 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700597
Alec Mourif4af03e2023-02-11 00:25:24 +0000598 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000599 snapshot->geomBufferSize = getBufferSize(drawingState);
600 snapshot->geomContentCrop = getBufferCrop();
601 snapshot->geomCrop = getCrop(drawingState);
602 snapshot->geomBufferTransform = getBufferTransform();
603 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
604 snapshot->geomUsesSourceCrop = usesSourceCrop();
605 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800606
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000607 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800608 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
609 for (const auto& [key, mandatory] : supportedMetadata) {
610 const auto& genericLayerMetadataCompatibilityMap =
611 mFlinger->getGenericLayerMetadataKeyMap();
612 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
613 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
614 continue;
615 }
616 const uint32_t id = compatIter->second;
617
618 auto it = drawingState.metadata.mMap.find(id);
619 if (it == std::end(drawingState.metadata.mMap)) {
620 continue;
621 }
622
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000623 snapshot->metadata.emplace(key,
624 compositionengine::GenericLayerMetadataEntry{mandatory,
625 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800626 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800627}
David Sodmanba340492018-08-05 21:51:33 -0700628
Lloyd Piquede196652020-01-22 17:29:58 -0800629void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800630 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000631 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000632 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800633
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000634 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800635
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000636 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
637 snapshot->dataspace = getDataSpace();
638 snapshot->colorTransform = getColorTransform();
639 snapshot->colorTransformIsIdentity = !hasColorTransform();
640 snapshot->surfaceDamage = surfaceDamageRegion;
641 snapshot->hasProtectedContent = isProtected();
642 snapshot->dimmingEnabled = isDimmingEnabled();
Sally Qi963049b2023-03-23 14:06:21 -0700643 snapshot->currentHdrSdrRatio = getCurrentHdrSdrRatio();
644 snapshot->desiredHdrSdrRatio = getDesiredHdrSdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000645 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800646
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700647 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700648
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000649 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800650
651 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400652 // Rounded corners no longer force client composition, since we may use a
653 // hole punch so that the layer will appear to have rounded corners.
Alec Mouri994761f2023-08-04 21:50:55 +0000654 if (drawShadows() || snapshot->stretchEffect.hasEffect()) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000655 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800656 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700657 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairc6384702023-07-31 12:22:20 -0700658 snapshot->blurRegions = getBlurRegions();
659 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400660
661 // Layer framerate is used in caching decisions.
662 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
663 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000664 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000665
666 if (hasBufferOrSidebandStream()) {
667 preparePerFrameBufferCompositionState();
668 } else {
669 preparePerFrameEffectsCompositionState();
670 }
671}
672
673void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000674 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000675 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000676 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000677 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
678 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000679 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
680 return;
681 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000682 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000683 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800684 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
685 snapshot->compositionType =
686 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000687 } else {
688 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000689 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
690 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000691 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
692 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
693 }
694
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000695 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000696 snapshot->acquireFence = mBufferInfo.mFence;
697 snapshot->frameNumber = mBufferInfo.mFrameNumber;
698 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000699}
700
701void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000702 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000703 auto* snapshot = editLayerSnapshot();
704 snapshot->color = getColor();
705 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000706 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800707}
708
Lloyd Piquede196652020-01-22 17:29:58 -0800709void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800710 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000711 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000712 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800713
714 // Apply the layer's transform, followed by the display's global transform
715 // Here we're guaranteed that the layer's transform preserves rects
716 Rect win = getCroppedBufferSize(drawingState);
717 // Subtract the transparent region and snap to the bounds
718 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
719 Rect frame(getTransform().transform(bounds));
720
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000721 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800722}
723
Lloyd Piquea83776c2019-01-29 18:42:32 -0800724const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700725 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800726}
727
Mathias Agopian13127d82013-03-05 17:47:11 -0800728// ---------------------------------------------------------------------------
729// drawing...
730// ---------------------------------------------------------------------------
731
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500732aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
733 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700734 const auto outputLayer = findOutputLayerForDisplay(&display);
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000735 return getCompositionType(outputLayer);
736}
737
738aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
739 const compositionengine::OutputLayer* outputLayer) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -0800740 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500741 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800742 }
743 if (outputLayer->getState().hwc) {
744 return (*outputLayer->getState().hwc).hwcCompositionType;
745 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500746 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800747 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800748}
749
Mathias Agopian13127d82013-03-05 17:47:11 -0800750// ----------------------------------------------------------------------------
751// local state
752// ----------------------------------------------------------------------------
753
David Sodman41fdfc92017-11-06 16:09:56 -0800754bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800755 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700756 if (s.flags & layer_state_t::eLayerSecure) {
757 return true;
758 }
759
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000760 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700761 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700762}
763
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100764void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
765 std::vector<JankData>& jankData) {
766 if (mPendingJankClassifications.empty() ||
767 !mPendingJankClassifications.front()->getJankType()) {
768 return;
769 }
770
771 bool includeJankData = false;
772 for (const auto& handle : handles) {
773 for (const auto& cb : handle->callbackIds) {
774 if (cb.includeJankData) {
775 includeJankData = true;
776 break;
777 }
778 }
779
780 if (includeJankData) {
781 jankData.reserve(mPendingJankClassifications.size());
782 break;
783 }
784 }
785
786 while (!mPendingJankClassifications.empty() &&
787 mPendingJankClassifications.front()->getJankType()) {
788 if (includeJankData) {
789 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
790 mPendingJankClassifications.front();
Pascal Muetschardac7bcd92023-10-03 15:05:36 +0200791 jankData.emplace_back(JankData(surfaceFrame->getToken(),
792 surfaceFrame->getJankType().value(),
793 surfaceFrame->getRenderRate().getPeriodNsecs()));
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100794 }
795 mPendingJankClassifications.pop_front();
796 }
797}
798
Mathias Agopian13127d82013-03-05 17:47:11 -0800799// ----------------------------------------------------------------------------
800// transaction
801// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800802
Vishnu Naira156f482023-02-22 00:23:38 +0000803uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700804 ATRACE_CALL();
805
Robert Carr0758e5d2021-03-11 22:15:04 -0800806 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700807 mDrawingStateModified = mDrawingState.modified;
808 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700809
Alec Mourib416efd2018-09-06 21:01:59 +0000810 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700811
Robert Carr6a160312021-05-17 12:08:20 -0700812 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800813 // invalidate and recompute the visible regions if needed
814 flags |= Layer::eVisibleRegion;
815 }
816
Robert Carr6a160312021-05-17 12:08:20 -0700817 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800818 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000819 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800820 flags |= eVisibleRegion;
821 this->contentDirty = true;
822
823 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700824 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800825 }
826
Arthur Hung9ed43392022-05-27 06:31:57 +0000827 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
828 mFlinger->mUpdateInputInfo = true;
829 }
830
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700831 commitTransaction();
Robert Carra1257842020-01-31 13:48:28 -0800832
Mathias Agopian13127d82013-03-05 17:47:11 -0800833 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800834}
835
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700836void Layer::commitTransaction() {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000837 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
838 // bufferSurfaceFrameTX will be presented in latchBuffer.
839 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
840 if (surfaceFrame->getPresentState() != PresentState::Presented) {
841 // With applyPendingStates, we could end up having presented surfaceframes from previous
842 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800843 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000844 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
845 }
846 }
Robert Carr6a160312021-05-17 12:08:20 -0700847 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700848}
849
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700850uint32_t Layer::clearTransactionFlags(uint32_t mask) {
851 const auto flags = mTransactionFlags & mask;
852 mTransactionFlags &= ~mask;
853 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800854}
855
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700856void Layer::setTransactionFlags(uint32_t mask) {
857 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800858}
859
Robert Carr1f0a16a2016-10-24 16:27:39 -0700860bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
861 ssize_t idx = mCurrentChildren.indexOf(childLayer);
862 if (idx < 0) {
863 return false;
864 }
865 if (childLayer->setLayer(z)) {
866 mCurrentChildren.removeAt(idx);
867 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800868 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700869 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800870 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700871}
872
Robert Carr503c7042017-09-27 15:06:08 -0700873bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
874 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
875 ssize_t idx = mCurrentChildren.indexOf(childLayer);
876 if (idx < 0) {
877 return false;
878 }
879 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
880 mCurrentChildren.removeAt(idx);
881 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800882 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700883 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800884 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700885}
886
Robert Carrae060832016-11-28 10:51:00 -0800887bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700888 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
889 mDrawingState.sequence++;
890 mDrawingState.z = z;
891 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700892
Robert Carra70e91c2021-06-11 13:59:52 -0700893 mFlinger->mSomeChildrenChanged = true;
894
Robert Carrdb66e622017-04-10 16:55:57 -0700895 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700896 if (mDrawingState.zOrderRelativeOf != nullptr) {
897 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700898 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700899 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700900 }
chaviw606e5cf2019-03-01 10:12:10 -0800901 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700902 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800903 setTransactionFlags(eTransactionNeeded);
904 return true;
905}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700906
Robert Carrdb66e622017-04-10 16:55:57 -0700907void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700908 mDrawingState.zOrderRelatives.remove(relative);
909 mDrawingState.sequence++;
910 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700911 setTransactionFlags(eTransactionNeeded);
912}
913
914void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700915 mDrawingState.zOrderRelatives.add(relative);
916 mDrawingState.modified = true;
917 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700918 setTransactionFlags(eTransactionNeeded);
919}
920
chaviw606e5cf2019-03-01 10:12:10 -0800921void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700922 mDrawingState.zOrderRelativeOf = relativeOf;
923 mDrawingState.sequence++;
924 mDrawingState.modified = true;
925 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700926
chaviw606e5cf2019-03-01 10:12:10 -0800927 setTransactionFlags(eTransactionNeeded);
928}
929
Robert Carr503d2bd2017-12-04 15:49:47 -0800930bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000931 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700932 if (relative == nullptr) {
933 return false;
934 }
935
Robert Carr6a160312021-05-17 12:08:20 -0700936 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
937 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800938 return false;
939 }
940
Robert Carr88b85e12022-03-21 15:47:35 -0700941 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
942 (relative->mDrawingState.zOrderRelativeOf == this)) {
943 ALOGE("Detected relative layer loop between %s and %s",
944 mName.c_str(), relative->mName.c_str());
945 ALOGE("Ignoring new call to set relative layer");
946 return false;
947 }
948
Robert Carra70e91c2021-06-11 13:59:52 -0700949 mFlinger->mSomeChildrenChanged = true;
950
Robert Carr6a160312021-05-17 12:08:20 -0700951 mDrawingState.sequence++;
952 mDrawingState.modified = true;
953 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700954
Robert Carr6a160312021-05-17 12:08:20 -0700955 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700956 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700957 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700958 }
chaviw606e5cf2019-03-01 10:12:10 -0800959 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700960 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700961
962 setTransactionFlags(eTransactionNeeded);
963
964 return true;
965}
966
Winson Chunga30f7c92021-06-29 15:42:56 -0700967bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
968 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
969 mDrawingState.isTrustedOverlay = isTrustedOverlay;
970 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000971 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700972 setTransactionFlags(eTransactionNeeded);
973 return true;
974}
975
976bool Layer::isTrustedOverlay() const {
977 if (getDrawingState().isTrustedOverlay) {
978 return true;
979 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000980 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700981 return (p != nullptr) && p->isTrustedOverlay();
982}
983
Dan Stoza9e56aa02015-11-02 13:00:03 -0800984bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700985 if (mDrawingState.color.a == alpha) return false;
986 mDrawingState.sequence++;
987 mDrawingState.color.a = alpha;
988 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800989 setTransactionFlags(eTransactionNeeded);
990 return true;
991}
chaviw13fdc492017-06-27 12:40:18 -0700992
Valerie Haudd0b7572019-01-29 14:59:27 -0800993bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700994 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700995 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800996 }
Robert Carr6a160312021-05-17 12:08:20 -0700997 mDrawingState.sequence++;
998 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800999 setTransactionFlags(eTransactionNeeded);
1000
Robert Carr6a160312021-05-17 12:08:20 -07001001 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001002 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001003 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001004 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001005 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Kean Mariotti4ba343c2023-04-19 13:31:02 +00001006 surfaceflinger::LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
1007 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001008
Valerie Haudd0b7572019-01-29 14:59:27 -08001009 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001010 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001011 mFlinger->mLayersAdded = true;
1012 // set up SF to handle added color layer
1013 if (isRemovedFromCurrentState()) {
Josh Gao194ff392022-09-08 16:19:29 -07001014 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001015 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001016 }
1017 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001018 } else if (mDrawingState.bgColorLayer && alpha == 0) {
Josh Gao194ff392022-09-08 16:19:29 -07001019 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001020 mDrawingState.bgColorLayer->reparent(nullptr);
1021 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001022 return true;
1023 }
1024
Robert Carr6a160312021-05-17 12:08:20 -07001025 mDrawingState.bgColorLayer->setColor(color);
1026 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1027 mDrawingState.bgColorLayer->setAlpha(alpha);
1028 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001029
chaviw13fdc492017-06-27 12:40:18 -07001030 return true;
1031}
1032
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001033bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001034 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001035
Robert Carr6a160312021-05-17 12:08:20 -07001036 mDrawingState.sequence++;
1037 mDrawingState.cornerRadius = cornerRadius;
1038 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001039 setTransactionFlags(eTransactionNeeded);
1040 return true;
1041}
1042
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001043bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001044 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001045 // If we start or stop drawing blur then the layer's visibility state may change so increment
1046 // the magic sequence number.
1047 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1048 mDrawingState.sequence++;
1049 }
Robert Carr6a160312021-05-17 12:08:20 -07001050 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1051 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001052 setTransactionFlags(eTransactionNeeded);
1053 return true;
1054}
Marissa Wall61c58622018-07-18 10:12:20 -07001055
Mathias Agopian13127d82013-03-05 17:47:11 -08001056bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001057 mDrawingState.sequence++;
1058 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001059 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001060 setTransactionFlags(eTransactionNeeded);
1061 return true;
1062}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001063
Lucas Dupinc3800b82020-10-02 16:24:48 -07001064bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001065 // If we start or stop drawing blur then the layer's visibility state may change so increment
1066 // the magic sequence number.
1067 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1068 mDrawingState.sequence++;
1069 }
Robert Carr6a160312021-05-17 12:08:20 -07001070 mDrawingState.blurRegions = blurRegions;
1071 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001072 setTransactionFlags(eTransactionNeeded);
1073 return true;
1074}
1075
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001076bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001077 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1078 if (mDrawingState.flags == newFlags) return false;
1079 mDrawingState.sequence++;
1080 mDrawingState.flags = newFlags;
1081 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001082 setTransactionFlags(eTransactionNeeded);
1083 return true;
1084}
Robert Carr99e27f02016-06-16 15:18:02 -07001085
chaviw25714502021-02-11 10:01:08 -08001086bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001087 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001088 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001089 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001090
Robert Carr6a160312021-05-17 12:08:20 -07001091 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001092 setTransactionFlags(eTransactionNeeded);
1093 return true;
1094}
Robert Carr8d5227b2017-03-16 15:41:03 -07001095
Evan Roskyef876c92019-01-25 17:46:06 -08001096bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001097 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1098 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001099 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001100 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001101}
1102
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001103bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001104 if (mDrawingState.layerStack == layerStack) return false;
1105 mDrawingState.sequence++;
1106 mDrawingState.layerStack = layerStack;
1107 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001108 setTransactionFlags(eTransactionNeeded);
1109 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001110}
1111
Peiyong Linc502cb72019-03-01 15:00:23 -08001112bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001113 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001114 return false;
1115 }
Robert Carr6a160312021-05-17 12:08:20 -07001116 mDrawingState.sequence++;
1117 mDrawingState.colorSpaceAgnostic = agnostic;
1118 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001119 setTransactionFlags(eTransactionNeeded);
1120 return true;
1121}
1122
Sally Qi81d95e62022-03-21 19:41:33 -07001123bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1124 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1125
1126 mDrawingState.sequence++;
1127 mDrawingState.dimmingEnabled = dimmingEnabled;
1128 mDrawingState.modified = true;
1129 setTransactionFlags(eTransactionNeeded);
1130 return true;
1131}
1132
Ana Krulecc84d09b2019-11-02 23:10:29 +01001133bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001134 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1135 mDrawingState.frameRateSelectionPriority = priority;
1136 mDrawingState.sequence++;
1137 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001138 setTransactionFlags(eTransactionNeeded);
1139 return true;
1140}
1141
1142int32_t Layer::getFrameRateSelectionPriority() const {
1143 // Check if layer has priority set.
1144 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1145 return mDrawingState.frameRateSelectionPriority;
1146 }
1147 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001148 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001149 if (parent != nullptr) {
1150 return parent->getFrameRateSelectionPriority();
1151 }
1152
1153 return Layer::PRIORITY_UNSET;
1154}
1155
Andy Labrada096227e2022-06-15 16:58:11 +00001156bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1157 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1158 mDrawingState.defaultFrameRateCompatibility = compatibility;
1159 mDrawingState.modified = true;
Vishnu Nair80e8cfe2023-09-29 17:03:45 -07001160 mFlinger->mScheduler->setDefaultFrameRateCompatibility(sequence, compatibility);
Andy Labrada096227e2022-06-15 16:58:11 +00001161 setTransactionFlags(eTransactionNeeded);
1162 return true;
1163}
1164
Vishnu Nair3fbe3262023-09-29 17:07:00 -07001165scheduler::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
Andy Labrada096227e2022-06-15 16:58:11 +00001166 return mDrawingState.defaultFrameRateCompatibility;
1167}
1168
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001169bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1170 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1171};
1172
Vishnu Nair73908d12022-10-24 21:46:42 -07001173ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1174 bool useDrawing = state == LayerVector::StateSet::Drawing;
1175 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1176 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001177 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001178 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001179 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001180}
1181
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001182bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001183 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001184 return false;
1185 }
1186
Robert Carr6a160312021-05-17 12:08:20 -07001187 mDrawingState.sequence++;
1188 mDrawingState.shadowRadius = shadowRadius;
1189 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001190 setTransactionFlags(eTransactionNeeded);
1191 return true;
1192}
1193
Vishnu Nair6213bd92020-05-08 17:42:25 -07001194bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001195 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001196 return false;
1197 }
1198
Robert Carr6a160312021-05-17 12:08:20 -07001199 mDrawingState.sequence++;
1200 mDrawingState.fixedTransformHint = fixedTransformHint;
1201 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001202 setTransactionFlags(eTransactionNeeded);
1203 return true;
1204}
1205
John Reckcdb4ed72021-02-04 13:39:33 -05001206bool Layer::setStretchEffect(const StretchEffect& effect) {
1207 StretchEffect temp = effect;
1208 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001209 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001210 return false;
1211 }
Robert Carr6a160312021-05-17 12:08:20 -07001212 mDrawingState.sequence++;
1213 mDrawingState.stretchEffect = temp;
1214 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001215 setTransactionFlags(eTransactionNeeded);
1216 return true;
1217}
1218
John Reckc00c6692021-02-16 11:37:33 -05001219StretchEffect Layer::getStretchEffect() const {
1220 if (mDrawingState.stretchEffect.hasEffect()) {
1221 return mDrawingState.stretchEffect;
1222 }
1223
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001224 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001225 if (parent != nullptr) {
1226 auto effect = parent->getStretchEffect();
1227 if (effect.hasEffect()) {
1228 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1229 return effect;
1230 }
1231 }
1232 return StretchEffect{};
1233}
1234
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001235bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1236 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001237 return false;
1238 }
1239 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001240 mBorderWidth = width;
1241 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001242 return true;
1243}
1244
1245bool Layer::isBorderEnabled() {
1246 return mBorderEnabled;
1247}
1248
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001249float Layer::getBorderWidth() {
1250 return mBorderWidth;
1251}
1252
1253const half4& Layer::getBorderColor() {
1254 return mBorderColor;
1255}
1256
Rachel Lee0faad6c2023-09-08 13:34:34 -07001257bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool overrideChildren,
1258 bool* transactionNeeded) {
1259 // Gets the frame rate to propagate to children.
Ady Abrahama850c182021-08-04 13:04:37 -07001260 const auto frameRate = [&] {
Rachel Lee0faad6c2023-09-08 13:34:34 -07001261 if (overrideChildren && parentFrameRate.isValid()) {
1262 return parentFrameRate;
1263 }
1264
Rachel Leece6e0042023-06-27 11:22:54 -07001265 if (mDrawingState.frameRate.isValid()) {
Ady Abrahama850c182021-08-04 13:04:37 -07001266 return mDrawingState.frameRate;
1267 }
1268
1269 return parentFrameRate;
1270 }();
1271
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001272 auto now = systemTime();
1273 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate, now);
Ady Abrahama850c182021-08-04 13:04:37 -07001274
1275 // The frame rate is propagated to the children
1276 bool childrenHaveFrameRate = false;
1277 for (const sp<Layer>& child : mCurrentChildren) {
1278 childrenHaveFrameRate |=
Rachel Lee0faad6c2023-09-08 13:34:34 -07001279 child->propagateFrameRateForLayerTree(frameRate,
1280 overrideChildren ||
1281 shouldOverrideChildrenFrameRate(),
1282 transactionNeeded);
Ady Abrahama850c182021-08-04 13:04:37 -07001283 }
1284
Rachel Leece6e0042023-06-27 11:22:54 -07001285 // If we don't have a valid frame rate specification, but the children do, we set this
Ady Abrahama850c182021-08-04 13:04:37 -07001286 // layer as NoVote to allow the children to control the refresh rate
Rachel Leece6e0042023-06-27 11:22:54 -07001287 if (!frameRate.isValid() && childrenHaveFrameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001288 *transactionNeeded |=
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001289 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote),
1290 now);
Ady Abrahama850c182021-08-04 13:04:37 -07001291 }
1292
Rachel Leece6e0042023-06-27 11:22:54 -07001293 // We return whether this layer or its children has a vote. We ignore ExactOrMultiple votes for
Ady Abrahama850c182021-08-04 13:04:37 -07001294 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001295 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001296 const auto layerVotedWithDefaultCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001297 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Default;
1298 const auto layerVotedWithNoVote = frameRate.vote.type == FrameRateCompatibility::NoVote;
1299 const auto layerVotedWithCategory = frameRate.category != FrameRateCategory::Default;
Ady Abrahama850c182021-08-04 13:04:37 -07001300 const auto layerVotedWithExactCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001301 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Exact;
1302 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote || layerVotedWithCategory ||
Ady Abrahama850c182021-08-04 13:04:37 -07001303 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1304}
1305
Ady Abraham60e42ea2020-03-09 19:17:31 -07001306void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001307 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001308 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001309 while (auto parent = layer->getParent()) {
1310 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001311 }
Ady Abrahama850c182021-08-04 13:04:37 -07001312 return layer;
1313 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001314
Ady Abraham60e42ea2020-03-09 19:17:31 -07001315 bool transactionNeeded = false;
Rachel Lee0faad6c2023-09-08 13:34:34 -07001316 root->propagateFrameRateForLayerTree({}, false, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001317
Ady Abrahama850c182021-08-04 13:04:37 -07001318 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001319 if (transactionNeeded) {
1320 mFlinger->setTransactionFlags(eTraversalNeeded);
1321 }
1322}
1323
Rachel Leece6e0042023-06-27 11:22:54 -07001324bool Layer::setFrameRate(FrameRate::FrameRateVote frameRateVote) {
1325 if (mDrawingState.frameRate.vote == frameRateVote) {
Steven Thomas3172e202020-01-06 19:25:30 -08001326 return false;
1327 }
1328
Robert Carr6a160312021-05-17 12:08:20 -07001329 mDrawingState.sequence++;
Rachel Leece6e0042023-06-27 11:22:54 -07001330 mDrawingState.frameRate.vote = frameRateVote;
1331 mDrawingState.modified = true;
1332
1333 updateTreeHasFrameRateVote();
1334
1335 setTransactionFlags(eTransactionNeeded);
1336 return true;
1337}
1338
Rachel Lee67afbea2023-09-28 15:35:07 -07001339bool Layer::setFrameRateCategory(FrameRateCategory category, bool smoothSwitchOnly) {
1340 if (mDrawingState.frameRate.category == category &&
1341 mDrawingState.frameRate.categorySmoothSwitchOnly == smoothSwitchOnly) {
Rachel Leece6e0042023-06-27 11:22:54 -07001342 return false;
1343 }
1344
1345 mDrawingState.sequence++;
1346 mDrawingState.frameRate.category = category;
Rachel Lee67afbea2023-09-28 15:35:07 -07001347 mDrawingState.frameRate.categorySmoothSwitchOnly = smoothSwitchOnly;
Robert Carr6a160312021-05-17 12:08:20 -07001348 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001349
1350 updateTreeHasFrameRateVote();
1351
Steven Thomas3172e202020-01-06 19:25:30 -08001352 setTransactionFlags(eTransactionNeeded);
1353 return true;
1354}
1355
Rachel Lee58cc90d2023-09-05 18:50:20 -07001356bool Layer::setFrameRateSelectionStrategy(FrameRateSelectionStrategy strategy) {
1357 if (mDrawingState.frameRateSelectionStrategy == strategy) return false;
1358 mDrawingState.frameRateSelectionStrategy = strategy;
1359 mDrawingState.sequence++;
1360 mDrawingState.modified = true;
Rachel Leed7479502023-09-25 17:02:35 -07001361
1362 updateTreeHasFrameRateVote();
Rachel Lee58cc90d2023-09-05 18:50:20 -07001363 setTransactionFlags(eTransactionNeeded);
1364 return true;
1365}
1366
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001367void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1368 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001369 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001370
1371 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1372 // there are two transactions with the same token, the first one without a buffer and the
1373 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1374 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001375 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1376 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001377 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001378 mDrawingState.bufferSurfaceFrameTX = it->second;
1379 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1380 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1381 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001382 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001383 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001384 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1385 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001386
1387 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001388}
1389
1390void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1391 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001392 mDrawingState.frameTimelineInfo = info;
1393 mDrawingState.postTime = postTime;
1394 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001395 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001396
Robert Carr6a160312021-05-17 12:08:20 -07001397 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001398 bufferSurfaceFrameTX != nullptr) {
1399 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1400 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1401 // being used for BufferSurfaceFrame, don't create a new one.
1402 return;
1403 }
1404 }
1405 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1406 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1407 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001408 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1409 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001410 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001411 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001412 } else {
1413 if (it->second->getPresentState() == PresentState::Presented) {
1414 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1415 // have been from previous vsync.
1416 it->second = createSurfaceFrameForTransaction(info, postTime);
1417 }
1418 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001419
1420 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001421}
1422
1423void Layer::addSurfaceFrameDroppedForBuffer(
Ady Abraham5a3e3562023-06-07 10:32:08 -07001424 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t dropTime) {
1425 surfaceFrame->setDropTime(dropTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001426 surfaceFrame->setPresentState(PresentState::Dropped);
1427 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1428}
1429
1430void Layer::addSurfaceFramePresentedForBuffer(
1431 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1432 nsecs_t currentLatchTime) {
1433 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1434 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1435 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001436 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001437}
1438
1439std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1440 const FrameTimelineInfo& info, nsecs_t postTime) {
1441 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001442 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1443 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001444 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001445 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001446 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001447 // For Transactions, the post time is considered to be both queue and acquire fence time.
1448 surfaceFrame->setActualQueueTime(postTime);
1449 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001450 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1451 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001452 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001453 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001454 onSurfaceFrameCreated(surfaceFrame);
1455 return surfaceFrame;
1456}
1457
1458std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1459 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1460 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001461 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001462 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001463 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001464 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001465 // For buffers, acquire fence time will set during latch.
1466 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001467 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1468 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001469 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001470 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001471 onSurfaceFrameCreated(surfaceFrame);
1472 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001473}
1474
Ady Abraham5a3e3562023-06-07 10:32:08 -07001475void Layer::setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
1476 std::string debugName) {
1477 if (info.skippedFrameVsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
1478 return;
1479 }
1480
1481 FrameTimelineInfo skippedFrameTimelineInfo = info;
1482 skippedFrameTimelineInfo.vsyncId = info.skippedFrameVsyncId;
1483
1484 auto surfaceFrame =
1485 mFlinger->mFrameTimeline->createSurfaceFrameForToken(skippedFrameTimelineInfo,
1486 mOwnerPid, mOwnerUid,
1487 getSequence(), mName, debugName,
1488 /*isBuffer*/ false, getGameMode());
1489 surfaceFrame->setActualStartTime(skippedFrameTimelineInfo.skippedFrameStartTimeNanos);
1490 // For Transactions, the post time is considered to be both queue and acquire fence time.
1491 surfaceFrame->setActualQueueTime(postTime);
1492 surfaceFrame->setAcquireFenceTime(postTime);
1493 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1494 if (fps) {
1495 surfaceFrame->setRenderRate(*fps);
1496 }
1497 onSurfaceFrameCreated(surfaceFrame);
1498 addSurfaceFrameDroppedForBuffer(surfaceFrame, postTime);
1499}
1500
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001501bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate, nsecs_t now) {
Ady Abrahama850c182021-08-04 13:04:37 -07001502 if (mDrawingState.frameRateForLayerTree == frameRate) {
1503 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001504 }
1505
Ady Abrahama850c182021-08-04 13:04:37 -07001506 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001507
Ady Abrahama850c182021-08-04 13:04:37 -07001508 // TODO(b/195668952): we probably don't need to dirty visible regions here
1509 // or even store frameRateForLayerTree in mDrawingState
1510 mDrawingState.sequence++;
1511 mDrawingState.modified = true;
1512 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001513
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001514 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001515 ->recordLayerHistory(sequence, getLayerProps(), now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001516 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1517 return true;
1518}
Ady Abrahama850c182021-08-04 13:04:37 -07001519
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001520bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps,
1521 nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001522 if (mDrawingState.frameRateForLayerTree == frameRate) {
1523 return false;
1524 }
1525
1526 mDrawingState.frameRateForLayerTree = frameRate;
1527 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001528 ->recordLayerHistory(sequence, layerProps, now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001529 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001530 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001531}
1532
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001533Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1534 return getDrawingState().frameRateForLayerTree;
1535}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001536
Robert Carr1f0a16a2016-10-24 16:27:39 -07001537bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001538 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001539 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001540 if (parent != nullptr && parent->isHiddenByPolicy()) {
1541 return true;
1542 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001543 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1544 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1545 if (zOrderRelativeOf != nullptr) {
1546 if (zOrderRelativeOf->isHiddenByPolicy()) {
1547 return true;
1548 }
1549 }
1550 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001551 if (CC_UNLIKELY(!isTransformValid())) {
1552 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1553 return true;
1554 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001555 return s.flags & layer_state_t::eLayerHidden;
1556}
1557
David Sodman41fdfc92017-11-06 16:09:56 -08001558uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001559 // TODO: should we do something special if mSecure is set?
1560 if (mProtectedByApp) {
1561 // need a hardware-protected path to external video sink
1562 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001563 }
Riley Andrews03414a12014-07-01 14:22:59 -07001564 if (mPotentialCursor) {
1565 usage |= GraphicBuffer::USAGE_CURSOR;
1566 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001567 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001568 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001569}
1570
Vishnu Nair71fcf912022-10-18 09:14:20 -07001571void Layer::skipReportingTransformHint() {
1572 mSkipReportingTransformHint = true;
1573}
1574
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001575void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1576 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1577 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001578 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001579
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001580 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001581}
1582
Mathias Agopian13127d82013-03-05 17:47:11 -08001583// ----------------------------------------------------------------------------
1584// debugging
1585// ----------------------------------------------------------------------------
1586
Marissa Wall61c58622018-07-18 10:12:20 -07001587// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001588gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001589 using namespace std::string_literals;
1590
Huihong Luo05539a12022-02-23 10:29:40 -08001591 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001592 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001593 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001594 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001595 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001596 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001597
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001598 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001599 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001600 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001601 info.mX = ds.transform.tx();
1602 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001603 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001604 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001605 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001606 info.mFlags = ds.flags;
1607 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001608 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001609 info.mMatrix[0][0] = ds.transform[0][0];
1610 info.mMatrix[0][1] = ds.transform[0][1];
1611 info.mMatrix[1][0] = ds.transform[1][0];
1612 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001613 {
chaviwd62d3062019-09-04 14:48:02 -07001614 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001615 if (buffer != 0) {
1616 info.mActiveBufferWidth = buffer->getWidth();
1617 info.mActiveBufferHeight = buffer->getHeight();
1618 info.mActiveBufferStride = buffer->getStride();
1619 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001620 } else {
1621 info.mActiveBufferWidth = 0;
1622 info.mActiveBufferHeight = 0;
1623 info.mActiveBufferStride = 0;
1624 info.mActiveBufferFormat = 0;
1625 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001626 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001627 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001628 info.mIsOpaque = isOpaque(ds);
1629 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001630 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001631 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001632}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001633
Yiwei Zhang5434a782018-12-05 18:06:32 -08001634void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001635 result.append(kDumpTableRowLength, '-');
1636 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001637 result.append(" Layer name\n");
1638 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001639 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001640 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001641 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001642 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001643 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001644 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1645 result.append(kDumpTableRowLength, '-');
1646 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001647}
1648
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001649void Layer::miniDumpLegacy(std::string& result, const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001650 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001651 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001652 return;
1653 }
1654
Yiwei Zhang5434a782018-12-05 18:06:32 -08001655 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001656 if (mName.length() > 77) {
1657 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001658 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001659 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001660 shortened.append(mName, mName.length() - 36);
1661 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001662 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001663 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001664 }
1665
Yiwei Zhang5434a782018-12-05 18:06:32 -08001666 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001667
Alec Mourib416efd2018-09-06 21:01:59 +00001668 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001669 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001670
Chia-I Wu1e043612018-03-01 09:45:09 -08001671 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001672 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001673 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001674 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001675 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001676 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001677 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001678 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1679 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001680 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001681 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001682 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001683 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001684 const auto frameRate = getFrameRateForLayerTree();
Rachel Leece6e0042023-06-27 11:22:54 -07001685 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
1686 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.vote.rate).c_str(),
1687 ftl::enum_string(frameRate.vote.type).c_str(),
1688 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001689 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001690 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001691 }
Dan Stozae22aec72016-08-01 13:20:59 -07001692
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001693 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1694 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1695
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001696 result.append(kDumpTableRowLength, '-');
1697 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001698}
Dan Stozae22aec72016-08-01 13:20:59 -07001699
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001700void Layer::miniDump(std::string& result, const frontend::LayerSnapshot& snapshot,
1701 const DisplayDevice& display) const {
1702 const auto outputLayer = findOutputLayerForDisplay(&display, snapshot.path);
1703 if (!outputLayer) {
1704 return;
1705 }
1706
1707 StringAppendF(&result, " %s\n", snapshot.debugName.c_str());
1708 StringAppendF(&result, " %10zu | ", snapshot.globalZ);
1709 StringAppendF(&result, " %10d | ",
1710 snapshot.layerMetadata.getInt32(gui::METADATA_WINDOW_TYPE, 0));
1711 StringAppendF(&result, "%10s | ", toString(getCompositionType(outputLayer)).c_str());
1712 const auto& outputLayerState = outputLayer->getState();
1713 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1714 const Rect& frame = outputLayerState.displayFrame;
1715 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1716 const FloatRect& crop = outputLayerState.sourceCrop;
1717 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
1718 crop.bottom);
1719 const auto frameRate = snapshot.frameRate;
Rachel Leece6e0042023-06-27 11:22:54 -07001720 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
1721 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.vote.rate).c_str(),
1722 ftl::enum_string(frameRate.vote.type).c_str(),
1723 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001724 } else {
1725 result.append(41, ' ');
1726 }
1727
1728 const auto focused = isLayerFocusedBasedOnPriority(snapshot.frameRateSelectionPriority);
1729 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1730
1731 result.append(kDumpTableRowLength, '-');
1732 result.append("\n");
1733}
1734
Yiwei Zhang5434a782018-12-05 18:06:32 -08001735void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001736 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001737}
1738
Svetoslavd85084b2014-03-20 10:28:31 -07001739void Layer::clearFrameStats() {
1740 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001741}
1742
Jamie Gennis6547ff42013-07-16 20:12:42 -07001743void Layer::logFrameStats() {
1744 mFrameTracker.logAndResetStats(mName);
1745}
1746
Svetoslavd85084b2014-03-20 10:28:31 -07001747void Layer::getFrameStats(FrameStats* outStats) const {
1748 mFrameTracker.getStats(outStats);
1749}
1750
Vishnu Nair76554eb2022-12-09 03:38:36 +00001751void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1752 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
Vishnu Nair3be61902023-04-26 19:47:29 -07001753 StringAppendF(&result, "Layer %s%s pid:%d uid:%d%s\n", getName().c_str(), hasBuffer.c_str(),
1754 mOwnerPid, mOwnerUid, isHandleAlive() ? " handleAlive" : "");
Vishnu Nair0f085c62019-08-30 08:49:12 -07001755}
1756
Brian Anderson5ea5e592016-12-01 16:54:33 -08001757void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001758 const int32_t layerId = getSequence();
1759 mFlinger->mTimeStats->onDestroy(layerId);
1760 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001761}
1762
Vishnu Nair787aa782023-03-17 13:46:46 -07001763size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001764 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001765 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001766 count += 1 + child->getChildrenCount();
1767 }
1768 return count;
1769}
1770
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001771void Layer::setGameModeForTree(GameMode gameMode) {
1772 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001773 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1774 gameMode =
1775 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001776 }
1777 setGameMode(gameMode);
1778 for (const sp<Layer>& child : mCurrentChildren) {
1779 child->setGameModeForTree(gameMode);
1780 }
1781}
1782
Robert Carr1f0a16a2016-10-24 16:27:39 -07001783void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001784 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001785 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001786
Robert Carr1f0a16a2016-10-24 16:27:39 -07001787 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001788 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001789 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001790 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001791}
1792
1793ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001794 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001795 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001796
Robert Carr1323c952019-01-28 18:13:27 -08001797 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001798 const auto removeResult = mCurrentChildren.remove(layer);
1799
1800 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001801 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001802 layer->updateTreeHasFrameRateVote();
1803
1804 return removeResult;
1805}
1806
Robert Carr15eae092018-03-23 13:43:53 -07001807void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001808 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001809 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001810 const float parentShadowRadius =
1811 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001812 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001813 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001814 }
1815}
1816
chaviwf1961f72017-09-18 16:41:07 -07001817bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001818 sp<Layer> newParent;
1819 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001820 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001821 if (newParent == nullptr) {
1822 ALOGE("Unable to promote Layer handle");
1823 return false;
1824 }
1825 if (newParent == this) {
1826 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1827 return false;
1828 }
1829 }
1830
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001831 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001832 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001833 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001834 }
1835
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001836 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001837 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001838 if (!newParent->isRemovedFromCurrentState()) {
1839 addToCurrentState();
1840 } else {
1841 onRemovedFromCurrentState();
1842 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001843 } else {
1844 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001845 }
1846
chaviw06178942017-07-27 10:25:59 -07001847 return true;
1848}
1849
Peiyong Lind3788632018-09-18 16:01:31 -07001850bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001851 static const mat4 identityMatrix = mat4();
1852
Robert Carr6a160312021-05-17 12:08:20 -07001853 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001854 return false;
1855 }
Robert Carr6a160312021-05-17 12:08:20 -07001856 ++mDrawingState.sequence;
1857 mDrawingState.colorTransform = matrix;
1858 mDrawingState.hasColorTransform = matrix != identityMatrix;
1859 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001860 setTransactionFlags(eTransactionNeeded);
1861 return true;
1862}
1863
chaviwf66724d2018-11-28 16:35:21 -08001864mat4 Layer::getColorTransform() const {
1865 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001866 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001867 colorTransform = parent->getColorTransform() * colorTransform;
1868 }
1869 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001870}
1871
1872bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001873 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001874 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001875 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1876 }
1877 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001878}
1879
Chia-I Wu11481472018-05-04 10:43:19 -07001880bool Layer::isLegacyDataSpace() const {
1881 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001882 return !(getDataSpace() &
1883 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1884 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001885}
1886
Robert Carr1f0a16a2016-10-24 16:27:39 -07001887void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001888 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001889}
1890
Robert Carr6a160312021-05-17 12:08:20 -07001891int32_t Layer::getZ(LayerVector::StateSet) const {
1892 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001893}
1894
Robert Carr1c5481e2019-07-01 14:42:27 -07001895bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001896 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001897 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001898 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001899}
1900
David Sodman41fdfc92017-11-06 16:09:56 -08001901__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001902 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001903 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1904 "makeTraversalList received invalid stateSet");
1905 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1906 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001907 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001908
Robert Carr29abff82017-12-04 13:51:20 -08001909 if (state.zOrderRelatives.size() == 0) {
1910 *outSkipRelativeZUsers = true;
1911 return children;
1912 }
1913
chaviwfd462612018-05-31 16:11:27 -07001914 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001915 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001916 sp<Layer> strongRelative = weakRelative.promote();
1917 if (strongRelative != nullptr) {
1918 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001919 }
1920 }
1921
Dan Stoza412903f2017-04-27 13:42:17 -07001922 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001923 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001924 continue;
1925 }
Robert Carrdb66e622017-04-10 16:55:57 -07001926 traverse.add(child);
1927 }
1928
1929 return traverse;
1930}
1931
Robert Carr1f0a16a2016-10-24 16:27:39 -07001932/**
Robert Carrdb66e622017-04-10 16:55:57 -07001933 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001934 */
Dan Stoza412903f2017-04-27 13:42:17 -07001935void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001936 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1937 // produce a new list for traversing, including our relatives, and not including our children
1938 // who are relatives of another surface. In the case that there are no relative Z,
1939 // makeTraversalList returns our children directly to avoid significant overhead.
1940 // However in this case we need to take the responsibility for filtering children which
1941 // are relatives of another surface here.
1942 bool skipRelativeZUsers = false;
1943 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001944
Robert Carr1f0a16a2016-10-24 16:27:39 -07001945 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001946 for (; i < list.size(); i++) {
1947 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001948 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1949 continue;
1950 }
1951
chaviw301b1d82019-11-06 13:15:09 -08001952 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001953 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001954 }
Dan Stoza412903f2017-04-27 13:42:17 -07001955 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001956 }
Robert Carr29abff82017-12-04 13:51:20 -08001957
Dan Stoza412903f2017-04-27 13:42:17 -07001958 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001959 for (; i < list.size(); i++) {
1960 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001961
Robert Carr29abff82017-12-04 13:51:20 -08001962 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1963 continue;
1964 }
Dan Stoza412903f2017-04-27 13:42:17 -07001965 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001966 }
1967}
1968
1969/**
Robert Carrdb66e622017-04-10 16:55:57 -07001970 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001971 */
Dan Stoza412903f2017-04-27 13:42:17 -07001972void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1973 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001974 // See traverseInZOrder for documentation.
1975 bool skipRelativeZUsers = false;
1976 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001977
Robert Carr1f0a16a2016-10-24 16:27:39 -07001978 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001979 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001980 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001981
1982 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1983 continue;
1984 }
1985
chaviw301b1d82019-11-06 13:15:09 -08001986 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001987 break;
1988 }
Dan Stoza412903f2017-04-27 13:42:17 -07001989 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001990 }
Dan Stoza412903f2017-04-27 13:42:17 -07001991 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001992 for (; 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
Dan Stoza412903f2017-04-27 13:42:17 -07001999 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002000 }
2001}
2002
Edgar Arriaga844fa672020-01-16 14:21:42 -08002003void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
2004 visitor(this);
2005 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07002006 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002007 for (const sp<Layer>& child : children) {
2008 child->traverse(state, visitor);
2009 }
2010}
2011
Vishnu Nair787aa782023-03-17 13:46:46 -07002012void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
2013 for (const sp<Layer>& child : mDrawingChildren) {
2014 visitor(child.get());
2015 }
2016}
2017
chaviw4b129c22018-04-09 16:19:43 -07002018LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
2019 const std::vector<Layer*>& layersInTree) {
2020 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2021 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07002022 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2023 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002024 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002025
chaviwfd462612018-05-31 16:11:27 -07002026 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07002027 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2028 sp<Layer> strongRelative = weakRelative.promote();
2029 // Only add relative layers that are also descendents of the top most parent of the tree.
2030 // If a relative layer is not a descendent, then it should be ignored.
2031 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
2032 traverse.add(strongRelative);
2033 }
2034 }
2035
2036 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07002037 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002038 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
2039 // descendent of the top most parent of the tree. If it's not a descendent, then just add
2040 // the child here since it won't be added later as a relative.
2041 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
2042 childState.zOrderRelativeOf.promote().get())) {
2043 continue;
2044 }
2045 traverse.add(child);
2046 }
2047
2048 return traverse;
2049}
2050
2051void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
2052 LayerVector::StateSet stateSet,
2053 const LayerVector::Visitor& visitor) {
2054 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07002055
2056 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07002057 for (; i < list.size(); i++) {
2058 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08002059 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07002060 break;
2061 }
chaviw4b129c22018-04-09 16:19:43 -07002062 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002063 }
chaviw4b129c22018-04-09 16:19:43 -07002064
chaviwa76b2712017-09-20 12:02:26 -07002065 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07002066 for (; i < list.size(); i++) {
2067 const auto& relative = list[i];
2068 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002069 }
2070}
2071
chaviw4b129c22018-04-09 16:19:43 -07002072std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2073 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2074 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2075
2076 std::vector<Layer*> layersInTree = {this};
2077 for (size_t i = 0; i < children.size(); i++) {
2078 const auto& child = children[i];
2079 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2080 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2081 }
2082
2083 return layersInTree;
2084}
2085
2086void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2087 const LayerVector::Visitor& visitor) {
2088 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2089 std::sort(layersInTree.begin(), layersInTree.end());
2090 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2091}
2092
Peiyong Linefefaac2018-08-17 12:27:51 -07002093ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08002094 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002095}
2096
Garfield Tan2c1782c2022-02-16 15:25:05 -08002097bool Layer::isTransformValid() const {
2098 float transformDet = getTransform().det();
2099 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2100}
2101
chaviw13fdc492017-06-27 12:40:18 -07002102half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002103 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002104
chaviw13fdc492017-06-27 12:40:18 -07002105 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2106 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002107}
Robert Carr6452f122017-03-21 10:41:29 -07002108
Vishnu Nair6213bd92020-05-08 17:42:25 -07002109ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002110 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002111 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2112 return fixedTransformHint;
2113 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002114 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002115 if (!p) return fixedTransformHint;
2116 return p->getFixedTransformHint();
2117}
2118
chaviw13fdc492017-06-27 12:40:18 -07002119half4 Layer::getColor() const {
2120 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002121 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002122}
Robert Carr6452f122017-03-21 10:41:29 -07002123
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002124int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002125 if (getDrawingState().backgroundBlurRadius == 0) {
2126 return 0;
2127 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002128
Vishnu Nair29810f72022-07-01 16:38:41 +00002129 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002130 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2131 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002132}
2133
Galia Peychevae0acf382021-04-12 21:22:34 +02002134const std::vector<BlurRegion> Layer::getBlurRegions() const {
2135 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002136 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002137 for (auto& region : regionsCopy) {
2138 region.alpha = region.alpha * layerAlpha;
2139 }
2140 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002141}
2142
Vishnu Naire14c6b32022-08-06 04:20:15 +00002143RoundedCornerState Layer::getRoundedCornerState() const {
Leon Scroggins IIIc1dbfcb2022-03-21 16:48:10 -04002144 // Today's DPUs cannot do rounded corners. If RenderEngine cannot render
2145 // protected content, remove rounded corners from protected content so it
2146 // can be rendered by the DPU.
2147 if (isProtected() && !mFlinger->getRenderEngine().supportsProtectedContent()) {
2148 return {};
2149 }
2150
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002151 // Get parent settings
2152 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002153 const auto& parent = mDrawingParent.promote();
2154 if (parent != nullptr) {
2155 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002156 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002157 ui::Transform t = getActiveTransform(getDrawingState());
2158 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002159 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002160 parentSettings.radius.x *= t.getScaleX();
2161 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002162 }
2163 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002164
2165 // Get layer settings
2166 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002167 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002168 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002169 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002170
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002171 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002172 // If the parent and the layer have rounded corner settings, use the parent settings if the
2173 // parent crop is entirely inside the layer crop.
2174 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2175 if (parentSettings.cropRect.left > layerCropRect.left &&
2176 parentSettings.cropRect.top > layerCropRect.top &&
2177 parentSettings.cropRect.right < layerCropRect.right &&
2178 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2179 return parentSettings;
2180 } else {
2181 return layerSettings;
2182 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002183 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002184 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002185 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002186 return parentSettings;
2187 }
2188 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002189}
2190
Robert Carr88b85e12022-03-21 15:47:35 -07002191bool Layer::findInHierarchy(const sp<Layer>& l) {
2192 if (l == this) {
2193 return true;
2194 }
2195 for (auto& child : mDrawingChildren) {
2196 if (child->findInHierarchy(l)) {
2197 return true;
2198 }
2199 }
2200 return false;
2201}
2202
Robert Carr1f0a16a2016-10-24 16:27:39 -07002203void Layer::commitChildList() {
2204 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2205 const auto& child = mCurrentChildren[i];
2206 child->commitChildList();
2207 }
2208 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002209 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002210 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2211 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2212 if (zOrderRelativeOf == nullptr) return;
2213 if (findInHierarchy(zOrderRelativeOf)) {
2214 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2215 zOrderRelativeOf->mName.c_str());
2216 ALOGE("Severing rel Z loop, potentially dangerous");
2217 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002218 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002219 }
2220 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002221}
2222
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002223
chaviw3277faf2021-05-19 16:45:23 -05002224void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002225 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002226 mDrawingState.touchableRegionCrop =
2227 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002228 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002229 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002230 setTransactionFlags(eTransactionNeeded);
2231}
2232
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002233perfetto::protos::LayerProto* Layer::writeToProto(perfetto::protos::LayersProto& layersProto,
2234 uint32_t traceFlags) {
2235 perfetto::protos::LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002236 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002237 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2238
Vishnu Nair00b90132021-11-05 14:03:40 -07002239 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nair2f65e972023-04-04 16:36:28 +00002240 ui::LayerStack layerStack =
2241 (mSnapshot) ? mSnapshot->outputFilter.layerStack : ui::INVALID_LAYER_STACK;
2242 writeCompositionStateToProto(layerProto, layerStack);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002243 }
2244
chaviw08f3cb22020-01-13 13:17:21 -08002245 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002246 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002247 }
chaviw6d89e2d2020-01-14 14:42:01 -08002248
2249 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002250}
2251
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002252void Layer::writeCompositionStateToProto(perfetto::protos::LayerProto* layerProto,
2253 ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002254 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002255 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +00002256
2257 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002258 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002259 const auto compositionType = getCompositionType(*display);
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002260 layerProto->set_hwc_composition_type(
2261 static_cast<perfetto::protos::HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +00002262 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +00002263 [&]() { return layerProto->mutable_visible_region(); });
2264 }
2265}
2266
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002267void Layer::writeToProtoDrawingState(perfetto::protos::LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002268 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002269 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002270 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002271 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002272 [&]() { return layerInfo->mutable_active_buffer(); });
2273 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2274 layerInfo->mutable_buffer_transform());
2275 }
2276 layerInfo->set_invalidate(contentDirty);
2277 layerInfo->set_is_protected(isProtected());
2278 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2279 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002280 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002281 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002282 layerInfo->set_corner_radius(
2283 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002284 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2285 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2286 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2287 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2288 [&]() { return layerInfo->mutable_position(); });
2289 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002290 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2291 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002292
Vishnu Nair00b90132021-11-05 14:03:40 -07002293 if (hasColorTransform()) {
2294 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002295 }
2296
Vishnu Nair60db8c02020-04-02 11:55:16 -07002297 LayerProtoHelper::writeToProto(mSourceBounds,
2298 [&]() { return layerInfo->mutable_source_bounds(); });
2299 LayerProtoHelper::writeToProto(mScreenBounds,
2300 [&]() { return layerInfo->mutable_screen_bounds(); });
2301 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2302 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2303 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002304}
2305
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002306void Layer::writeToProtoCommonState(perfetto::protos::LayerProto* layerInfo,
2307 LayerVector::StateSet stateSet, uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002308 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2309 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002310 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002311
chaviw766c9c52021-02-10 17:36:47 -08002312 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002313
Vishnu Nair00b90132021-11-05 14:03:40 -07002314 layerInfo->set_id(sequence);
2315 layerInfo->set_name(getName().c_str());
2316 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002317
Vishnu Nair00b90132021-11-05 14:03:40 -07002318 for (const auto& child : children) {
2319 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002320 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002321
Vishnu Nair00b90132021-11-05 14:03:40 -07002322 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2323 sp<Layer> strongRelative = weakRelative.promote();
2324 if (strongRelative != nullptr) {
2325 layerInfo->add_relatives(strongRelative->sequence);
2326 }
2327 }
2328
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002329 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002330 [&]() { return layerInfo->mutable_transparent_region(); });
2331
2332 layerInfo->set_layer_stack(getLayerStack().id);
2333 layerInfo->set_z(state.z);
2334
2335 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2336 return layerInfo->mutable_requested_position();
2337 });
2338
Vishnu Nair00b90132021-11-05 14:03:40 -07002339 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2340
2341 layerInfo->set_is_opaque(isOpaque(state));
2342
2343 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2344 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2345 LayerProtoHelper::writeToProto(state.color,
2346 [&]() { return layerInfo->mutable_requested_color(); });
2347 layerInfo->set_flags(state.flags);
2348
2349 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2350 layerInfo->mutable_requested_transform());
2351
2352 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2353 if (parent != nullptr) {
2354 layerInfo->set_parent(parent->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002355 }
2356
2357 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2358 if (zOrderRelativeOf != nullptr) {
2359 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002360 }
2361
2362 layerInfo->set_is_relative_of(state.isRelativeOf);
2363
2364 layerInfo->set_owner_uid(mOwnerUid);
2365
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002366 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002367 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002368 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002369 info = fillInputInfo(
2370 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002371 } else {
2372 info = state.inputInfo;
2373 }
2374
2375 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002376 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002377 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002378
Vishnu Nair00b90132021-11-05 14:03:40 -07002379 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002380 auto protoMap = layerInfo->mutable_metadata();
2381 for (const auto& entry : state.metadata.mMap) {
2382 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2383 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002384 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002385
2386 LayerProtoHelper::writeToProto(state.destinationFrame,
2387 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002388}
2389
Robert Carr2e102c92018-10-23 12:11:15 -07002390bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002391 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002392}
2393
Prabir Pradhan33da9462022-06-14 14:55:57 +00002394// Applies the given transform to the region, while protecting against overflows caused by any
2395// offsets. If applying the offset in the transform to any of the Rects in the region would result
2396// in an overflow, they are not added to the output Region.
2397static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2398 const std::string& debugWindowName) {
2399 // Round the translation using the same rounding strategy used by ui::Transform.
2400 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2401 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2402
2403 ui::Transform transformWithoutOffset = t;
2404 transformWithoutOffset.set(0.f, 0.f);
2405
2406 const Region transformed = transformWithoutOffset.transform(r);
2407
2408 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2409 Region ret;
2410 for (const auto& rect : transformed) {
2411 Rect newRect;
2412 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2413 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2414 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2415 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2416 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2417 debugWindowName.c_str());
2418 continue;
2419 }
2420 ret.orSelf(newRect);
2421 }
2422 return ret;
2423}
2424
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002425void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002426 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2427 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002428 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002429 }
2430
Chavi Weingarten7f019192023-08-08 20:39:01 +00002431 info.frame = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
chaviw1ff3d1e2020-07-01 15:53:47 -07002432
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002433 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002434 inputToLayer.set(inputBounds.left, inputBounds.top);
2435 const ui::Transform layerToScreen = getInputTransform();
2436 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002437
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002438 // InputDispatcher expects a display-to-input transform.
2439 info.transform = inputToDisplay.inverse();
2440
2441 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002442 info.touchableRegion =
2443 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002444}
2445
chaviw3277faf2021-05-19 16:45:23 -05002446void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002447 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002448 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002449 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002450 }
2451 if (p != nullptr) {
2452 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2453 }
2454}
2455
Vishnu Naira066d902021-09-13 18:40:17 -07002456gui::DropInputMode Layer::getDropInputMode() const {
2457 gui::DropInputMode mode = mDrawingState.dropInputMode;
2458 if (mode == gui::DropInputMode::ALL) {
2459 return mode;
2460 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002461 sp<Layer> parent = mDrawingParent.promote();
2462 if (parent) {
2463 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002464 if (parentMode != gui::DropInputMode::NONE) {
2465 return parentMode;
2466 }
2467 }
2468 return mode;
2469}
2470
2471void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002472 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002473 return;
2474 }
2475
2476 // Check if we need to drop input unconditionally
2477 gui::DropInputMode dropInputMode = getDropInputMode();
2478 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002479 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002480 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2481 return;
2482 }
2483
2484 // Check if we need to check if the window is obscured by parent
2485 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2486 return;
2487 }
2488
2489 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002490 sp<Layer> parent = mDrawingParent.promote();
2491 if (parent && parent->getAlpha() != 1.0_hf) {
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 because alpha=%f", getDebugName(),
2494 static_cast<float>(getAlpha()));
2495 }
2496
2497 // Check if the parent has cropped the buffer
2498 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2499 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002500 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002501 return;
2502 }
2503
2504 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2505 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2506 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2507 // match then the layer has not been cropped by its parents.
2508 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2509 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2510
2511 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002512 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002513 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2514 getDebugName());
2515 } else {
2516 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2517 // input if the window is obscured. This check should be done in surfaceflinger but the
2518 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2519 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002520 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002521 }
2522}
2523
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002524WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002525 if (!hasInputInfo()) {
2526 mDrawingState.inputInfo.name = getName();
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002527 mDrawingState.inputInfo.ownerUid = gui::Uid{mOwnerUid};
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00002528 mDrawingState.inputInfo.ownerPid = gui::Pid{mOwnerPid};
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002529 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002530 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002531 }
2532
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002533 const ui::Transform& displayTransform =
2534 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2535
chaviw3277faf2021-05-19 16:45:23 -05002536 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002537 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002538 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002539
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002540 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002541
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002542 if (displayArgs.transform == nullptr) {
2543 // Do not let the window receive touches if it is not associated with a valid display
2544 // transform. We still allow the window to receive keys and prevent ANRs.
2545 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2546 }
2547
Patrick Williams1caf3b72023-03-31 10:59:10 -05002548 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !isVisibleForInput());
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002549
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002550 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002551 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002552 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002553
Vishnu Nair16a938f2021-09-24 07:14:54 -07002554 // If the window will be blacked out on a display because the display does not have the secure
2555 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002556 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002557 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002558 }
2559
Vishnu Nairfed7c122023-03-18 01:54:43 +00002560 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002561 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002562 Rect inputBoundsInDisplaySpace;
2563 if (!cropLayer) {
2564 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2565 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2566 } else {
2567 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2568 inputBoundsInDisplaySpace =
2569 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2570 }
2571 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002572 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002573 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2574 Rect inputBoundsInDisplaySpace =
2575 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2576 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002577 }
2578
Winson Chunga30f7c92021-06-29 15:42:56 -07002579 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2580 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002581 if (isTrustedOverlay()) {
2582 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2583 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002584
chaviwaf87b3e2019-10-01 16:59:28 -07002585 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2586 // touches from going outside the cloned area.
2587 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002588 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002589 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2590 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002591 info.touchableRegion = info.touchableRegion.intersect(rect);
2592 }
2593 }
2594
Robert Carr720e5062018-07-30 17:45:14 -07002595 return info;
2596}
2597
Vishnu Nairfed7c122023-03-18 01:54:43 +00002598Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2599 const ui::Transform& screenToDisplay) {
2600 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2601 // frame and transform used for the layer, which determines the bounds and the coordinate space
2602 // within which the layer will receive input.
2603
2604 // Coordinate space definitions:
2605 // - display: The display device's coordinate space. Correlates to pixels on the display.
2606 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2607 // - layer: The coordinate space of this layer.
2608 // - input: The coordinate space in which this layer will receive input events. This could be
2609 // different than layer space if a surfaceInset is used, which changes the origin
2610 // of the input space.
2611
2612 // Crop the input bounds to ensure it is within the parent's bounds.
2613 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2614 const ui::Transform layerToScreen = getInputTransform();
2615 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2616 return Rect{layerToDisplay.transform(croppedInputBounds)};
2617}
2618
chaviwaf87b3e2019-10-01 16:59:28 -07002619sp<Layer> Layer::getClonedRoot() {
2620 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002621 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002622 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002623 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002624 return nullptr;
2625 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002626 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002627}
2628
Robert Carredd13602020-04-13 17:24:34 -07002629bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002630 return mDrawingState.inputInfo.token != nullptr ||
2631 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002632}
2633
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002634compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002635 const DisplayDevice* display) const {
2636 if (!display) return nullptr;
Lloyd Pique30db6402023-06-26 18:56:51 +00002637 if (!mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00002638 return display->getCompositionDisplay()->getOutputLayerForLayer(
2639 getCompositionEngineLayerFE());
2640 }
2641 sp<LayerFE> layerFE;
2642 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2643 for (auto& [p, layer] : mLayerFEs) {
2644 if (p == path) {
2645 layerFE = layer;
2646 }
2647 }
2648
2649 if (!layerFE) return nullptr;
2650 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002651}
2652
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002653compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
2654 const DisplayDevice* display, const frontend::LayerHierarchy::TraversalPath& path) const {
2655 if (!display) return nullptr;
Vishnu Naire9ee0002023-07-01 03:14:51 +00002656 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2657 return display->getCompositionDisplay()->getOutputLayerForLayer(
2658 getCompositionEngineLayerFE());
2659 }
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002660 sp<LayerFE> layerFE;
2661 for (auto& [p, layer] : mLayerFEs) {
2662 if (p == path) {
2663 layerFE = layer;
2664 }
2665 }
2666
2667 if (!layerFE) return nullptr;
2668 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
2669}
2670
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002671Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2672 const auto outputLayer = findOutputLayerForDisplay(display);
2673 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002674}
2675
Vishnu Nairde177252023-04-21 12:44:10 -07002676void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom, uint32_t mirrorRootId) {
2677 mSnapshot->path.id = clonedFrom->getSequence();
Vishnu Nair6f878312023-09-08 11:05:01 -07002678 mSnapshot->path.mirrorRootIds.emplace_back(mirrorRootId);
Vishnu Nairde177252023-04-21 12:44:10 -07002679
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002680 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002681 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002682 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2683 mPotentialCursor = clonedFrom->mPotentialCursor;
2684 mProtectedByApp = clonedFrom->mProtectedByApp;
2685 updateCloneBufferInfo();
2686}
2687
2688void Layer::updateCloneBufferInfo() {
2689 if (!isClone() || !isClonedFromAlive()) {
2690 return;
2691 }
2692
2693 sp<Layer> clonedFrom = getClonedFrom();
2694 mBufferInfo = clonedFrom->mBufferInfo;
2695 mSidebandStream = clonedFrom->mSidebandStream;
2696 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2697 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2698 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2699
2700 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2701 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2702 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2703 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2704 // the cloned drawingState again.
2705 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2706 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2707 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2708 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2709
2710 cloneDrawingState(clonedFrom.get());
2711
2712 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2713 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2714 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2715 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002716}
chaviw74b03172019-08-19 11:09:03 -07002717
Vishnu Nair3be61902023-04-26 19:47:29 -07002718bool Layer::updateMirrorInfo(const std::deque<Layer*>& cloneRootsPendingUpdates) {
chaviw74b03172019-08-19 11:09:03 -07002719 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2720 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2721 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2722 // that case, we want to delete the reference to the clone since we want it to get
2723 // destroyed. The root, this layer, will still be around since the client can continue
2724 // to hold a reference, but no cloned layers will be displayed.
2725 mClonedChild = nullptr;
Vishnu Nair3be61902023-04-26 19:47:29 -07002726 return true;
chaviw74b03172019-08-19 11:09:03 -07002727 }
2728
2729 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2730 // If the real layer exists and is in current state, add the clone as a child of the root.
2731 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2732 // copied to drawingState for the root layer. So the clonedChild is always removed from
2733 // drawingState and then needs to be added back each traversal.
2734 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2735 addChildToDrawing(mClonedChild);
2736 }
2737
2738 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002739 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002740 mClonedChild->updateClonedRelatives(clonedLayersMap);
Vishnu Nair3be61902023-04-26 19:47:29 -07002741
2742 for (Layer* root : cloneRootsPendingUpdates) {
2743 if (clonedLayersMap.find(sp<Layer>::fromExisting(root)) != clonedLayersMap.end()) {
2744 return false;
2745 }
2746 }
2747 return true;
chaviw74b03172019-08-19 11:09:03 -07002748}
2749
2750void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2751 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2752 // to the clone. If the real layer is no longer alive, continue traversing the children
2753 // since we may be able to pull out other children that are still alive.
2754 if (isClonedFromAlive()) {
2755 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002756 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002757 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002758 }
2759
2760 // The clone layer may have children in drawingState since they may have been created and
2761 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2762 // that already exist, since we can just re-use them.
2763 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2764 // not updated in the regular traversal. They are skipped since the root will lose the
2765 // reference to them when it copies its currentChildren to drawing.
2766 for (sp<Layer>& child : mDrawingChildren) {
2767 child->updateClonedDrawingState(clonedLayersMap);
2768 }
2769}
2770
2771void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2772 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2773 mDrawingChildren.clear();
2774
2775 if (!isClonedFromAlive()) {
2776 return;
2777 }
2778
2779 sp<Layer> clonedFrom = getClonedFrom();
2780 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2781 if (child == mirrorRoot) {
2782 // This is to avoid cyclical mirroring.
2783 continue;
2784 }
2785 sp<Layer> clonedChild = clonedLayersMap[child];
2786 if (clonedChild == nullptr) {
Vishnu Nairde177252023-04-21 12:44:10 -07002787 clonedChild = child->createClone(mirrorRoot->getSequence());
chaviw74b03172019-08-19 11:09:03 -07002788 clonedLayersMap[child] = clonedChild;
2789 }
2790 addChildToDrawing(clonedChild);
2791 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2792 }
2793}
2794
chaviwaf87b3e2019-10-01 16:59:28 -07002795void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2796 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2797 if (cropLayer != nullptr) {
2798 if (clonedLayersMap.count(cropLayer) == 0) {
2799 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2800 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002801 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002802 } else {
2803 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2804 mDrawingState.touchableRegionCrop = clonedCropLayer;
2805 }
2806 }
2807 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2808 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002809 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002810}
2811
2812void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002813 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002814 mDrawingState.zOrderRelatives.clear();
2815
2816 if (!isClonedFromAlive()) {
2817 return;
2818 }
2819
chaviwaf87b3e2019-10-01 16:59:28 -07002820 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002821 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002822 const sp<Layer>& relative = relativeWeak.promote();
2823 if (clonedLayersMap.count(relative) > 0) {
2824 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002825 mDrawingState.zOrderRelatives.add(clonedRelative);
2826 }
2827 }
2828
2829 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2830 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2831 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2832 // still traverse the children, but the layer with the missing relativeOf will not be shown
2833 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002834 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2835 if (clonedLayersMap.count(relativeOf) > 0) {
2836 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002837 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2838 }
2839
chaviwaf87b3e2019-10-01 16:59:28 -07002840 updateClonedInputInfo(clonedLayersMap);
2841
chaviw74b03172019-08-19 11:09:03 -07002842 for (sp<Layer>& child : mDrawingChildren) {
2843 child->updateClonedRelatives(clonedLayersMap);
2844 }
2845}
2846
2847void Layer::addChildToDrawing(const sp<Layer>& layer) {
2848 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002849 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002850}
2851
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002852bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002853 const State& s(mDrawingState);
2854 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2855 return true;
2856 }
2857
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002858 sp<Layer> parent = mDrawingParent.promote();
2859 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002860}
2861
Robert Carr6a0382d2021-07-01 15:57:17 -07002862void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2863 mClonedChild = clonedChild;
2864 mHadClonedChild = true;
Vishnu Nair3be61902023-04-26 19:47:29 -07002865 mFlinger->mLayerMirrorRoots.push_back(this);
Robert Carr6a0382d2021-07-01 15:57:17 -07002866}
2867
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002868bool Layer::setDropInputMode(gui::DropInputMode mode) {
2869 if (mDrawingState.dropInputMode == mode) {
2870 return false;
2871 }
2872 mDrawingState.dropInputMode = mode;
2873 return true;
2874}
2875
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002876void Layer::cloneDrawingState(const Layer* from) {
2877 mDrawingState = from->mDrawingState;
2878 // Skip callback info since they are not applicable for cloned layers.
2879 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002880 // TODO (b/238781169) currently broken for mirror layers because we do not
2881 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002882 mDrawingState.callbackHandles = {};
2883}
2884
Patrick Williamsbb25f802022-08-30 23:02:34 +00002885void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2886 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002887 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002888 if (!listener) {
2889 return;
2890 }
2891 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002892 uint32_t currentMaxAcquiredBufferCount =
2893 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002894 listener->onReleaseBuffer({buffer->getId(), framenumber},
2895 releaseFence ? releaseFence : Fence::NO_FENCE,
2896 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002897}
2898
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002899void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
2900 ui::LayerStack layerStack) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002901 // If we are displayed on multiple displays in a single composition cycle then we would
2902 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2903 // For example we can only use it if all the displays are client comp, and we need
2904 // to merge all the client comp fences. We could do this, but for now we just
2905 // disable the optimization when a layer is composed on multiple displays.
2906 if (mClearClientCompositionFenceOnLayerDisplayed) {
2907 mLastClientCompositionFence = nullptr;
2908 } else {
2909 mClearClientCompositionFenceOnLayerDisplayed = true;
2910 }
2911
2912 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2913 // buffer that was presented on this layer. The first transaction that came in this frame that
2914 // replaced the previous buffer on this layer needs this release fence, because the fence will
2915 // let the client know when that previous buffer is removed from the screen.
2916 //
2917 // Every other transaction on this layer does not need a release fence because no other
2918 // Transactions that were set on this layer this frame are going to have their preceding buffer
2919 // removed from the display this frame.
2920 //
2921 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2922 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2923 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2924 // the previous buffer will be released this frame. The third transaction also contains a
2925 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2926 // transaction will now no longer be presented so it is released immediately and the third
2927 // transaction doesn't need a previous release fence.
2928 sp<CallbackHandle> ch;
2929 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002930 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002931 ch = handle;
2932 break;
2933 }
2934 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002935 if (ch != nullptr) {
2936 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2937 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2938 ch->name = mName;
2939 }
Vishnu Nair316b7f42023-10-13 23:44:46 +00002940 if (mBufferInfo.mBuffer) {
2941 mPreviouslyPresentedLayerStacks.push_back(layerStack);
2942 }
Alec Mouri21d94322023-10-17 19:51:39 +00002943
2944 if (mDrawingState.frameNumber > 0) {
2945 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
2946 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002947}
2948
2949void Layer::onSurfaceFrameCreated(
2950 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2951 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2952 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2953 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2954 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002955 if (hasBufferOrSidebandStreamInDrawing()) {
2956 // Only log for layers with a buffer, since we expect the jank data to be drained for
2957 // these, while there may be no jank listeners for bufferless layers.
2958 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2959 mName.c_str());
2960 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2961 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2962 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002963 mPendingJankClassifications.pop_front();
2964 }
2965 mPendingJankClassifications.emplace_back(surfaceFrame);
2966}
2967
2968void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2969 for (const auto& handle : mDrawingState.callbackHandles) {
Lloyd Pique30db6402023-06-26 18:56:51 +00002970 if (mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -07002971 handle->transformHint = mTransformHint;
2972 } else {
2973 handle->transformHint = mSkipReportingTransformHint
2974 ? std::nullopt
2975 : std::make_optional<uint32_t>(mTransformHintLegacy);
2976 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002977 handle->dequeueReadyTime = dequeueReadyTime;
2978 handle->currentMaxAcquiredBufferCount =
2979 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2980 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2981 handle->previousReleaseCallbackId.framenumber);
2982 }
2983
2984 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002985 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002986 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2987 break;
2988 }
2989 }
2990
2991 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002992 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002993 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2994 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002995 mDrawingState.callbackHandles = {};
2996}
2997
2998bool Layer::willPresentCurrentTransaction() const {
2999 // Returns true if the most recent Transaction applied to CurrentState will be presented.
3000 return (getSidebandStreamChanged() || getAutoRefresh() ||
3001 (mDrawingState.modified &&
3002 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
3003}
3004
3005bool Layer::setTransform(uint32_t transform) {
3006 if (mDrawingState.bufferTransform == transform) return false;
3007 mDrawingState.bufferTransform = transform;
3008 mDrawingState.modified = true;
3009 setTransactionFlags(eTransactionNeeded);
3010 return true;
3011}
3012
3013bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
3014 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
3015 mDrawingState.sequence++;
3016 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
3017 mDrawingState.modified = true;
3018 setTransactionFlags(eTransactionNeeded);
3019 return true;
3020}
3021
3022bool Layer::setBufferCrop(const Rect& bufferCrop) {
3023 if (mDrawingState.bufferCrop == bufferCrop) return false;
3024
3025 mDrawingState.sequence++;
3026 mDrawingState.bufferCrop = bufferCrop;
3027
3028 mDrawingState.modified = true;
3029 setTransactionFlags(eTransactionNeeded);
3030 return true;
3031}
3032
3033bool Layer::setDestinationFrame(const Rect& destinationFrame) {
3034 if (mDrawingState.destinationFrame == destinationFrame) return false;
3035
3036 mDrawingState.sequence++;
3037 mDrawingState.destinationFrame = destinationFrame;
3038
3039 mDrawingState.modified = true;
3040 setTransactionFlags(eTransactionNeeded);
3041 return true;
3042}
3043
3044// Translate destination frame into scale and position. If a destination frame is not set, use the
3045// provided scale and position
3046bool Layer::updateGeometry() {
3047 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
3048 mDrawingState.destinationFrame.isEmpty()) {
3049 // If destination frame is not set, use the requested transform set via
3050 // Layer::setPosition and Layer::setMatrix.
3051 return assignTransform(&mDrawingState.transform, mRequestedTransform);
3052 }
3053
3054 Rect destRect = mDrawingState.destinationFrame;
3055 int32_t destW = destRect.width();
3056 int32_t destH = destRect.height();
3057 if (destRect.left < 0) {
3058 destRect.left = 0;
3059 destRect.right = destW;
3060 }
3061 if (destRect.top < 0) {
3062 destRect.top = 0;
3063 destRect.bottom = destH;
3064 }
3065
3066 if (!mDrawingState.buffer) {
3067 ui::Transform t;
3068 t.set(destRect.left, destRect.top);
3069 return assignTransform(&mDrawingState.transform, t);
3070 }
3071
3072 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3073 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3074 // Undo any transformations on the buffer.
3075 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3076 std::swap(bufferWidth, bufferHeight);
3077 }
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003078 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003079 if (mDrawingState.transformToDisplayInverse) {
3080 if (invTransform & ui::Transform::ROT_90) {
3081 std::swap(bufferWidth, bufferHeight);
3082 }
3083 }
3084
3085 float sx = destW / static_cast<float>(bufferWidth);
3086 float sy = destH / static_cast<float>(bufferHeight);
3087 ui::Transform t;
3088 t.set(sx, 0, 0, sy);
3089 t.set(destRect.left, destRect.top);
3090 return assignTransform(&mDrawingState.transform, t);
3091}
3092
3093bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3094 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3095 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3096 return false;
3097 }
3098
3099 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3100
3101 mDrawingState.sequence++;
3102 mDrawingState.modified = true;
3103 setTransactionFlags(eTransactionNeeded);
3104
3105 return true;
3106}
3107
3108bool Layer::setPosition(float x, float y) {
3109 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3110 return false;
3111 }
3112
3113 mRequestedTransform.set(x, y);
3114
3115 mDrawingState.sequence++;
3116 mDrawingState.modified = true;
3117 setTransactionFlags(eTransactionNeeded);
3118
3119 return true;
3120}
3121
Dorin Drimuse5374e52023-08-02 17:52:43 +00003122void Layer::releasePreviousBuffer() {
3123 mReleasePreviousBuffer = true;
3124 if (!mBufferInfo.mBuffer ||
3125 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3126 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3127 // If mDrawingState has a buffer, and we are about to update again
3128 // before swapping to drawing state, then the first buffer will be
3129 // dropped and we should decrement the pending buffer count and
3130 // call any release buffer callbacks if set.
3131 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3132 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3133 mDrawingState.acquireFence);
3134 decrementPendingBufferCount();
3135 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3136 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3137 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX, systemTime());
3138 mDrawingState.bufferSurfaceFrameTX.reset();
3139 }
3140 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3141 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3142 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3143 mLastClientCompositionFence);
3144 mLastClientCompositionFence = nullptr;
3145 }
3146}
3147
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003148void Layer::resetDrawingStateBufferInfo() {
3149 mDrawingState.producerId = 0;
3150 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +00003151 mDrawingState.previousFrameNumber = 0;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003152 mDrawingState.releaseBufferListener = nullptr;
3153 mDrawingState.buffer = nullptr;
3154 mDrawingState.acquireFence = sp<Fence>::make(-1);
3155 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3156 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3157 mDrawingState.releaseBufferEndpoint = nullptr;
3158}
3159
Patrick Williamsbb25f802022-08-30 23:02:34 +00003160bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3161 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3162 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003163 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003164 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003165
3166 const bool frameNumberChanged =
3167 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3168 const uint64_t frameNumber =
3169 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003170 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003171
3172 if (mDrawingState.buffer) {
Dorin Drimuse5374e52023-08-02 17:52:43 +00003173 releasePreviousBuffer();
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003174 } else if (buffer) {
Vishnu Nairc09c0232023-03-02 03:22:35 +00003175 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3176 // we don't want to incorrectly classify a frame if we miss the desired present time.
3177 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003178 }
3179
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003180 mDrawingState.desiredPresentTime = desiredPresentTime;
3181 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3182 mDrawingState.latchedVsyncId = info.vsyncId;
Ady Abraham55269162023-05-09 11:26:06 -07003183 mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003184 mDrawingState.modified = true;
3185 if (!buffer) {
3186 resetDrawingStateBufferInfo();
3187 setTransactionFlags(eTransactionNeeded);
3188 mDrawingState.bufferSurfaceFrameTX = nullptr;
3189 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3190 return true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003191 } else {
3192 // release sideband stream if it exists and a non null buffer is being set
3193 if (mDrawingState.sidebandStream != nullptr) {
Dorin Drimus66ed1c42023-09-27 13:10:16 +00003194 setSidebandStream(nullptr, info, postTime);
Dorin Drimuse5374e52023-08-02 17:52:43 +00003195 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003196 }
3197
Vishnu Naird1f74982023-06-15 20:16:51 -07003198 if ((mDrawingState.producerId > bufferData.producerId) ||
3199 ((mDrawingState.producerId == bufferData.producerId) &&
3200 (mDrawingState.frameNumber > frameNumber))) {
3201 ALOGE("Out of order buffers detected for %s producedId=%d frameNumber=%" PRIu64
3202 " -> producedId=%d frameNumber=%" PRIu64,
3203 getDebugName(), mDrawingState.producerId, mDrawingState.frameNumber,
3204 bufferData.producerId, frameNumber);
3205 TransactionTraceWriter::getInstance().invoke("out_of_order_buffers_", /*overwrite=*/false);
3206 }
3207
liulijuneb489f62022-10-17 22:02:14 +08003208 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -07003209 mDrawingState.barrierProducerId =
3210 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003211 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -07003212 mDrawingState.barrierFrameNumber =
3213 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
3214
Patrick Williamsbb25f802022-08-30 23:02:34 +00003215 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3216 mDrawingState.buffer = std::move(buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003217 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3218 ? bufferData.acquireFence
3219 : Fence::NO_FENCE;
3220 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3221 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3222 // We latched this buffer unsiganled, so we need to pass the acquire fence
3223 // on the callback instead of just the acquire time, since it's unknown at
3224 // this point.
3225 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3226 } else {
3227 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3228 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003229 setTransactionFlags(eTransactionNeeded);
3230
3231 const int32_t layerId = getSequence();
3232 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3233 mOwnerUid, postTime, getGameMode());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003234
Lloyd Pique30db6402023-06-26 18:56:51 +00003235 if (mFlinger->mLegacyFrontEndEnabled) {
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003236 recordLayerHistoryBufferUpdate(getLayerProps(), systemTime());
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003237 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003238
3239 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3240
3241 if (dequeueTime && *dequeueTime != 0) {
3242 const uint64_t bufferId = mDrawingState.buffer->getId();
3243 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3244 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3245 FrameTracer::FrameEvent::DEQUEUE);
3246 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3247 FrameTracer::FrameEvent::QUEUE);
3248 }
3249
3250 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
Arthur Hungc70bee22023-06-02 01:35:52 +00003251
3252 // If the layer had been updated a TextureView, this would make sure the present time could be
3253 // same to TextureView update when it's a small dirty, and get the correct heuristic rate.
3254 if (mFlinger->mScheduler->supportSmallDirtyDetection()) {
3255 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3256 mUsedVsyncIdForRefreshRateSelection = true;
3257 }
3258 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003259 return true;
3260}
3261
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003262void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3263 mDrawingState.desiredPresentTime = desiredPresentTime;
3264 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3265}
3266
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003267void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps, nsecs_t now) {
Ady Abraham55269162023-05-09 11:26:06 -07003268 ATRACE_CALL();
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003269 const nsecs_t presentTime = [&] {
Ady Abraham55269162023-05-09 11:26:06 -07003270 if (!mDrawingState.isAutoTimestamp) {
3271 ATRACE_FORMAT_INSTANT("desiredPresentTime");
3272 return mDrawingState.desiredPresentTime;
3273 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003274
Ady Abraham55269162023-05-09 11:26:06 -07003275 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3276 const auto prediction =
3277 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3278 mDrawingState.latchedVsyncId);
3279 if (prediction.has_value()) {
3280 ATRACE_FORMAT_INSTANT("predictedPresentTime");
Arthur Hungc70bee22023-06-02 01:35:52 +00003281 mMaxTimeForUseVsyncId = prediction->presentTime +
3282 scheduler::LayerHistory::kMaxPeriodForHistory.count();
Ady Abraham55269162023-05-09 11:26:06 -07003283 return prediction->presentTime;
3284 }
3285 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003286
Arthur Hungc70bee22023-06-02 01:35:52 +00003287 if (!mFlinger->mScheduler->supportSmallDirtyDetection()) {
3288 return static_cast<nsecs_t>(0);
3289 }
3290
3291 // If the layer is not an application and didn't set an explicit rate or desiredPresentTime,
3292 // return "0" to tell the layer history that it will use the max refresh rate without
3293 // calculating the adaptive rate.
3294 if (mWindowType != WindowInfo::Type::APPLICATION &&
3295 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
3296 return static_cast<nsecs_t>(0);
3297 }
3298
3299 // Return the valid present time only when the layer potentially updated a TextureView so
3300 // LayerHistory could heuristically calculate the rate if the UI is continually updating.
3301 if (mUsedVsyncIdForRefreshRateSelection) {
3302 const auto prediction =
3303 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3304 mDrawingState.latchedVsyncId);
3305 if (prediction.has_value()) {
3306 if (mMaxTimeForUseVsyncId >= prediction->presentTime) {
3307 return prediction->presentTime;
3308 }
3309 mUsedVsyncIdForRefreshRateSelection = false;
3310 }
3311 }
3312
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003313 return static_cast<nsecs_t>(0);
3314 }();
Ady Abraham55269162023-05-09 11:26:06 -07003315
3316 if (ATRACE_ENABLED() && presentTime > 0) {
3317 const auto presentIn = TimePoint::fromNs(presentTime) - TimePoint::now();
3318 ATRACE_FORMAT_INSTANT("presentIn %s", to_string(presentIn).c_str());
3319 }
3320
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003321 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003322 scheduler::LayerHistory::LayerUpdateType::Buffer);
3323}
3324
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003325void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps, nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003326 const nsecs_t presentTime =
3327 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003328 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003329 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3330}
3331
Patrick Williamsbb25f802022-08-30 23:02:34 +00003332bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003333 if (mDrawingState.dataspace == dataspace) return false;
3334 mDrawingState.dataspace = dataspace;
3335 mDrawingState.modified = true;
3336 setTransactionFlags(eTransactionNeeded);
3337 return true;
3338}
3339
John Reck68796592023-01-25 13:47:12 -05003340bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07003341 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3342 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05003343 return false;
Sally Qi963049b2023-03-23 14:06:21 -07003344 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3345 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05003346 mDrawingState.modified = true;
3347 setTransactionFlags(eTransactionNeeded);
3348 return true;
3349}
3350
Alec Mourif4af03e2023-02-11 00:25:24 +00003351bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3352 if (mDrawingState.cachingHint == cachingHint) return false;
3353 mDrawingState.cachingHint = cachingHint;
3354 mDrawingState.modified = true;
3355 setTransactionFlags(eTransactionNeeded);
3356 return true;
3357}
3358
Patrick Williamsbb25f802022-08-30 23:02:34 +00003359bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3360 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3361 mDrawingState.hdrMetadata = hdrMetadata;
3362 mDrawingState.modified = true;
3363 setTransactionFlags(eTransactionNeeded);
3364 return true;
3365}
3366
3367bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003368 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003369 mDrawingState.surfaceDamageRegion = surfaceDamage;
3370 mDrawingState.modified = true;
3371 setTransactionFlags(eTransactionNeeded);
Arthur Hung69f95222023-10-04 07:39:02 +00003372 setIsSmallDirty(surfaceDamage, getTransform());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003373 return true;
3374}
3375
3376bool Layer::setApi(int32_t api) {
3377 if (mDrawingState.api == api) return false;
3378 mDrawingState.api = api;
3379 mDrawingState.modified = true;
3380 setTransactionFlags(eTransactionNeeded);
3381 return true;
3382}
3383
Dorin Drimuse5374e52023-08-02 17:52:43 +00003384bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream, const FrameTimelineInfo& info,
3385 nsecs_t postTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003386 if (mDrawingState.sidebandStream == sidebandStream) return false;
3387
3388 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3389 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3390 } else if (sidebandStream != nullptr) {
3391 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3392 }
3393
3394 mDrawingState.sidebandStream = sidebandStream;
3395 mDrawingState.modified = true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003396 if (sidebandStream != nullptr && mDrawingState.buffer != nullptr) {
3397 releasePreviousBuffer();
3398 resetDrawingStateBufferInfo();
3399 mDrawingState.bufferSurfaceFrameTX = nullptr;
3400 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3401 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003402 setTransactionFlags(eTransactionNeeded);
3403 if (!mSidebandStreamChanged.exchange(true)) {
3404 // mSidebandStreamChanged was false
3405 mFlinger->onLayerUpdate();
3406 }
3407 return true;
3408}
3409
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003410bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3411 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003412 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3413 if (handles.empty()) {
3414 mReleasePreviousBuffer = false;
3415 return false;
3416 }
3417
Pascal Muetschard81cef292023-02-06 12:18:52 +01003418 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003419 for (const auto& handle : handles) {
3420 // If this transaction set a buffer on this layer, release its previous buffer
3421 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3422
3423 // If this layer will be presented in this frame
3424 if (willPresent) {
3425 // If this transaction set an acquire fence on this layer, set its acquire time
3426 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3427 handle->frameNumber = mDrawingState.frameNumber;
Alec Mouri21d94322023-10-17 19:51:39 +00003428 handle->previousFrameNumber = mDrawingState.previousFrameNumber;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003429
3430 // Store so latched time and release fence can be set
3431 mDrawingState.callbackHandles.push_back(handle);
3432
3433 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003434 // Queue this handle to be notified below.
3435 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003436 }
3437 }
3438
Pascal Muetschard81cef292023-02-06 12:18:52 +01003439 if (!remainingHandles.empty()) {
3440 // Notify the transaction completed threads these handles are done. These are only the
3441 // handles that were not added to the mDrawingState, which will be notified later.
3442 std::vector<JankData> jankData;
3443 transferAvailableJankData(remainingHandles, jankData);
3444 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3445 }
3446
Patrick Williamsbb25f802022-08-30 23:02:34 +00003447 mReleasePreviousBuffer = false;
3448 mCallbackHandleAcquireTimeOrFence = -1;
3449
3450 return willPresent;
3451}
3452
3453Rect Layer::getBufferSize(const State& /*s*/) const {
3454 // for buffer state layers we use the display frame size as the buffer size.
3455
3456 if (mBufferInfo.mBuffer == nullptr) {
3457 return Rect::INVALID_RECT;
3458 }
3459
3460 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3461 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3462
3463 // Undo any transformations on the buffer and return the result.
3464 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3465 std::swap(bufWidth, bufHeight);
3466 }
3467
3468 if (getTransformToDisplayInverse()) {
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003469 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003470 if (invTransform & ui::Transform::ROT_90) {
3471 std::swap(bufWidth, bufHeight);
3472 }
3473 }
3474
3475 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3476}
3477
3478FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3479 if (mBufferInfo.mBuffer == nullptr) {
3480 return parentBounds;
3481 }
3482
3483 return getBufferSize(getDrawingState()).toFloatRect();
3484}
3485
3486bool Layer::fenceHasSignaled() const {
3487 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3488 return true;
3489 }
3490
3491 const bool fenceSignaled =
3492 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3493 if (!fenceSignaled) {
3494 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3495 TimeStats::LatchSkipReason::LateAcquire);
3496 }
3497
3498 return fenceSignaled;
3499}
3500
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003501void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003502 for (const auto& handle : mDrawingState.callbackHandles) {
3503 handle->refreshStartTime = refreshStartTime;
3504 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003505}
3506
3507void Layer::setAutoRefresh(bool autoRefresh) {
3508 mDrawingState.autoRefresh = autoRefresh;
3509}
3510
3511bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3512 // 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 +00003513 auto* snapshot = editLayerSnapshot();
3514 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003515
3516 if (mSidebandStreamChanged.exchange(false)) {
3517 const State& s(getDrawingState());
3518 // mSidebandStreamChanged was true
3519 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003520 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003521 if (mSidebandStream != nullptr) {
3522 setTransactionFlags(eTransactionNeeded);
3523 mFlinger->setTransactionFlags(eTraversalNeeded);
3524 }
3525 recomputeVisibleRegions = true;
3526
3527 return true;
3528 }
3529 return false;
3530}
3531
3532bool Layer::hasFrameUpdate() const {
3533 const State& c(getDrawingState());
3534 return (mDrawingStateModified || mDrawingState.modified) &&
3535 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3536}
3537
Vishnu Naird47bcee2023-02-24 18:08:51 +00003538void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003539 const State& s(getDrawingState());
3540
3541 if (!s.buffer) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003542 if (bgColorOnly || mBufferInfo.mBuffer) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003543 for (auto& handle : mDrawingState.callbackHandles) {
3544 handle->latchTime = latchTime;
3545 }
3546 }
3547 return;
3548 }
3549
3550 for (auto& handle : mDrawingState.callbackHandles) {
3551 if (handle->frameNumber == mDrawingState.frameNumber) {
3552 handle->latchTime = latchTime;
3553 }
3554 }
3555
3556 const int32_t layerId = getSequence();
3557 const uint64_t bufferId = mDrawingState.buffer->getId();
3558 const uint64_t frameNumber = mDrawingState.frameNumber;
3559 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3560 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3561 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3562
3563 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3564 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3565 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3566 FrameTracer::FrameEvent::LATCH);
3567
3568 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3569 if (bufferSurfaceFrame != nullptr &&
3570 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3571 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3572 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3573 // are processing the next state.
3574 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3575 mDrawingState.acquireFenceTime->getSignalTime(),
3576 latchTime);
3577 mDrawingState.bufferSurfaceFrameTX.reset();
3578 }
3579
3580 std::deque<sp<CallbackHandle>> remainingHandles;
3581 mFlinger->getTransactionCallbackInvoker()
3582 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3583 mDrawingState.callbackHandles = remainingHandles;
3584
3585 mDrawingStateModified = false;
3586}
3587
3588void Layer::gatherBufferInfo() {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003589 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3590 mPreviousReleaseBufferEndpoint = mBufferInfo.mReleaseBufferEndpoint;
3591 if (!mDrawingState.buffer) {
3592 mBufferInfo = {};
3593 return;
3594 }
3595
3596 if ((!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer))) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003597 decrementPendingBufferCount();
3598 }
3599
Patrick Williamsbb25f802022-08-30 23:02:34 +00003600 mBufferInfo.mBuffer = mDrawingState.buffer;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003601 mBufferInfo.mReleaseBufferEndpoint = mDrawingState.releaseBufferEndpoint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003602 mBufferInfo.mFence = mDrawingState.acquireFence;
3603 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3604 mBufferInfo.mPixelFormat =
3605 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3606 mBufferInfo.mFrameLatencyNeeded = true;
3607 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3608 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3609 mBufferInfo.mFence = mDrawingState.acquireFence;
3610 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3611 auto lastDataspace = mBufferInfo.mDataspace;
3612 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003613 if (mBufferInfo.mBuffer != nullptr) {
3614 auto& mapper = GraphicBufferMapper::get();
3615 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
3616 // and don't need to possibly remaps buffers.
3617 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
3618 status_t err = OK;
3619 {
3620 ATRACE_NAME("getDataspace");
3621 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
3622 }
3623 if (err != OK || dataspace != mBufferInfo.mDataspace) {
3624 {
3625 ATRACE_NAME("setDataspace");
3626 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
3627 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
3628 }
3629
3630 // Some GPU drivers may cache gralloc metadata which means before we composite we need
3631 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
3632 // compatible with old vendors, with a ticking clock.
3633 static const int32_t kVendorVersion =
3634 base::GetIntProperty("ro.vndk.version", __ANDROID_API_FUTURE__);
3635 if (const auto format =
3636 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
3637 mBufferInfo.mBuffer->getPixelFormat());
3638 err == OK && kVendorVersion < __ANDROID_API_U__ &&
3639 (format ==
3640 aidl::android::hardware::graphics::common::PixelFormat::
3641 IMPLEMENTATION_DEFINED ||
3642 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
3643 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
3644 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
3645 mBufferInfo.mBuffer->remapBuffer();
3646 }
3647 }
3648 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003649 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003650 mFlinger->mHdrLayerInfoChanged = true;
3651 }
Sally Qi963049b2023-03-23 14:06:21 -07003652 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3653 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05003654 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003655 }
3656 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3657 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3658 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3659 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3660 mBufferInfo.mApi = mDrawingState.api;
3661 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003662}
3663
3664Rect Layer::computeBufferCrop(const State& s) {
3665 if (s.buffer && !s.bufferCrop.isEmpty()) {
3666 Rect bufferCrop;
3667 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3668 return bufferCrop;
3669 } else if (s.buffer) {
3670 return s.buffer->getBounds();
3671 } else {
3672 return s.bufferCrop;
3673 }
3674}
3675
Vishnu Nairde177252023-04-21 12:44:10 -07003676sp<Layer> Layer::createClone(uint32_t mirrorRootId) {
Kean Mariotti4ba343c2023-04-19 13:31:02 +00003677 surfaceflinger::LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0,
3678 LayerMetadata());
Patrick Williams83f36b22022-09-14 17:57:35 +00003679 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Vishnu Nairde177252023-04-21 12:44:10 -07003680 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this), mirrorRootId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003681 return layer;
3682}
3683
Patrick Williamsbb25f802022-08-30 23:02:34 +00003684void Layer::decrementPendingBufferCount() {
3685 int32_t pendingBuffers = --mPendingBufferTransactions;
3686 tracePendingBufferCount(pendingBuffers);
3687}
3688
3689void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3690 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3691}
3692
3693/*
3694 * We don't want to send the layer's transform to input, but rather the
3695 * parent's transform. This is because Layer's transform is
3696 * information about how the buffer is placed on screen. The parent's
3697 * transform makes more sense to send since it's information about how the
3698 * layer is placed on screen. This transform is used by input to determine
3699 * how to go from screen space back to window space.
3700 */
3701ui::Transform Layer::getInputTransform() const {
3702 if (!hasBufferOrSidebandStream()) {
3703 return getTransform();
3704 }
3705 sp<Layer> parent = mDrawingParent.promote();
3706 if (parent == nullptr) {
3707 return ui::Transform();
3708 }
3709
3710 return parent->getTransform();
3711}
3712
3713/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003714 * Returns the bounds used to fill the input frame and the touchable region.
3715 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003716 * Similar to getInputTransform, we need to update the bounds to include the transform.
3717 * This is because bounds don't include the buffer transform, where the input assumes
3718 * that's already included.
3719 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003720std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3721 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3722 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3723 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3724 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3725 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003726 }
3727
Vishnu Nairfed7c122023-03-18 01:54:43 +00003728 bool inputBoundsValid = croppedBufferSize.isValid();
3729 if (!inputBoundsValid) {
3730 /**
3731 * Input bounds are based on the layer crop or buffer size. But if we are using
3732 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3733 * we can use the parent bounds as the input bounds if the layer does not have buffer
3734 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3735 * use the parent bounds. A layer without a buffer can get input. So when a window is
3736 * initially added, its touchable region can fill its parent layer bounds and that can
3737 * have negative consequences.
3738 */
3739 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003740 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003741
3742 // Clamp surface inset to the input bounds.
3743 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3744 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3745 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3746
3747 // Apply the insets to the input bounds.
3748 inputBounds.left += xSurfaceInset;
3749 inputBounds.top += ySurfaceInset;
3750 inputBounds.right -= xSurfaceInset;
3751 inputBounds.bottom -= ySurfaceInset;
3752
3753 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003754}
3755
Ady Abraham005398b2023-06-05 13:59:41 -07003756bool Layer::isSimpleBufferUpdate(const layer_state_t& s) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003757 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3758
3759 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3760 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3761 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3762 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3763 layer_state_t::eReparent;
3764
Patrick Williamsbb25f802022-08-30 23:02:34 +00003765 if ((s.what & requiredFlags) != requiredFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003766 ATRACE_FORMAT_INSTANT("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3767 (s.what | requiredFlags) & ~s.what);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003768 return false;
3769 }
3770
3771 if (s.what & deniedFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003772 ATRACE_FORMAT_INSTANT("%s: false [has denied flags 0x%" PRIx64 "]", __func__,
3773 s.what & deniedFlags);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003774 return false;
3775 }
3776
Patrick Williamsbb25f802022-08-30 23:02:34 +00003777 if (s.what & layer_state_t::ePositionChanged) {
3778 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
Ady Abraham005398b2023-06-05 13:59:41 -07003779 ATRACE_FORMAT_INSTANT("%s: false [ePositionChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003780 return false;
3781 }
3782 }
3783
3784 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003785 if (mDrawingState.color.a != s.color.a) {
Ady Abraham005398b2023-06-05 13:59:41 -07003786 ATRACE_FORMAT_INSTANT("%s: false [eAlphaChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003787 return false;
3788 }
3789 }
3790
3791 if (s.what & layer_state_t::eColorTransformChanged) {
3792 if (mDrawingState.colorTransform != s.colorTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003793 ATRACE_FORMAT_INSTANT("%s: false [eColorTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003794 return false;
3795 }
3796 }
3797
3798 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003799 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Ady Abraham005398b2023-06-05 13:59:41 -07003800 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundColorChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003801 return false;
3802 }
3803 }
3804
3805 if (s.what & layer_state_t::eMatrixChanged) {
3806 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3807 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3808 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3809 mRequestedTransform.dsdy() != s.matrix.dsdy) {
Ady Abraham005398b2023-06-05 13:59:41 -07003810 ATRACE_FORMAT_INSTANT("%s: false [eMatrixChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003811 return false;
3812 }
3813 }
3814
3815 if (s.what & layer_state_t::eCornerRadiusChanged) {
3816 if (mDrawingState.cornerRadius != s.cornerRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003817 ATRACE_FORMAT_INSTANT("%s: false [eCornerRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003818 return false;
3819 }
3820 }
3821
3822 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3823 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
Ady Abraham005398b2023-06-05 13:59:41 -07003824 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003825 return false;
3826 }
3827 }
3828
Vishnu Nairbbceb462022-10-10 04:52:13 +00003829 if (s.what & layer_state_t::eBufferTransformChanged) {
3830 if (mDrawingState.bufferTransform != s.bufferTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003831 ATRACE_FORMAT_INSTANT("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003832 return false;
3833 }
3834 }
3835
3836 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3837 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
Ady Abraham005398b2023-06-05 13:59:41 -07003838 ATRACE_FORMAT_INSTANT("%s: false [eTransformToDisplayInverseChanged changed]",
3839 __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003840 return false;
3841 }
3842 }
3843
3844 if (s.what & layer_state_t::eCropChanged) {
3845 if (mDrawingState.crop != s.crop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003846 ATRACE_FORMAT_INSTANT("%s: false [eCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003847 return false;
3848 }
3849 }
3850
3851 if (s.what & layer_state_t::eDataspaceChanged) {
3852 if (mDrawingState.dataspace != s.dataspace) {
Ady Abraham005398b2023-06-05 13:59:41 -07003853 ATRACE_FORMAT_INSTANT("%s: false [eDataspaceChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003854 return false;
3855 }
3856 }
3857
3858 if (s.what & layer_state_t::eHdrMetadataChanged) {
3859 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
Ady Abraham005398b2023-06-05 13:59:41 -07003860 ATRACE_FORMAT_INSTANT("%s: false [eHdrMetadataChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003861 return false;
3862 }
3863 }
3864
3865 if (s.what & layer_state_t::eSidebandStreamChanged) {
3866 if (mDrawingState.sidebandStream != s.sidebandStream) {
Ady Abraham005398b2023-06-05 13:59:41 -07003867 ATRACE_FORMAT_INSTANT("%s: false [eSidebandStreamChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003868 return false;
3869 }
3870 }
3871
3872 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3873 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
Ady Abraham005398b2023-06-05 13:59:41 -07003874 ATRACE_FORMAT_INSTANT("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003875 return false;
3876 }
3877 }
3878
3879 if (s.what & layer_state_t::eShadowRadiusChanged) {
3880 if (mDrawingState.shadowRadius != s.shadowRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003881 ATRACE_FORMAT_INSTANT("%s: false [eShadowRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003882 return false;
3883 }
3884 }
3885
3886 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3887 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
Ady Abraham005398b2023-06-05 13:59:41 -07003888 ATRACE_FORMAT_INSTANT("%s: false [eFixedTransformHintChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003889 return false;
3890 }
3891 }
3892
3893 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3894 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
Ady Abraham005398b2023-06-05 13:59:41 -07003895 ATRACE_FORMAT_INSTANT("%s: false [eTrustedOverlayChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003896 return false;
3897 }
3898 }
3899
3900 if (s.what & layer_state_t::eStretchChanged) {
3901 StretchEffect temp = s.stretchEffect;
3902 temp.sanitize();
3903 if (mDrawingState.stretchEffect != temp) {
Ady Abraham005398b2023-06-05 13:59:41 -07003904 ATRACE_FORMAT_INSTANT("%s: false [eStretchChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003905 return false;
3906 }
3907 }
3908
3909 if (s.what & layer_state_t::eBufferCropChanged) {
3910 if (mDrawingState.bufferCrop != s.bufferCrop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003911 ATRACE_FORMAT_INSTANT("%s: false [eBufferCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003912 return false;
3913 }
3914 }
3915
3916 if (s.what & layer_state_t::eDestinationFrameChanged) {
3917 if (mDrawingState.destinationFrame != s.destinationFrame) {
Ady Abraham005398b2023-06-05 13:59:41 -07003918 ATRACE_FORMAT_INSTANT("%s: false [eDestinationFrameChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003919 return false;
3920 }
3921 }
3922
3923 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3924 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
Ady Abraham005398b2023-06-05 13:59:41 -07003925 ATRACE_FORMAT_INSTANT("%s: false [eDimmingEnabledChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003926 return false;
3927 }
3928 }
3929
John Reck68796592023-01-25 13:47:12 -05003930 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07003931 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
3932 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
Ady Abraham005398b2023-06-05 13:59:41 -07003933 ATRACE_FORMAT_INSTANT("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05003934 return false;
3935 }
3936 }
3937
Patrick Williamsbb25f802022-08-30 23:02:34 +00003938 return true;
3939}
3940
Vishnu Naire14c6b32022-08-06 04:20:15 +00003941sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003942 // 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 +00003943 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003944}
3945
Vishnu Naire14c6b32022-08-06 04:20:15 +00003946const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003947 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003948}
3949
Vishnu Naire14c6b32022-08-06 04:20:15 +00003950LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003951 return mSnapshot.get();
3952}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003953
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003954std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3955 return std::move(mSnapshot);
3956}
3957
3958void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3959 mSnapshot = std::move(snapshot);
3960}
3961
Patrick Williamsbb25f802022-08-30 23:02:34 +00003962const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003963 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003964}
3965
Patrick Williams7584c6a2022-10-29 02:10:58 +00003966sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003967 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003968 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3969 return result;
3970}
3971
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003972sp<LayerFE> Layer::getCompositionEngineLayerFE(
3973 const frontend::LayerHierarchy::TraversalPath& path) {
3974 for (auto& [p, layerFE] : mLayerFEs) {
3975 if (p == path) {
3976 return layerFE;
3977 }
3978 }
3979 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3980 mLayerFEs.emplace_back(path, layerFE);
3981 return layerFE;
3982}
3983
Patrick Williamsbb25f802022-08-30 23:02:34 +00003984void Layer::useSurfaceDamage() {
3985 if (mFlinger->mForceFullDamage) {
3986 surfaceDamageRegion = Region::INVALID_REGION;
3987 } else {
3988 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3989 }
3990}
3991
3992void Layer::useEmptyDamage() {
3993 surfaceDamageRegion.clear();
3994}
3995
3996bool Layer::isOpaque(const Layer::State& s) const {
3997 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3998 // layer's opaque flag.
3999 if (!hasSomethingToDraw()) {
4000 return false;
4001 }
4002
4003 // if the layer has the opaque flag, then we're always opaque
4004 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
4005 return true;
4006 }
4007
4008 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004009 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004010 return true;
4011 }
4012
4013 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
4014 return fillsColor() && getAlpha() == 1.0_hf;
4015}
4016
4017bool Layer::canReceiveInput() const {
4018 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
4019}
4020
4021bool Layer::isVisible() const {
4022 if (!hasSomethingToDraw()) {
4023 return false;
4024 }
4025
4026 if (isHiddenByPolicy()) {
4027 return false;
4028 }
4029
4030 return getAlpha() > 0.0f || hasBlur();
4031}
4032
Leon Scroggins III5b581492023-10-31 14:29:41 -04004033void Layer::onCompositionPresented(const DisplayDevice* display,
4034 const std::shared_ptr<FenceTime>& glDoneFence,
4035 const std::shared_ptr<FenceTime>& presentFence,
4036 const CompositorTiming& compositorTiming) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004037 // mFrameLatencyNeeded is true when a new frame was latched for the
4038 // composition.
4039 if (!mBufferInfo.mFrameLatencyNeeded) return;
4040
4041 for (const auto& handle : mDrawingState.callbackHandles) {
4042 handle->gpuCompositionDoneFence = glDoneFence;
4043 handle->compositorTiming = compositorTiming;
4044 }
4045
4046 // Update mFrameTracker.
4047 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
4048 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
4049
4050 const int32_t layerId = getSequence();
4051 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
4052
4053 const auto outputLayer = findOutputLayerForDisplay(display);
4054 if (outputLayer && outputLayer->requiresClientComposition()) {
4055 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
4056 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4057 clientCompositionTimestamp,
4058 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
4059 // Update the SurfaceFrames in the drawing state
4060 if (mDrawingState.bufferSurfaceFrameTX) {
4061 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
4062 }
4063 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
4064 surfaceFrame->setGpuComposition();
4065 }
4066 }
4067
4068 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
4069 if (frameReadyFence->isValid()) {
4070 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
4071 } else {
4072 // There was no fence for this frame, so assume that it was ready
4073 // to be presented at the desired present time.
4074 mFrameTracker.setFrameReadyTime(desiredPresentTime);
4075 }
4076
4077 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08004078 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004079 const std::optional<Fps> renderRate =
4080 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
4081
Alec Mouri7c1d8b52023-08-29 20:14:46 +00004082 const auto vote = frameRateToSetFrameRateVotePayload(getFrameRateForLayerTree());
Patrick Williamsbb25f802022-08-30 23:02:34 +00004083 const auto gameMode = getGameMode();
4084
4085 if (presentFence->isValid()) {
4086 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
4087 refreshRate, renderRate, vote, gameMode);
4088 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4089 presentFence,
4090 FrameTracer::FrameEvent::PRESENT_FENCE);
4091 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
4092 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
4093 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04004094 // The HWC doesn't support present fences, so use the present timestamp instead.
4095 const nsecs_t presentTimestamp =
4096 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
4097
4098 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
4099 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
4100 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
4101
Patrick Williamsbb25f802022-08-30 23:02:34 +00004102 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
4103 refreshRate, renderRate, vote, gameMode);
4104 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
4105 mCurrentFrameNumber, actualPresentTime,
4106 FrameTracer::FrameEvent::PRESENT_FENCE);
4107 mFrameTracker.setActualPresentTime(actualPresentTime);
4108 }
4109 }
4110
4111 mFrameTracker.advanceFrame();
4112 mBufferInfo.mFrameLatencyNeeded = false;
4113}
4114
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004115bool Layer::willReleaseBufferOnLatch() const {
4116 return !mDrawingState.buffer && mBufferInfo.mBuffer;
4117}
4118
Patrick Williamsbb25f802022-08-30 23:02:34 +00004119bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00004120 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
4121 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
4122}
4123
4124bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004125 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
4126 getDrawingState().frameNumber);
4127
4128 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
4129
4130 if (refreshRequired) {
4131 return refreshRequired;
4132 }
4133
4134 // If the head buffer's acquire fence hasn't signaled yet, return and
4135 // try again later
4136 if (!fenceHasSignaled()) {
4137 ATRACE_NAME("!fenceHasSignaled()");
4138 mFlinger->onLayerUpdate();
4139 return false;
4140 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00004141 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004142
4143 // Capture the old state of the layer for comparisons later
4144 BufferInfo oldBufferInfo = mBufferInfo;
4145 const bool oldOpacity = isOpaque(mDrawingState);
4146 mPreviousFrameNumber = mCurrentFrameNumber;
4147 mCurrentFrameNumber = mDrawingState.frameNumber;
4148 gatherBufferInfo();
4149
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004150 if (mBufferInfo.mBuffer) {
4151 // We latched a buffer that will be presented soon. Clear the previously presented layer
4152 // stack list.
4153 mPreviouslyPresentedLayerStacks.clear();
4154 }
4155
4156 if (mDrawingState.buffer == nullptr) {
4157 const bool bufferReleased = oldBufferInfo.mBuffer != nullptr;
4158 recomputeVisibleRegions = bufferReleased;
4159 return bufferReleased;
4160 }
4161
Patrick Williamsbb25f802022-08-30 23:02:34 +00004162 if (oldBufferInfo.mBuffer == nullptr) {
4163 // the first time we receive a buffer, we need to trigger a
4164 // geometry invalidation.
4165 recomputeVisibleRegions = true;
4166 }
4167
4168 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
4169 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
4170 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
4171 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
4172 recomputeVisibleRegions = true;
4173 }
4174
4175 if (oldBufferInfo.mBuffer != nullptr) {
4176 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
4177 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
4178 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
4179 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
4180 recomputeVisibleRegions = true;
4181 }
4182 }
4183
4184 if (oldOpacity != isOpaque(mDrawingState)) {
4185 recomputeVisibleRegions = true;
4186 }
4187
4188 return true;
4189}
4190
4191bool Layer::hasReadyFrame() const {
4192 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4193}
4194
4195bool Layer::isProtected() const {
4196 return (mBufferInfo.mBuffer != nullptr) &&
4197 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4198}
4199
Patrick Williamsbb25f802022-08-30 23:02:34 +00004200void Layer::latchAndReleaseBuffer() {
4201 if (hasReadyFrame()) {
4202 bool ignored = false;
4203 latchBuffer(ignored, systemTime());
4204 }
4205 releasePendingBuffer(systemTime());
4206}
4207
4208PixelFormat Layer::getPixelFormat() const {
4209 return mBufferInfo.mPixelFormat;
4210}
4211
4212bool Layer::getTransformToDisplayInverse() const {
4213 return mBufferInfo.mTransformToDisplayInverse;
4214}
4215
4216Rect Layer::getBufferCrop() const {
4217 // this is the crop rectangle that applies to the buffer
4218 // itself (as opposed to the window)
4219 if (!mBufferInfo.mCrop.isEmpty()) {
4220 // if the buffer crop is defined, we use that
4221 return mBufferInfo.mCrop;
4222 } else if (mBufferInfo.mBuffer != nullptr) {
4223 // otherwise we use the whole buffer
4224 return mBufferInfo.mBuffer->getBounds();
4225 } else {
4226 // if we don't have a buffer yet, we use an empty/invalid crop
4227 return Rect();
4228 }
4229}
4230
4231uint32_t Layer::getBufferTransform() const {
4232 return mBufferInfo.mTransform;
4233}
4234
4235ui::Dataspace Layer::getDataSpace() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004236 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4237}
4238
Alec Mouri89f5d4e2023-10-20 17:12:49 +00004239bool Layer::isFrontBuffered() const {
4240 if (mBufferInfo.mBuffer == nullptr) {
4241 return false;
4242 }
4243
4244 return mBufferInfo.mBuffer->getUsage() & AHARDWAREBUFFER_USAGE_FRONT_BUFFER;
4245}
4246
Patrick Williamsbb25f802022-08-30 23:02:34 +00004247ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4248 ui::Dataspace updatedDataspace = dataspace;
4249 // translate legacy dataspaces to modern dataspaces
4250 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00004251 // Treat unknown dataspaces as V0_sRGB
4252 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00004253 case ui::Dataspace::SRGB:
4254 updatedDataspace = ui::Dataspace::V0_SRGB;
4255 break;
4256 case ui::Dataspace::SRGB_LINEAR:
4257 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4258 break;
4259 case ui::Dataspace::JFIF:
4260 updatedDataspace = ui::Dataspace::V0_JFIF;
4261 break;
4262 case ui::Dataspace::BT601_625:
4263 updatedDataspace = ui::Dataspace::V0_BT601_625;
4264 break;
4265 case ui::Dataspace::BT601_525:
4266 updatedDataspace = ui::Dataspace::V0_BT601_525;
4267 break;
4268 case ui::Dataspace::BT709:
4269 updatedDataspace = ui::Dataspace::V0_BT709;
4270 break;
4271 default:
4272 break;
4273 }
4274
4275 return updatedDataspace;
4276}
4277
4278sp<GraphicBuffer> Layer::getBuffer() const {
4279 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4280}
4281
Vishnu Nairb76d99a2023-03-19 18:22:31 -07004282void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4283 mTransformHintLegacy = getFixedTransformHint();
4284 if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4285 mTransformHintLegacy = displayTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004286 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004287 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004288}
4289
4290const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4291 return mBufferInfo.mBuffer;
4292}
4293
4294bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004295 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004296 return false;
4297 }
4298
4299 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004300 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004301 mDrawingState.modified = true;
4302 setTransactionFlags(eTransactionNeeded);
4303 return true;
4304}
4305
4306bool Layer::fillsColor() const {
4307 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4308 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4309}
4310
4311bool Layer::hasBlur() const {
4312 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4313}
4314
Vishnu Nairba354102022-08-01 00:14:18 +00004315void Layer::updateSnapshot(bool updateGeometry) {
4316 if (!getCompositionEngineLayerFE()) {
4317 return;
4318 }
4319
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004320 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004321 if (updateGeometry) {
4322 prepareBasicGeometryCompositionState();
4323 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004324 snapshot->roundedCorner = getRoundedCornerState();
4325 snapshot->stretchEffect = getStretchEffect();
4326 snapshot->transformedBounds = mScreenBounds;
4327 if (mEffectiveShadowRadius > 0.f) {
4328 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4329
4330 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4331 // it if transparent regions are present. This may not be necessary since shadows are
4332 // typically cast by layers without transparent regions.
4333 snapshot->shadowSettings.boundaries = mBounds;
4334
4335 const float casterAlpha = snapshot->alpha;
4336 const bool casterIsOpaque =
4337 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4338
4339 // If the casting layer is translucent, we need to fill in the shadow underneath the
4340 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4341 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4342 snapshot->shadowSettings.ambientColor *= casterAlpha;
4343 snapshot->shadowSettings.spotColor *= casterAlpha;
4344 }
4345 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004346 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004347 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004348 snapshot->layerOpaqueFlagSet =
4349 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004350 sp<Layer> p = mDrawingParent.promote();
4351 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004352 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004353 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004354 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004355 }
4356 snapshot->bufferSize = getBufferSize(mDrawingState);
4357 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004358 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004359 preparePerFrameCompositionState();
4360}
4361
Vishnu Naire14c6b32022-08-06 04:20:15 +00004362void Layer::updateChildrenSnapshots(bool updateGeometry) {
4363 for (const sp<Layer>& child : mDrawingChildren) {
4364 child->updateSnapshot(updateGeometry);
4365 child->updateChildrenSnapshots(updateGeometry);
4366 }
4367}
4368
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004369void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4370 mSnapshot->layerMetadata = parentMetadata;
4371 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4372 for (const sp<Layer>& child : mDrawingChildren) {
4373 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4374 }
4375}
4376
4377void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4378 std::unordered_set<Layer*>& visited) {
4379 if (visited.find(this) != visited.end()) {
4380 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4381 return;
4382 }
4383 visited.insert(this);
4384
4385 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4386
4387 if (mDrawingState.zOrderRelatives.empty()) {
4388 return;
4389 }
4390 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4391 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4392 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4393 sp<Layer> relative = weakRelative.promote();
4394 if (!relative) {
4395 continue;
4396 }
4397 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4398 }
4399}
4400
Chavi Weingarten328a8312023-01-26 21:17:52 +00004401bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004402 TrustedPresentationListener const& listener) {
4403 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4404 mTrustedPresentationListener = listener;
4405 mTrustedPresentationThresholds = thresholds;
4406 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4407 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4408 mFlinger->mNumTrustedPresentationListeners++;
4409 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4410 mFlinger->mNumTrustedPresentationListeners--;
4411 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004412
4413 // Reset trusted presentation states to ensure we start the time again.
4414 mEnteredTrustedPresentationStateTime = -1;
4415 mLastReportedTrustedPresentationState = false;
4416 mLastComputedTrustedPresentationState = false;
4417
4418 // If there's a new trusted presentation listener, the code needs to go through the composite
4419 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4420 // we're already in the requested state.
4421 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004422}
4423
Vishnu Naira156f482023-02-22 00:23:38 +00004424void Layer::updateLastLatchTime(nsecs_t latchTime) {
4425 mLastLatchTime = latchTime;
4426}
4427
Arthur Hung69f95222023-10-04 07:39:02 +00004428void Layer::setIsSmallDirty(const Region& damageRegion,
4429 const ui::Transform& layerToDisplayTransform) {
4430 mSmallDirty = false;
Arthur Hungc70bee22023-06-02 01:35:52 +00004431 if (!mFlinger->mScheduler->supportSmallDirtyDetection()) {
4432 return;
4433 }
4434
4435 if (mWindowType != WindowInfo::Type::APPLICATION &&
4436 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
4437 return;
4438 }
Arthur Hung69f95222023-10-04 07:39:02 +00004439
4440 Rect bounds = damageRegion.getBounds();
Arthur Hungc70bee22023-06-02 01:35:52 +00004441 if (!bounds.isValid()) {
4442 return;
4443 }
4444
Arthur Hung69f95222023-10-04 07:39:02 +00004445 // Transform to screen space.
4446 bounds = layerToDisplayTransform.transform(bounds);
4447
Arthur Hungc70bee22023-06-02 01:35:52 +00004448 // If the damage region is a small dirty, this could give the hint for the layer history that
4449 // it could suppress the heuristic rate when calculating.
Tony Huangf3621102023-09-04 17:14:22 +08004450 mSmallDirty = mFlinger->mScheduler->isSmallDirtyArea(mOwnerAppId,
Tony Huang9ac5e6e2023-08-24 09:01:44 +00004451 bounds.getWidth() * bounds.getHeight());
Arthur Hungc70bee22023-06-02 01:35:52 +00004452}
4453
Arthur Hung69f95222023-10-04 07:39:02 +00004454void Layer::setIsSmallDirty(frontend::LayerSnapshot* snapshot) {
4455 setIsSmallDirty(snapshot->surfaceDamage, snapshot->localTransform);
4456 snapshot->isSmallDirty = mSmallDirty;
4457}
4458
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004459} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004460
4461#if defined(__gl_h_)
4462#error "don't include gl/gl.h in this file"
4463#endif
4464
4465#if defined(__gl2_h_)
4466#error "don't include gl2/gl2.h in this file"
4467#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004468
4469// TODO(b/129481165): remove the #pragma below and fix conversion issues
4470#pragma clang diagnostic pop // ignored "-Wconversion"