blob: 95e1a2f0d3f0e903a408bdc7b57d7a1ff897f933 [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>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070052#include <ui/DataspaceUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080053#include <ui/DebugUtils.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000054#include <ui/FloatRect.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080055#include <ui/GraphicBuffer.h>
56#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
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700142Layer::Layer(const 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),
151 mTextureName(args.textureName),
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000152 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000153 ALOGV("Creating Layer %s", getDebugName());
154
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700155 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700156 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
157 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
158 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700159 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
160 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700161 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700162 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700163 mDrawingState.z = 0;
164 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700165 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700166 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700167 mDrawingState.transform.set(0, 0);
168 mDrawingState.frameNumber = 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;
174 mDrawingState.crop.makeInvalid();
175 mDrawingState.acquireFence = sp<Fence>::make(-1);
176 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
Alec Mouri74c7ae12023-03-26 02:57:47 +0000177 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Robert Carr6a160312021-05-17 12:08:20 -0700178 mDrawingState.hdrMetadata.validTypes = 0;
179 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
180 mDrawingState.cornerRadius = 0.0f;
181 mDrawingState.backgroundBlurRadius = 0;
182 mDrawingState.api = -1;
183 mDrawingState.hasColorTransform = false;
184 mDrawingState.colorSpaceAgnostic = false;
185 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
186 mDrawingState.metadata = args.metadata;
187 mDrawingState.shadowRadius = 0.f;
188 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
189 mDrawingState.frameTimelineInfo = {};
190 mDrawingState.postTime = -1;
191 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000192 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700193 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700194 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000195 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
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;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000209
210 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
211 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
212 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000213
214 mSnapshot->sequence = sequence;
215 mSnapshot->name = getDebugName();
216 mSnapshot->textureName = mTextureName;
217 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 }
238 if (!isClone()) {
239 // The original layer and the clone layer share the same texture. Therefore, only one of
240 // the layers, in this case the original layer, needs to handle the deletion. The original
241 // layer and the clone should be removed at the same time so there shouldn't be any issue
242 // with the clone layer trying to use the deleted texture.
243 mFlinger->deleteTextureAsync(mTextureName);
244 }
245 const int32_t layerId = getSequence();
246 mFlinger->mTimeStats->onDestroy(layerId);
247 mFlinger->mFrameTracer->onDestroy(layerId);
248
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000249 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700250 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700251
252 if (mDrawingState.sidebandStream != nullptr) {
253 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
254 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700255 if (mHadClonedChild) {
Vishnu Nair3be61902023-04-26 19:47:29 -0700256 auto& roots = mFlinger->mLayerMirrorRoots;
257 roots.erase(std::remove(roots.begin(), roots.end(), this), roots.end());
Robert Carr6a0382d2021-07-01 15:57:17 -0700258 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000259 if (hasTrustedPresentationListener()) {
260 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000261 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000262 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700263}
264
Mathias Agopian13127d82013-03-05 17:47:11 -0800265// ---------------------------------------------------------------------------
266// callbacks
267// ---------------------------------------------------------------------------
268
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700269void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700270 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700271 return;
272 }
Robert Carr2e102c92018-10-23 12:11:15 -0700273
Robert Carr6a160312021-05-17 12:08:20 -0700274 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700275 if (strongRelative == nullptr) {
276 setZOrderRelativeOf(nullptr);
277 return;
278 }
279
280 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700281 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700282 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800283 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700284 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700285}
286
287void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700288 if (!mRemovedFromDrawingState) {
289 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700290 mFlinger->mScheduler->deregisterLayer(this);
291 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000292 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000293
Ady Abrahamd11bade2022-08-01 16:18:03 -0700294 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700295}
Chia-I Wu38512252017-05-17 14:36:16 -0700296
chaviw68d4dab2020-06-08 15:07:32 -0700297sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000298 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700299 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700300 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700301 }
302 return parent->getRootLayer();
303}
304
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700305void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700306 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
307 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700308 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700309
Josh Gao194ff392022-09-08 16:19:29 -0700310 REQUIRE_MUTEX(mFlinger->mStateLock);
311 traverse(LayerVector::StateSet::Current,
312 [&](Layer* layer) REQUIRES(layer->mFlinger->mStateLock) {
313 layer->removeFromCurrentState();
314 layer->removeRelativeZ(layersInTree);
315 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700316}
317
chaviw61626f22018-11-15 16:26:27 -0800318void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700319 if (mRemovedFromDrawingState) {
320 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700321 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700322 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700323 }
chaviw61626f22018-11-15 16:26:27 -0800324
325 for (const auto& child : mCurrentChildren) {
326 child->addToCurrentState();
327 }
328}
329
Mathias Agopian13127d82013-03-05 17:47:11 -0800330// ---------------------------------------------------------------------------
331// set-up
332// ---------------------------------------------------------------------------
333
chaviw13fdc492017-06-27 12:40:18 -0700334bool Layer::getPremultipledAlpha() const {
335 return mPremultipliedAlpha;
336}
337
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700338sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800339 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700340 if (mGetHandleCalled) {
341 ALOGE("Get handle called twice" );
342 return nullptr;
343 }
344 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700345 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000346 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800347}
348
349// ---------------------------------------------------------------------------
350// h/w composer set-up
351// ---------------------------------------------------------------------------
352
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700353static Rect reduce(const Rect& win, const Region& exclude) {
354 if (CC_LIKELY(exclude.isEmpty())) {
355 return win;
356 }
357 if (exclude.isRect()) {
358 return win.reduce(exclude.getBounds());
359 }
360 return Region(win).subtract(exclude).getBounds();
361}
362
Dan Stoza80d61162017-12-20 15:57:52 -0800363static FloatRect reduce(const FloatRect& win, const Region& exclude) {
364 if (CC_LIKELY(exclude.isEmpty())) {
365 return win;
366 }
367 // Convert through Rect (by rounding) for lack of FloatRegion
368 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
369}
370
Vishnu Nair4351ad52019-02-11 14:13:02 -0800371Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800372 if (!reduceTransparentRegion) {
373 return Rect{mScreenBounds};
374 }
375
376 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800377 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800378 // Transform to screen space.
379 bounds = t.transform(bounds);
380 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700381}
382
Vishnu Nair4351ad52019-02-11 14:13:02 -0800383FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000384 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800385 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700386}
387
Vishnu Nairf0c28512019-02-08 12:40:28 -0800388FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
389 // Subtract the transparent region and snap to the bounds.
390 return reduce(mBounds, activeTransparentRegion);
391}
392
Chavi Weingarten076acac2023-01-19 17:20:43 +0000393// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000394void Layer::updateTrustedPresentationState(const DisplayDevice* display,
395 const frontend::LayerSnapshot* snapshot,
396 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000397 if (!hasTrustedPresentationListener()) {
398 return;
399 }
400 const bool lastState = mLastComputedTrustedPresentationState;
401 mLastComputedTrustedPresentationState = false;
402
403 if (!leaveState) {
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000404 const auto outputLayer = findOutputLayerForDisplay(display, snapshot->path);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000405 if (outputLayer != nullptr) {
406 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
407 Region coveredRegion =
408 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
409 mLastComputedTrustedPresentationState =
410 computeTrustedPresentationState(snapshot->geomLayerBounds,
411 snapshot->sourceBounds(), coveredRegion,
412 snapshot->transformedBounds,
413 snapshot->alpha,
414 snapshot->geomLayerTransform,
415 mTrustedPresentationThresholds);
416 } else {
417 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
418 "TrustedPresentationState",
419 getDebugName());
420 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000421 }
422 }
423 const bool newState = mLastComputedTrustedPresentationState;
424 if (lastState && !newState) {
425 // We were in the trusted presentation state, but now we left it,
426 // emit the callback if needed
427 if (mLastReportedTrustedPresentationState) {
428 mLastReportedTrustedPresentationState = false;
429 mTrustedPresentationListener.invoke(false);
430 }
431 // Reset the timer
432 mEnteredTrustedPresentationStateTime = -1;
433 } else if (!lastState && newState) {
434 // We were not in the trusted presentation state, but we entered it, begin the timer
435 // and make sure this gets called at least once more!
436 mEnteredTrustedPresentationStateTime = time_in_ms;
437 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
438 }
439
440 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
441 if (!mLastReportedTrustedPresentationState && newState &&
442 (time_in_ms - mEnteredTrustedPresentationStateTime >
443 mTrustedPresentationThresholds.stabilityRequirementMs)) {
444 mLastReportedTrustedPresentationState = true;
445 mTrustedPresentationListener.invoke(true);
446 }
447}
448
449/**
450 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
451 * of how the parameters and thresholds are interpreted. The general spirit is
452 * to produce an upper bound on the amount of the buffer which was presented.
453 */
454bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
455 const Region& coveredRegion,
456 const FloatRect& screenBounds, float alpha,
457 const ui::Transform& effectiveTransform,
458 const TrustedPresentationThresholds& thresholds) {
459 if (alpha < thresholds.minAlpha) {
460 return false;
461 }
462 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
463 return false;
464 }
465 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
466 return false;
467 }
468
469 const float sx = effectiveTransform.dsdx();
470 const float sy = effectiveTransform.dsdy();
471 float fractionRendered = std::min(sx * sy, 1.0f);
472
473 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
474 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
475 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
476
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000477 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
478 // Compute the size of all the rects since they may be disconnected.
479 float coveredSize = 0;
480 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
481 float size = rect->width() * rect->height();
482 coveredSize += size;
483 }
484
485 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000486
487 if (fractionRendered < thresholds.minFractionRendered) {
488 return false;
489 }
490
491 return true;
492}
493
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700494void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
495 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800496 const State& s(getDrawingState());
497
498 // Calculate effective layer transform
499 mEffectiveTransform = parentTransform * getActiveTransform(s);
500
Garfield Tan2c1782c2022-02-16 15:25:05 -0800501 if (CC_UNLIKELY(!isTransformValid())) {
502 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
503 getDebugName());
504 return;
505 }
506
Vishnu Nair4351ad52019-02-11 14:13:02 -0800507 // Transform parent bounds to layer space
508 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
509
Vishnu Nairc652ff82019-03-15 12:48:54 -0700510 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800511 mSourceBounds = computeSourceBounds(parentBounds);
512
513 // Calculate bounds by croping diplay frame with layer crop and parent bounds
514 FloatRect bounds = mSourceBounds;
515 const Rect layerCrop = getCrop(s);
516 if (!layerCrop.isEmpty()) {
517 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
518 }
519 bounds = bounds.intersect(parentBounds);
520
521 mBounds = bounds;
522 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700523
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700524 // Use the layer's own shadow radius if set. Otherwise get the radius from
525 // parent.
526 if (s.shadowRadius > 0.f) {
527 mEffectiveShadowRadius = s.shadowRadius;
528 } else {
529 mEffectiveShadowRadius = parentShadowRadius;
530 }
531
532 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
533 // don't pass it to its children.
534 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
535
Vishnu Nair4351ad52019-02-11 14:13:02 -0800536 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700537 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800538 }
Vishnu Nairba354102022-08-01 00:14:18 +0000539
540 if (mPotentialCursor) {
541 prepareCursorCompositionState();
542 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800543}
544
Vishnu Nair60356342018-11-13 13:00:45 -0800545Rect Layer::getCroppedBufferSize(const State& s) const {
546 Rect size = getBufferSize(s);
547 Rect crop = getCrop(s);
548 if (!crop.isEmpty() && size.isValid()) {
549 size.intersect(crop, &size);
550 } else if (!crop.isEmpty()) {
551 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700552 }
Vishnu Nair60356342018-11-13 13:00:45 -0800553 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800554}
555
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700556void Layer::setupRoundedCornersCropCoordinates(Rect win,
557 const FloatRect& roundedCornersCrop) const {
558 // Translate win by the rounded corners rect coordinates, to have all values in
559 // layer coordinate space.
560 win.left -= roundedCornersCrop.left;
561 win.right -= roundedCornersCrop.left;
562 win.top -= roundedCornersCrop.top;
563 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700564}
565
Lloyd Piquede196652020-01-22 17:29:58 -0800566void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800567 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800568 const auto alpha = static_cast<float>(getAlpha());
569 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700570 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800571
572 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
573 if (!opaque || alpha != 1.0f) {
574 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
575 : Hwc2::IComposerClient::BlendMode::COVERAGE;
576 }
577
Alec Mourif4af03e2023-02-11 00:25:24 +0000578 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000579 auto* snapshot = editLayerSnapshot();
580 snapshot->outputFilter = getOutputFilter();
581 snapshot->isVisible = isVisible();
582 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
583 snapshot->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800584
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000585 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800586 contentDirty = false;
587
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000588 snapshot->geomLayerBounds = mBounds;
589 snapshot->geomLayerTransform = getTransform();
590 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
591 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000592 snapshot->localTransform = getActiveTransform(drawingState);
593 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000594 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
595 snapshot->alpha = alpha;
Vishnu Nairc6384702023-07-31 12:22:20 -0700596 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
597 snapshot->blurRegions = getBlurRegions();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000598 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800599}
600
Lloyd Piquede196652020-01-22 17:29:58 -0800601void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800602 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000603 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700604
Alec Mourif4af03e2023-02-11 00:25:24 +0000605 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000606 snapshot->geomBufferSize = getBufferSize(drawingState);
607 snapshot->geomContentCrop = getBufferCrop();
608 snapshot->geomCrop = getCrop(drawingState);
609 snapshot->geomBufferTransform = getBufferTransform();
610 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
611 snapshot->geomUsesSourceCrop = usesSourceCrop();
612 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800613
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000614 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800615 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
616 for (const auto& [key, mandatory] : supportedMetadata) {
617 const auto& genericLayerMetadataCompatibilityMap =
618 mFlinger->getGenericLayerMetadataKeyMap();
619 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
620 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
621 continue;
622 }
623 const uint32_t id = compatIter->second;
624
625 auto it = drawingState.metadata.mMap.find(id);
626 if (it == std::end(drawingState.metadata.mMap)) {
627 continue;
628 }
629
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000630 snapshot->metadata.emplace(key,
631 compositionengine::GenericLayerMetadataEntry{mandatory,
632 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800633 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800634}
David Sodmanba340492018-08-05 21:51:33 -0700635
Lloyd Piquede196652020-01-22 17:29:58 -0800636void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800637 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000638 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000639 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800640
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000641 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800642
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000643 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
644 snapshot->dataspace = getDataSpace();
645 snapshot->colorTransform = getColorTransform();
646 snapshot->colorTransformIsIdentity = !hasColorTransform();
647 snapshot->surfaceDamage = surfaceDamageRegion;
648 snapshot->hasProtectedContent = isProtected();
649 snapshot->dimmingEnabled = isDimmingEnabled();
Sally Qi963049b2023-03-23 14:06:21 -0700650 snapshot->currentHdrSdrRatio = getCurrentHdrSdrRatio();
651 snapshot->desiredHdrSdrRatio = getDesiredHdrSdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000652 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800653
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700654 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700655
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000656 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800657
658 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400659 // Rounded corners no longer force client composition, since we may use a
660 // hole punch so that the layer will appear to have rounded corners.
Alec Mouri994761f2023-08-04 21:50:55 +0000661 if (drawShadows() || snapshot->stretchEffect.hasEffect()) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000662 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800663 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700664 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairc6384702023-07-31 12:22:20 -0700665 snapshot->blurRegions = getBlurRegions();
666 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400667
668 // Layer framerate is used in caching decisions.
669 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
670 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000671 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000672
673 if (hasBufferOrSidebandStream()) {
674 preparePerFrameBufferCompositionState();
675 } else {
676 preparePerFrameEffectsCompositionState();
677 }
678}
679
680void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000681 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000682 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000683 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000684 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
685 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000686 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
687 return;
688 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000689 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000690 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800691 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
692 snapshot->compositionType =
693 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000694 } else {
695 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000696 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
697 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000698 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
699 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
700 }
701
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000702 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000703 snapshot->acquireFence = mBufferInfo.mFence;
704 snapshot->frameNumber = mBufferInfo.mFrameNumber;
705 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000706}
707
708void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000709 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000710 auto* snapshot = editLayerSnapshot();
711 snapshot->color = getColor();
712 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000713 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800714}
715
Lloyd Piquede196652020-01-22 17:29:58 -0800716void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800717 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000718 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000719 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800720
721 // Apply the layer's transform, followed by the display's global transform
722 // Here we're guaranteed that the layer's transform preserves rects
723 Rect win = getCroppedBufferSize(drawingState);
724 // Subtract the transparent region and snap to the bounds
725 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
726 Rect frame(getTransform().transform(bounds));
727
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000728 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800729}
730
Lloyd Piquea83776c2019-01-29 18:42:32 -0800731const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700732 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800733}
734
Mathias Agopian13127d82013-03-05 17:47:11 -0800735// ---------------------------------------------------------------------------
736// drawing...
737// ---------------------------------------------------------------------------
738
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500739aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
740 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700741 const auto outputLayer = findOutputLayerForDisplay(&display);
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000742 return getCompositionType(outputLayer);
743}
744
745aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
746 const compositionengine::OutputLayer* outputLayer) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -0800747 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500748 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800749 }
750 if (outputLayer->getState().hwc) {
751 return (*outputLayer->getState().hwc).hwcCompositionType;
752 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500753 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800754 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800755}
756
Mathias Agopian13127d82013-03-05 17:47:11 -0800757// ----------------------------------------------------------------------------
758// local state
759// ----------------------------------------------------------------------------
760
David Sodman41fdfc92017-11-06 16:09:56 -0800761bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800762 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700763 if (s.flags & layer_state_t::eLayerSecure) {
764 return true;
765 }
766
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000767 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700768 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700769}
770
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100771void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
772 std::vector<JankData>& jankData) {
773 if (mPendingJankClassifications.empty() ||
774 !mPendingJankClassifications.front()->getJankType()) {
775 return;
776 }
777
778 bool includeJankData = false;
779 for (const auto& handle : handles) {
780 for (const auto& cb : handle->callbackIds) {
781 if (cb.includeJankData) {
782 includeJankData = true;
783 break;
784 }
785 }
786
787 if (includeJankData) {
788 jankData.reserve(mPendingJankClassifications.size());
789 break;
790 }
791 }
792
793 while (!mPendingJankClassifications.empty() &&
794 mPendingJankClassifications.front()->getJankType()) {
795 if (includeJankData) {
796 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
797 mPendingJankClassifications.front();
798 jankData.emplace_back(
799 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
800 }
801 mPendingJankClassifications.pop_front();
802 }
803}
804
Mathias Agopian13127d82013-03-05 17:47:11 -0800805// ----------------------------------------------------------------------------
806// transaction
807// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800808
Vishnu Naira156f482023-02-22 00:23:38 +0000809uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700810 ATRACE_CALL();
811
Robert Carr0758e5d2021-03-11 22:15:04 -0800812 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700813 mDrawingStateModified = mDrawingState.modified;
814 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700815
Alec Mourib416efd2018-09-06 21:01:59 +0000816 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700817
Robert Carr6a160312021-05-17 12:08:20 -0700818 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800819 // invalidate and recompute the visible regions if needed
820 flags |= Layer::eVisibleRegion;
821 }
822
Robert Carr6a160312021-05-17 12:08:20 -0700823 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800824 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000825 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800826 flags |= eVisibleRegion;
827 this->contentDirty = true;
828
829 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700830 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800831 }
832
Arthur Hung9ed43392022-05-27 06:31:57 +0000833 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
834 mFlinger->mUpdateInputInfo = true;
835 }
836
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700837 commitTransaction();
Robert Carra1257842020-01-31 13:48:28 -0800838
Mathias Agopian13127d82013-03-05 17:47:11 -0800839 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800840}
841
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700842void Layer::commitTransaction() {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000843 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
844 // bufferSurfaceFrameTX will be presented in latchBuffer.
845 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
846 if (surfaceFrame->getPresentState() != PresentState::Presented) {
847 // With applyPendingStates, we could end up having presented surfaceframes from previous
848 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800849 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000850 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
851 }
852 }
Robert Carr6a160312021-05-17 12:08:20 -0700853 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700854}
855
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700856uint32_t Layer::clearTransactionFlags(uint32_t mask) {
857 const auto flags = mTransactionFlags & mask;
858 mTransactionFlags &= ~mask;
859 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800860}
861
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700862void Layer::setTransactionFlags(uint32_t mask) {
863 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800864}
865
Robert Carr1f0a16a2016-10-24 16:27:39 -0700866bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
867 ssize_t idx = mCurrentChildren.indexOf(childLayer);
868 if (idx < 0) {
869 return false;
870 }
871 if (childLayer->setLayer(z)) {
872 mCurrentChildren.removeAt(idx);
873 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800874 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700875 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800876 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700877}
878
Robert Carr503c7042017-09-27 15:06:08 -0700879bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
880 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
881 ssize_t idx = mCurrentChildren.indexOf(childLayer);
882 if (idx < 0) {
883 return false;
884 }
885 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
886 mCurrentChildren.removeAt(idx);
887 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800888 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700889 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800890 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700891}
892
Robert Carrae060832016-11-28 10:51:00 -0800893bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700894 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
895 mDrawingState.sequence++;
896 mDrawingState.z = z;
897 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700898
Robert Carra70e91c2021-06-11 13:59:52 -0700899 mFlinger->mSomeChildrenChanged = true;
900
Robert Carrdb66e622017-04-10 16:55:57 -0700901 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700902 if (mDrawingState.zOrderRelativeOf != nullptr) {
903 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700904 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700905 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700906 }
chaviw606e5cf2019-03-01 10:12:10 -0800907 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700908 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800909 setTransactionFlags(eTransactionNeeded);
910 return true;
911}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700912
Robert Carrdb66e622017-04-10 16:55:57 -0700913void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700914 mDrawingState.zOrderRelatives.remove(relative);
915 mDrawingState.sequence++;
916 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700917 setTransactionFlags(eTransactionNeeded);
918}
919
920void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700921 mDrawingState.zOrderRelatives.add(relative);
922 mDrawingState.modified = true;
923 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700924 setTransactionFlags(eTransactionNeeded);
925}
926
chaviw606e5cf2019-03-01 10:12:10 -0800927void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700928 mDrawingState.zOrderRelativeOf = relativeOf;
929 mDrawingState.sequence++;
930 mDrawingState.modified = true;
931 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700932
chaviw606e5cf2019-03-01 10:12:10 -0800933 setTransactionFlags(eTransactionNeeded);
934}
935
Robert Carr503d2bd2017-12-04 15:49:47 -0800936bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000937 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700938 if (relative == nullptr) {
939 return false;
940 }
941
Robert Carr6a160312021-05-17 12:08:20 -0700942 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
943 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800944 return false;
945 }
946
Robert Carr88b85e12022-03-21 15:47:35 -0700947 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
948 (relative->mDrawingState.zOrderRelativeOf == this)) {
949 ALOGE("Detected relative layer loop between %s and %s",
950 mName.c_str(), relative->mName.c_str());
951 ALOGE("Ignoring new call to set relative layer");
952 return false;
953 }
954
Robert Carra70e91c2021-06-11 13:59:52 -0700955 mFlinger->mSomeChildrenChanged = true;
956
Robert Carr6a160312021-05-17 12:08:20 -0700957 mDrawingState.sequence++;
958 mDrawingState.modified = true;
959 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700960
Robert Carr6a160312021-05-17 12:08:20 -0700961 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700962 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700963 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700964 }
chaviw606e5cf2019-03-01 10:12:10 -0800965 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700966 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700967
968 setTransactionFlags(eTransactionNeeded);
969
970 return true;
971}
972
Winson Chunga30f7c92021-06-29 15:42:56 -0700973bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
974 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
975 mDrawingState.isTrustedOverlay = isTrustedOverlay;
976 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000977 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700978 setTransactionFlags(eTransactionNeeded);
979 return true;
980}
981
982bool Layer::isTrustedOverlay() const {
983 if (getDrawingState().isTrustedOverlay) {
984 return true;
985 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000986 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700987 return (p != nullptr) && p->isTrustedOverlay();
988}
989
Dan Stoza9e56aa02015-11-02 13:00:03 -0800990bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700991 if (mDrawingState.color.a == alpha) return false;
992 mDrawingState.sequence++;
993 mDrawingState.color.a = alpha;
994 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800995 setTransactionFlags(eTransactionNeeded);
996 return true;
997}
chaviw13fdc492017-06-27 12:40:18 -0700998
Valerie Haudd0b7572019-01-29 14:59:27 -0800999bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -07001000 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -07001001 return false;
Valerie Hauaa194562019-02-05 16:21:38 -08001002 }
Robert Carr6a160312021-05-17 12:08:20 -07001003 mDrawingState.sequence++;
1004 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -08001005 setTransactionFlags(eTransactionNeeded);
1006
Robert Carr6a160312021-05-17 12:08:20 -07001007 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001008 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001009 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001010 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001011 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08001012 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001013 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001014
Valerie Haudd0b7572019-01-29 14:59:27 -08001015 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001016 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001017 mFlinger->mLayersAdded = true;
1018 // set up SF to handle added color layer
1019 if (isRemovedFromCurrentState()) {
Josh Gao194ff392022-09-08 16:19:29 -07001020 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001021 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001022 }
1023 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001024 } else if (mDrawingState.bgColorLayer && alpha == 0) {
Josh Gao194ff392022-09-08 16:19:29 -07001025 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001026 mDrawingState.bgColorLayer->reparent(nullptr);
1027 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001028 return true;
1029 }
1030
Robert Carr6a160312021-05-17 12:08:20 -07001031 mDrawingState.bgColorLayer->setColor(color);
1032 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1033 mDrawingState.bgColorLayer->setAlpha(alpha);
1034 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001035
chaviw13fdc492017-06-27 12:40:18 -07001036 return true;
1037}
1038
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001039bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001040 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001041
Robert Carr6a160312021-05-17 12:08:20 -07001042 mDrawingState.sequence++;
1043 mDrawingState.cornerRadius = cornerRadius;
1044 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001045 setTransactionFlags(eTransactionNeeded);
1046 return true;
1047}
1048
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001049bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001050 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001051 // If we start or stop drawing blur then the layer's visibility state may change so increment
1052 // the magic sequence number.
1053 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1054 mDrawingState.sequence++;
1055 }
Robert Carr6a160312021-05-17 12:08:20 -07001056 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1057 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001058 setTransactionFlags(eTransactionNeeded);
1059 return true;
1060}
Marissa Wall61c58622018-07-18 10:12:20 -07001061
Mathias Agopian13127d82013-03-05 17:47:11 -08001062bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001063 mDrawingState.sequence++;
1064 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001065 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001066 setTransactionFlags(eTransactionNeeded);
1067 return true;
1068}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001069
Lucas Dupinc3800b82020-10-02 16:24:48 -07001070bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001071 // If we start or stop drawing blur then the layer's visibility state may change so increment
1072 // the magic sequence number.
1073 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1074 mDrawingState.sequence++;
1075 }
Robert Carr6a160312021-05-17 12:08:20 -07001076 mDrawingState.blurRegions = blurRegions;
1077 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001078 setTransactionFlags(eTransactionNeeded);
1079 return true;
1080}
1081
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001082bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001083 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1084 if (mDrawingState.flags == newFlags) return false;
1085 mDrawingState.sequence++;
1086 mDrawingState.flags = newFlags;
1087 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001088 setTransactionFlags(eTransactionNeeded);
1089 return true;
1090}
Robert Carr99e27f02016-06-16 15:18:02 -07001091
chaviw25714502021-02-11 10:01:08 -08001092bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001093 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001094 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001095 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001096
Robert Carr6a160312021-05-17 12:08:20 -07001097 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001098 setTransactionFlags(eTransactionNeeded);
1099 return true;
1100}
Robert Carr8d5227b2017-03-16 15:41:03 -07001101
Evan Roskyef876c92019-01-25 17:46:06 -08001102bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001103 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1104 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001105 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001106 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001107}
1108
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001109bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001110 if (mDrawingState.layerStack == layerStack) return false;
1111 mDrawingState.sequence++;
1112 mDrawingState.layerStack = layerStack;
1113 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001114 setTransactionFlags(eTransactionNeeded);
1115 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001116}
1117
Peiyong Linc502cb72019-03-01 15:00:23 -08001118bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001119 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001120 return false;
1121 }
Robert Carr6a160312021-05-17 12:08:20 -07001122 mDrawingState.sequence++;
1123 mDrawingState.colorSpaceAgnostic = agnostic;
1124 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001125 setTransactionFlags(eTransactionNeeded);
1126 return true;
1127}
1128
Sally Qi81d95e62022-03-21 19:41:33 -07001129bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1130 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1131
1132 mDrawingState.sequence++;
1133 mDrawingState.dimmingEnabled = dimmingEnabled;
1134 mDrawingState.modified = true;
1135 setTransactionFlags(eTransactionNeeded);
1136 return true;
1137}
1138
Ana Krulecc84d09b2019-11-02 23:10:29 +01001139bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001140 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1141 mDrawingState.frameRateSelectionPriority = priority;
1142 mDrawingState.sequence++;
1143 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001144 setTransactionFlags(eTransactionNeeded);
1145 return true;
1146}
1147
1148int32_t Layer::getFrameRateSelectionPriority() const {
1149 // Check if layer has priority set.
1150 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1151 return mDrawingState.frameRateSelectionPriority;
1152 }
1153 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001154 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001155 if (parent != nullptr) {
1156 return parent->getFrameRateSelectionPriority();
1157 }
1158
1159 return Layer::PRIORITY_UNSET;
1160}
1161
Andy Labrada096227e2022-06-15 16:58:11 +00001162bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1163 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1164 mDrawingState.defaultFrameRateCompatibility = compatibility;
1165 mDrawingState.modified = true;
1166 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1167 setTransactionFlags(eTransactionNeeded);
1168 return true;
1169}
1170
1171scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1172 return mDrawingState.defaultFrameRateCompatibility;
1173}
1174
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001175bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1176 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1177};
1178
Vishnu Nair73908d12022-10-24 21:46:42 -07001179ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1180 bool useDrawing = state == LayerVector::StateSet::Drawing;
1181 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1182 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001183 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001184 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001185 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001186}
1187
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001188bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001189 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001190 return false;
1191 }
1192
Robert Carr6a160312021-05-17 12:08:20 -07001193 mDrawingState.sequence++;
1194 mDrawingState.shadowRadius = shadowRadius;
1195 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001196 setTransactionFlags(eTransactionNeeded);
1197 return true;
1198}
1199
Vishnu Nair6213bd92020-05-08 17:42:25 -07001200bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001201 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001202 return false;
1203 }
1204
Robert Carr6a160312021-05-17 12:08:20 -07001205 mDrawingState.sequence++;
1206 mDrawingState.fixedTransformHint = fixedTransformHint;
1207 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001208 setTransactionFlags(eTransactionNeeded);
1209 return true;
1210}
1211
John Reckcdb4ed72021-02-04 13:39:33 -05001212bool Layer::setStretchEffect(const StretchEffect& effect) {
1213 StretchEffect temp = effect;
1214 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001215 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001216 return false;
1217 }
Robert Carr6a160312021-05-17 12:08:20 -07001218 mDrawingState.sequence++;
1219 mDrawingState.stretchEffect = temp;
1220 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001221 setTransactionFlags(eTransactionNeeded);
1222 return true;
1223}
1224
John Reckc00c6692021-02-16 11:37:33 -05001225StretchEffect Layer::getStretchEffect() const {
1226 if (mDrawingState.stretchEffect.hasEffect()) {
1227 return mDrawingState.stretchEffect;
1228 }
1229
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001230 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001231 if (parent != nullptr) {
1232 auto effect = parent->getStretchEffect();
1233 if (effect.hasEffect()) {
1234 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1235 return effect;
1236 }
1237 }
1238 return StretchEffect{};
1239}
1240
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001241bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1242 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001243 return false;
1244 }
1245 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001246 mBorderWidth = width;
1247 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001248 return true;
1249}
1250
1251bool Layer::isBorderEnabled() {
1252 return mBorderEnabled;
1253}
1254
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001255float Layer::getBorderWidth() {
1256 return mBorderWidth;
1257}
1258
1259const half4& Layer::getBorderColor() {
1260 return mBorderColor;
1261}
1262
Ady Abrahama850c182021-08-04 13:04:37 -07001263bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1264 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1265 const auto frameRate = [&] {
Rachel Leece6e0042023-06-27 11:22:54 -07001266 if (mDrawingState.frameRate.isValid()) {
Ady Abrahama850c182021-08-04 13:04:37 -07001267 return mDrawingState.frameRate;
1268 }
1269
1270 return parentFrameRate;
1271 }();
1272
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001273 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate);
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 |=
1279 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1280 }
1281
Rachel Leece6e0042023-06-27 11:22:54 -07001282 // If we don't have a valid frame rate specification, but the children do, we set this
Ady Abrahama850c182021-08-04 13:04:37 -07001283 // layer as NoVote to allow the children to control the refresh rate
Rachel Leece6e0042023-06-27 11:22:54 -07001284 if (!frameRate.isValid() && childrenHaveFrameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001285 *transactionNeeded |=
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001286 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001287 }
1288
Rachel Leece6e0042023-06-27 11:22:54 -07001289 // We return whether this layer or its children has a vote. We ignore ExactOrMultiple votes for
Ady Abrahama850c182021-08-04 13:04:37 -07001290 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001291 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001292 const auto layerVotedWithDefaultCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001293 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Default;
1294 const auto layerVotedWithNoVote = frameRate.vote.type == FrameRateCompatibility::NoVote;
1295 const auto layerVotedWithCategory = frameRate.category != FrameRateCategory::Default;
Ady Abrahama850c182021-08-04 13:04:37 -07001296 const auto layerVotedWithExactCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001297 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Exact;
1298 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote || layerVotedWithCategory ||
Ady Abrahama850c182021-08-04 13:04:37 -07001299 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1300}
1301
Ady Abraham60e42ea2020-03-09 19:17:31 -07001302void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001303 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001304 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001305 while (auto parent = layer->getParent()) {
1306 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001307 }
Ady Abrahama850c182021-08-04 13:04:37 -07001308 return layer;
1309 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001310
Ady Abraham60e42ea2020-03-09 19:17:31 -07001311 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001312 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001313
Ady Abrahama850c182021-08-04 13:04:37 -07001314 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001315 if (transactionNeeded) {
1316 mFlinger->setTransactionFlags(eTraversalNeeded);
1317 }
1318}
1319
Rachel Leece6e0042023-06-27 11:22:54 -07001320bool Layer::setFrameRate(FrameRate::FrameRateVote frameRateVote) {
1321 if (mDrawingState.frameRate.vote == frameRateVote) {
Steven Thomas3172e202020-01-06 19:25:30 -08001322 return false;
1323 }
1324
Robert Carr6a160312021-05-17 12:08:20 -07001325 mDrawingState.sequence++;
Rachel Leece6e0042023-06-27 11:22:54 -07001326 mDrawingState.frameRate.vote = frameRateVote;
1327 mDrawingState.modified = true;
1328
1329 updateTreeHasFrameRateVote();
1330
1331 setTransactionFlags(eTransactionNeeded);
1332 return true;
1333}
1334
1335bool Layer::setFrameRateCategory(FrameRateCategory category) {
1336 if (mDrawingState.frameRate.category == category) {
1337 return false;
1338 }
1339
1340 mDrawingState.sequence++;
1341 mDrawingState.frameRate.category = category;
Robert Carr6a160312021-05-17 12:08:20 -07001342 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001343
1344 updateTreeHasFrameRateVote();
1345
Steven Thomas3172e202020-01-06 19:25:30 -08001346 setTransactionFlags(eTransactionNeeded);
1347 return true;
1348}
1349
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001350void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1351 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001352 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001353
1354 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1355 // there are two transactions with the same token, the first one without a buffer and the
1356 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1357 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001358 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1359 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001360 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001361 mDrawingState.bufferSurfaceFrameTX = it->second;
1362 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1363 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1364 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001365 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001366 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001367 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1368 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001369
1370 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001371}
1372
1373void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1374 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001375 mDrawingState.frameTimelineInfo = info;
1376 mDrawingState.postTime = postTime;
1377 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001378 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001379
Robert Carr6a160312021-05-17 12:08:20 -07001380 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001381 bufferSurfaceFrameTX != nullptr) {
1382 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1383 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1384 // being used for BufferSurfaceFrame, don't create a new one.
1385 return;
1386 }
1387 }
1388 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1389 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1390 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001391 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1392 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001393 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001394 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001395 } else {
1396 if (it->second->getPresentState() == PresentState::Presented) {
1397 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1398 // have been from previous vsync.
1399 it->second = createSurfaceFrameForTransaction(info, postTime);
1400 }
1401 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001402
1403 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001404}
1405
1406void Layer::addSurfaceFrameDroppedForBuffer(
Ady Abraham5a3e3562023-06-07 10:32:08 -07001407 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t dropTime) {
1408 surfaceFrame->setDropTime(dropTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001409 surfaceFrame->setPresentState(PresentState::Dropped);
1410 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1411}
1412
1413void Layer::addSurfaceFramePresentedForBuffer(
1414 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1415 nsecs_t currentLatchTime) {
1416 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1417 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1418 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001419 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001420}
1421
1422std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1423 const FrameTimelineInfo& info, nsecs_t postTime) {
1424 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001425 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1426 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001427 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001428 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001429 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001430 // For Transactions, the post time is considered to be both queue and acquire fence time.
1431 surfaceFrame->setActualQueueTime(postTime);
1432 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001433 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1434 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001435 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001436 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001437 onSurfaceFrameCreated(surfaceFrame);
1438 return surfaceFrame;
1439}
1440
1441std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1442 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1443 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001444 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001445 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001446 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001447 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001448 // For buffers, acquire fence time will set during latch.
1449 surfaceFrame->setActualQueueTime(queueTime);
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;
Ady Abraham74e17562020-08-24 18:18:19 -07001456}
1457
Ady Abraham5a3e3562023-06-07 10:32:08 -07001458void Layer::setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
1459 std::string debugName) {
1460 if (info.skippedFrameVsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
1461 return;
1462 }
1463
1464 FrameTimelineInfo skippedFrameTimelineInfo = info;
1465 skippedFrameTimelineInfo.vsyncId = info.skippedFrameVsyncId;
1466
1467 auto surfaceFrame =
1468 mFlinger->mFrameTimeline->createSurfaceFrameForToken(skippedFrameTimelineInfo,
1469 mOwnerPid, mOwnerUid,
1470 getSequence(), mName, debugName,
1471 /*isBuffer*/ false, getGameMode());
1472 surfaceFrame->setActualStartTime(skippedFrameTimelineInfo.skippedFrameStartTimeNanos);
1473 // For Transactions, the post time is considered to be both queue and acquire fence time.
1474 surfaceFrame->setActualQueueTime(postTime);
1475 surfaceFrame->setAcquireFenceTime(postTime);
1476 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1477 if (fps) {
1478 surfaceFrame->setRenderRate(*fps);
1479 }
1480 onSurfaceFrameCreated(surfaceFrame);
1481 addSurfaceFrameDroppedForBuffer(surfaceFrame, postTime);
1482}
1483
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001484bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001485 if (mDrawingState.frameRateForLayerTree == frameRate) {
1486 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001487 }
1488
Ady Abrahama850c182021-08-04 13:04:37 -07001489 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001490
Ady Abrahama850c182021-08-04 13:04:37 -07001491 // TODO(b/195668952): we probably don't need to dirty visible regions here
1492 // or even store frameRateForLayerTree in mDrawingState
1493 mDrawingState.sequence++;
1494 mDrawingState.modified = true;
1495 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001496
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001497 mFlinger->mScheduler
1498 ->recordLayerHistory(sequence, getLayerProps(), systemTime(),
1499 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1500 return true;
1501}
Ady Abrahama850c182021-08-04 13:04:37 -07001502
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001503bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps) {
1504 if (mDrawingState.frameRateForLayerTree == frameRate) {
1505 return false;
1506 }
1507
1508 mDrawingState.frameRateForLayerTree = frameRate;
1509 mFlinger->mScheduler
1510 ->recordLayerHistory(sequence, layerProps, systemTime(),
1511 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001512 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001513}
1514
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001515Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1516 return getDrawingState().frameRateForLayerTree;
1517}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001518
Robert Carr1f0a16a2016-10-24 16:27:39 -07001519bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001520 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001521 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001522 if (parent != nullptr && parent->isHiddenByPolicy()) {
1523 return true;
1524 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001525 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1526 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1527 if (zOrderRelativeOf != nullptr) {
1528 if (zOrderRelativeOf->isHiddenByPolicy()) {
1529 return true;
1530 }
1531 }
1532 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001533 if (CC_UNLIKELY(!isTransformValid())) {
1534 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1535 return true;
1536 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001537 return s.flags & layer_state_t::eLayerHidden;
1538}
1539
David Sodman41fdfc92017-11-06 16:09:56 -08001540uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001541 // TODO: should we do something special if mSecure is set?
1542 if (mProtectedByApp) {
1543 // need a hardware-protected path to external video sink
1544 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001545 }
Riley Andrews03414a12014-07-01 14:22:59 -07001546 if (mPotentialCursor) {
1547 usage |= GraphicBuffer::USAGE_CURSOR;
1548 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001549 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001550 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001551}
1552
Vishnu Nair71fcf912022-10-18 09:14:20 -07001553void Layer::skipReportingTransformHint() {
1554 mSkipReportingTransformHint = true;
1555}
1556
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001557void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1558 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1559 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001560 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001561
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001562 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001563}
1564
Mathias Agopian13127d82013-03-05 17:47:11 -08001565// ----------------------------------------------------------------------------
1566// debugging
1567// ----------------------------------------------------------------------------
1568
Marissa Wall61c58622018-07-18 10:12:20 -07001569// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001570gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001571 using namespace std::string_literals;
1572
Huihong Luo05539a12022-02-23 10:29:40 -08001573 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001574 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001575 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001576 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001577 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001578 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001579
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001580 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001581 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001582 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001583 info.mX = ds.transform.tx();
1584 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001585 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001586 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001587 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001588 info.mFlags = ds.flags;
1589 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001590 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001591 info.mMatrix[0][0] = ds.transform[0][0];
1592 info.mMatrix[0][1] = ds.transform[0][1];
1593 info.mMatrix[1][0] = ds.transform[1][0];
1594 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001595 {
chaviwd62d3062019-09-04 14:48:02 -07001596 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001597 if (buffer != 0) {
1598 info.mActiveBufferWidth = buffer->getWidth();
1599 info.mActiveBufferHeight = buffer->getHeight();
1600 info.mActiveBufferStride = buffer->getStride();
1601 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001602 } else {
1603 info.mActiveBufferWidth = 0;
1604 info.mActiveBufferHeight = 0;
1605 info.mActiveBufferStride = 0;
1606 info.mActiveBufferFormat = 0;
1607 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001608 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001609 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001610 info.mIsOpaque = isOpaque(ds);
1611 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001612 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001613 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001614}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001615
Yiwei Zhang5434a782018-12-05 18:06:32 -08001616void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001617 result.append(kDumpTableRowLength, '-');
1618 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001619 result.append(" Layer name\n");
1620 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001621 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001622 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001623 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001624 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001625 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001626 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1627 result.append(kDumpTableRowLength, '-');
1628 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001629}
1630
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001631void Layer::miniDumpLegacy(std::string& result, const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001632 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001633 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001634 return;
1635 }
1636
Yiwei Zhang5434a782018-12-05 18:06:32 -08001637 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001638 if (mName.length() > 77) {
1639 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001640 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001641 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001642 shortened.append(mName, mName.length() - 36);
1643 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001644 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001645 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001646 }
1647
Yiwei Zhang5434a782018-12-05 18:06:32 -08001648 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001649
Alec Mourib416efd2018-09-06 21:01:59 +00001650 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001651 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001652
Chia-I Wu1e043612018-03-01 09:45:09 -08001653 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001654 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001655 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001656 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001657 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001658 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001659 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001660 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1661 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001662 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001663 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001664 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001665 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001666 const auto frameRate = getFrameRateForLayerTree();
Rachel Leece6e0042023-06-27 11:22:54 -07001667 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
1668 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.vote.rate).c_str(),
1669 ftl::enum_string(frameRate.vote.type).c_str(),
1670 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001671 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001672 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001673 }
Dan Stozae22aec72016-08-01 13:20:59 -07001674
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001675 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1676 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1677
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001678 result.append(kDumpTableRowLength, '-');
1679 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001680}
Dan Stozae22aec72016-08-01 13:20:59 -07001681
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001682void Layer::miniDump(std::string& result, const frontend::LayerSnapshot& snapshot,
1683 const DisplayDevice& display) const {
1684 const auto outputLayer = findOutputLayerForDisplay(&display, snapshot.path);
1685 if (!outputLayer) {
1686 return;
1687 }
1688
1689 StringAppendF(&result, " %s\n", snapshot.debugName.c_str());
1690 StringAppendF(&result, " %10zu | ", snapshot.globalZ);
1691 StringAppendF(&result, " %10d | ",
1692 snapshot.layerMetadata.getInt32(gui::METADATA_WINDOW_TYPE, 0));
1693 StringAppendF(&result, "%10s | ", toString(getCompositionType(outputLayer)).c_str());
1694 const auto& outputLayerState = outputLayer->getState();
1695 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1696 const Rect& frame = outputLayerState.displayFrame;
1697 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1698 const FloatRect& crop = outputLayerState.sourceCrop;
1699 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
1700 crop.bottom);
1701 const auto frameRate = snapshot.frameRate;
Rachel Leece6e0042023-06-27 11:22:54 -07001702 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
1703 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.vote.rate).c_str(),
1704 ftl::enum_string(frameRate.vote.type).c_str(),
1705 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001706 } else {
1707 result.append(41, ' ');
1708 }
1709
1710 const auto focused = isLayerFocusedBasedOnPriority(snapshot.frameRateSelectionPriority);
1711 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1712
1713 result.append(kDumpTableRowLength, '-');
1714 result.append("\n");
1715}
1716
Yiwei Zhang5434a782018-12-05 18:06:32 -08001717void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001718 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001719}
1720
Svetoslavd85084b2014-03-20 10:28:31 -07001721void Layer::clearFrameStats() {
1722 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001723}
1724
Jamie Gennis6547ff42013-07-16 20:12:42 -07001725void Layer::logFrameStats() {
1726 mFrameTracker.logAndResetStats(mName);
1727}
1728
Svetoslavd85084b2014-03-20 10:28:31 -07001729void Layer::getFrameStats(FrameStats* outStats) const {
1730 mFrameTracker.getStats(outStats);
1731}
1732
Vishnu Nair76554eb2022-12-09 03:38:36 +00001733void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1734 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
Vishnu Nair3be61902023-04-26 19:47:29 -07001735 StringAppendF(&result, "Layer %s%s pid:%d uid:%d%s\n", getName().c_str(), hasBuffer.c_str(),
1736 mOwnerPid, mOwnerUid, isHandleAlive() ? " handleAlive" : "");
Vishnu Nair0f085c62019-08-30 08:49:12 -07001737}
1738
Brian Anderson5ea5e592016-12-01 16:54:33 -08001739void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001740 const int32_t layerId = getSequence();
1741 mFlinger->mTimeStats->onDestroy(layerId);
1742 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001743}
1744
Vishnu Nair787aa782023-03-17 13:46:46 -07001745size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001746 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001747 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001748 count += 1 + child->getChildrenCount();
1749 }
1750 return count;
1751}
1752
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001753void Layer::setGameModeForTree(GameMode gameMode) {
1754 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001755 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1756 gameMode =
1757 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001758 }
1759 setGameMode(gameMode);
1760 for (const sp<Layer>& child : mCurrentChildren) {
1761 child->setGameModeForTree(gameMode);
1762 }
1763}
1764
Robert Carr1f0a16a2016-10-24 16:27:39 -07001765void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001766 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001767 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001768
Robert Carr1f0a16a2016-10-24 16:27:39 -07001769 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001770 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001771 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001772 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001773}
1774
1775ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001776 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001777 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001778
Robert Carr1323c952019-01-28 18:13:27 -08001779 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001780 const auto removeResult = mCurrentChildren.remove(layer);
1781
1782 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001783 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001784 layer->updateTreeHasFrameRateVote();
1785
1786 return removeResult;
1787}
1788
Robert Carr15eae092018-03-23 13:43:53 -07001789void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001790 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001791 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001792 const float parentShadowRadius =
1793 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001794 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001795 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001796 }
1797}
1798
chaviwf1961f72017-09-18 16:41:07 -07001799bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001800 sp<Layer> newParent;
1801 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001802 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001803 if (newParent == nullptr) {
1804 ALOGE("Unable to promote Layer handle");
1805 return false;
1806 }
1807 if (newParent == this) {
1808 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1809 return false;
1810 }
1811 }
1812
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001813 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001814 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001815 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001816 }
1817
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001818 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001819 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001820 if (!newParent->isRemovedFromCurrentState()) {
1821 addToCurrentState();
1822 } else {
1823 onRemovedFromCurrentState();
1824 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001825 } else {
1826 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001827 }
1828
chaviw06178942017-07-27 10:25:59 -07001829 return true;
1830}
1831
Peiyong Lind3788632018-09-18 16:01:31 -07001832bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001833 static const mat4 identityMatrix = mat4();
1834
Robert Carr6a160312021-05-17 12:08:20 -07001835 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001836 return false;
1837 }
Robert Carr6a160312021-05-17 12:08:20 -07001838 ++mDrawingState.sequence;
1839 mDrawingState.colorTransform = matrix;
1840 mDrawingState.hasColorTransform = matrix != identityMatrix;
1841 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001842 setTransactionFlags(eTransactionNeeded);
1843 return true;
1844}
1845
chaviwf66724d2018-11-28 16:35:21 -08001846mat4 Layer::getColorTransform() const {
1847 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001848 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001849 colorTransform = parent->getColorTransform() * colorTransform;
1850 }
1851 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001852}
1853
1854bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001855 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001856 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001857 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1858 }
1859 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001860}
1861
Chia-I Wu11481472018-05-04 10:43:19 -07001862bool Layer::isLegacyDataSpace() const {
1863 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001864 return !(getDataSpace() &
1865 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1866 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001867}
1868
Robert Carr1f0a16a2016-10-24 16:27:39 -07001869void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001870 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001871}
1872
Robert Carr6a160312021-05-17 12:08:20 -07001873int32_t Layer::getZ(LayerVector::StateSet) const {
1874 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001875}
1876
Robert Carr1c5481e2019-07-01 14:42:27 -07001877bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001878 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001879 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001880 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001881}
1882
David Sodman41fdfc92017-11-06 16:09:56 -08001883__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001884 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001885 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1886 "makeTraversalList received invalid stateSet");
1887 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1888 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001889 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001890
Robert Carr29abff82017-12-04 13:51:20 -08001891 if (state.zOrderRelatives.size() == 0) {
1892 *outSkipRelativeZUsers = true;
1893 return children;
1894 }
1895
chaviwfd462612018-05-31 16:11:27 -07001896 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001897 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001898 sp<Layer> strongRelative = weakRelative.promote();
1899 if (strongRelative != nullptr) {
1900 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001901 }
1902 }
1903
Dan Stoza412903f2017-04-27 13:42:17 -07001904 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001905 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001906 continue;
1907 }
Robert Carrdb66e622017-04-10 16:55:57 -07001908 traverse.add(child);
1909 }
1910
1911 return traverse;
1912}
1913
Robert Carr1f0a16a2016-10-24 16:27:39 -07001914/**
Robert Carrdb66e622017-04-10 16:55:57 -07001915 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001916 */
Dan Stoza412903f2017-04-27 13:42:17 -07001917void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001918 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1919 // produce a new list for traversing, including our relatives, and not including our children
1920 // who are relatives of another surface. In the case that there are no relative Z,
1921 // makeTraversalList returns our children directly to avoid significant overhead.
1922 // However in this case we need to take the responsibility for filtering children which
1923 // are relatives of another surface here.
1924 bool skipRelativeZUsers = false;
1925 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001926
Robert Carr1f0a16a2016-10-24 16:27:39 -07001927 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001928 for (; i < list.size(); i++) {
1929 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001930 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1931 continue;
1932 }
1933
chaviw301b1d82019-11-06 13:15:09 -08001934 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001935 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001936 }
Dan Stoza412903f2017-04-27 13:42:17 -07001937 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001938 }
Robert Carr29abff82017-12-04 13:51:20 -08001939
Dan Stoza412903f2017-04-27 13:42:17 -07001940 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001941 for (; i < list.size(); i++) {
1942 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001943
Robert Carr29abff82017-12-04 13:51:20 -08001944 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1945 continue;
1946 }
Dan Stoza412903f2017-04-27 13:42:17 -07001947 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001948 }
1949}
1950
1951/**
Robert Carrdb66e622017-04-10 16:55:57 -07001952 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001953 */
Dan Stoza412903f2017-04-27 13:42:17 -07001954void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1955 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001956 // See traverseInZOrder for documentation.
1957 bool skipRelativeZUsers = false;
1958 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001959
Robert Carr1f0a16a2016-10-24 16:27:39 -07001960 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001961 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001962 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001963
1964 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1965 continue;
1966 }
1967
chaviw301b1d82019-11-06 13:15:09 -08001968 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001969 break;
1970 }
Dan Stoza412903f2017-04-27 13:42:17 -07001971 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001972 }
Dan Stoza412903f2017-04-27 13:42:17 -07001973 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001974 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001975 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001976
1977 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1978 continue;
1979 }
1980
Dan Stoza412903f2017-04-27 13:42:17 -07001981 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001982 }
1983}
1984
Edgar Arriaga844fa672020-01-16 14:21:42 -08001985void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1986 visitor(this);
1987 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001988 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001989 for (const sp<Layer>& child : children) {
1990 child->traverse(state, visitor);
1991 }
1992}
1993
Vishnu Nair787aa782023-03-17 13:46:46 -07001994void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
1995 for (const sp<Layer>& child : mDrawingChildren) {
1996 visitor(child.get());
1997 }
1998}
1999
chaviw4b129c22018-04-09 16:19:43 -07002000LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
2001 const std::vector<Layer*>& layersInTree) {
2002 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2003 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07002004 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2005 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002006 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002007
chaviwfd462612018-05-31 16:11:27 -07002008 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07002009 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2010 sp<Layer> strongRelative = weakRelative.promote();
2011 // Only add relative layers that are also descendents of the top most parent of the tree.
2012 // If a relative layer is not a descendent, then it should be ignored.
2013 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
2014 traverse.add(strongRelative);
2015 }
2016 }
2017
2018 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07002019 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002020 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
2021 // descendent of the top most parent of the tree. If it's not a descendent, then just add
2022 // the child here since it won't be added later as a relative.
2023 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
2024 childState.zOrderRelativeOf.promote().get())) {
2025 continue;
2026 }
2027 traverse.add(child);
2028 }
2029
2030 return traverse;
2031}
2032
2033void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
2034 LayerVector::StateSet stateSet,
2035 const LayerVector::Visitor& visitor) {
2036 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07002037
2038 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07002039 for (; i < list.size(); i++) {
2040 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08002041 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07002042 break;
2043 }
chaviw4b129c22018-04-09 16:19:43 -07002044 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002045 }
chaviw4b129c22018-04-09 16:19:43 -07002046
chaviwa76b2712017-09-20 12:02:26 -07002047 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07002048 for (; i < list.size(); i++) {
2049 const auto& relative = list[i];
2050 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002051 }
2052}
2053
chaviw4b129c22018-04-09 16:19:43 -07002054std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2055 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2056 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2057
2058 std::vector<Layer*> layersInTree = {this};
2059 for (size_t i = 0; i < children.size(); i++) {
2060 const auto& child = children[i];
2061 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2062 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2063 }
2064
2065 return layersInTree;
2066}
2067
2068void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2069 const LayerVector::Visitor& visitor) {
2070 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2071 std::sort(layersInTree.begin(), layersInTree.end());
2072 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2073}
2074
Peiyong Linefefaac2018-08-17 12:27:51 -07002075ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08002076 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002077}
2078
Garfield Tan2c1782c2022-02-16 15:25:05 -08002079bool Layer::isTransformValid() const {
2080 float transformDet = getTransform().det();
2081 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2082}
2083
chaviw13fdc492017-06-27 12:40:18 -07002084half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002085 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002086
chaviw13fdc492017-06-27 12:40:18 -07002087 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2088 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002089}
Robert Carr6452f122017-03-21 10:41:29 -07002090
Vishnu Nair6213bd92020-05-08 17:42:25 -07002091ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002092 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002093 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2094 return fixedTransformHint;
2095 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002096 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002097 if (!p) return fixedTransformHint;
2098 return p->getFixedTransformHint();
2099}
2100
chaviw13fdc492017-06-27 12:40:18 -07002101half4 Layer::getColor() const {
2102 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002103 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002104}
Robert Carr6452f122017-03-21 10:41:29 -07002105
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002106int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002107 if (getDrawingState().backgroundBlurRadius == 0) {
2108 return 0;
2109 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002110
Vishnu Nair29810f72022-07-01 16:38:41 +00002111 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002112 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2113 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002114}
2115
Galia Peychevae0acf382021-04-12 21:22:34 +02002116const std::vector<BlurRegion> Layer::getBlurRegions() const {
2117 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002118 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002119 for (auto& region : regionsCopy) {
2120 region.alpha = region.alpha * layerAlpha;
2121 }
2122 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002123}
2124
Vishnu Naire14c6b32022-08-06 04:20:15 +00002125RoundedCornerState Layer::getRoundedCornerState() const {
Leon Scroggins IIIc1dbfcb2022-03-21 16:48:10 -04002126 // Today's DPUs cannot do rounded corners. If RenderEngine cannot render
2127 // protected content, remove rounded corners from protected content so it
2128 // can be rendered by the DPU.
2129 if (isProtected() && !mFlinger->getRenderEngine().supportsProtectedContent()) {
2130 return {};
2131 }
2132
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002133 // Get parent settings
2134 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002135 const auto& parent = mDrawingParent.promote();
2136 if (parent != nullptr) {
2137 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002138 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002139 ui::Transform t = getActiveTransform(getDrawingState());
2140 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002141 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002142 parentSettings.radius.x *= t.getScaleX();
2143 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002144 }
2145 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002146
2147 // Get layer settings
2148 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002149 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002150 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002151 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002152
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002153 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002154 // If the parent and the layer have rounded corner settings, use the parent settings if the
2155 // parent crop is entirely inside the layer crop.
2156 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2157 if (parentSettings.cropRect.left > layerCropRect.left &&
2158 parentSettings.cropRect.top > layerCropRect.top &&
2159 parentSettings.cropRect.right < layerCropRect.right &&
2160 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2161 return parentSettings;
2162 } else {
2163 return layerSettings;
2164 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002165 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002166 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002167 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002168 return parentSettings;
2169 }
2170 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002171}
2172
Robert Carr88b85e12022-03-21 15:47:35 -07002173bool Layer::findInHierarchy(const sp<Layer>& l) {
2174 if (l == this) {
2175 return true;
2176 }
2177 for (auto& child : mDrawingChildren) {
2178 if (child->findInHierarchy(l)) {
2179 return true;
2180 }
2181 }
2182 return false;
2183}
2184
Robert Carr1f0a16a2016-10-24 16:27:39 -07002185void Layer::commitChildList() {
2186 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2187 const auto& child = mCurrentChildren[i];
2188 child->commitChildList();
2189 }
2190 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002191 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002192 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2193 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2194 if (zOrderRelativeOf == nullptr) return;
2195 if (findInHierarchy(zOrderRelativeOf)) {
2196 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2197 zOrderRelativeOf->mName.c_str());
2198 ALOGE("Severing rel Z loop, potentially dangerous");
2199 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002200 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002201 }
2202 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002203}
2204
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002205
chaviw3277faf2021-05-19 16:45:23 -05002206void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002207 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002208 mDrawingState.touchableRegionCrop =
2209 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002210 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002211 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002212 setTransactionFlags(eTransactionNeeded);
2213}
2214
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002215LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002216 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002217 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002218 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2219
Vishnu Nair00b90132021-11-05 14:03:40 -07002220 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nair2f65e972023-04-04 16:36:28 +00002221 ui::LayerStack layerStack =
2222 (mSnapshot) ? mSnapshot->outputFilter.layerStack : ui::INVALID_LAYER_STACK;
2223 writeCompositionStateToProto(layerProto, layerStack);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002224 }
2225
chaviw08f3cb22020-01-13 13:17:21 -08002226 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002227 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002228 }
chaviw6d89e2d2020-01-14 14:42:01 -08002229
2230 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002231}
2232
Vishnu Nair2f65e972023-04-04 16:36:28 +00002233void Layer::writeCompositionStateToProto(LayerProto* layerProto, ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002234 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002235 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +00002236
2237 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002238 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002239 const auto compositionType = getCompositionType(*display);
2240 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +00002241 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +00002242 [&]() { return layerProto->mutable_visible_region(); });
2243 }
2244}
2245
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002246void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002247 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002248 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002249 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002250 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002251 [&]() { return layerInfo->mutable_active_buffer(); });
2252 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2253 layerInfo->mutable_buffer_transform());
2254 }
2255 layerInfo->set_invalidate(contentDirty);
2256 layerInfo->set_is_protected(isProtected());
2257 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2258 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002259 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002260 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002261 layerInfo->set_corner_radius(
2262 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002263 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2264 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2265 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2266 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2267 [&]() { return layerInfo->mutable_position(); });
2268 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002269 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2270 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002271
Vishnu Nair00b90132021-11-05 14:03:40 -07002272 if (hasColorTransform()) {
2273 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002274 }
2275
Vishnu Nair60db8c02020-04-02 11:55:16 -07002276 LayerProtoHelper::writeToProto(mSourceBounds,
2277 [&]() { return layerInfo->mutable_source_bounds(); });
2278 LayerProtoHelper::writeToProto(mScreenBounds,
2279 [&]() { return layerInfo->mutable_screen_bounds(); });
2280 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2281 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2282 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002283}
2284
2285void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002286 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002287 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2288 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002289 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002290
chaviw766c9c52021-02-10 17:36:47 -08002291 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002292
Vishnu Nair00b90132021-11-05 14:03:40 -07002293 layerInfo->set_id(sequence);
2294 layerInfo->set_name(getName().c_str());
2295 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002296
Vishnu Nair00b90132021-11-05 14:03:40 -07002297 for (const auto& child : children) {
2298 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002299 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002300
Vishnu Nair00b90132021-11-05 14:03:40 -07002301 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2302 sp<Layer> strongRelative = weakRelative.promote();
2303 if (strongRelative != nullptr) {
2304 layerInfo->add_relatives(strongRelative->sequence);
2305 }
2306 }
2307
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002308 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002309 [&]() { return layerInfo->mutable_transparent_region(); });
2310
2311 layerInfo->set_layer_stack(getLayerStack().id);
2312 layerInfo->set_z(state.z);
2313
2314 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2315 return layerInfo->mutable_requested_position();
2316 });
2317
Vishnu Nair00b90132021-11-05 14:03:40 -07002318 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2319
2320 layerInfo->set_is_opaque(isOpaque(state));
2321
2322 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2323 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2324 LayerProtoHelper::writeToProto(state.color,
2325 [&]() { return layerInfo->mutable_requested_color(); });
2326 layerInfo->set_flags(state.flags);
2327
2328 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2329 layerInfo->mutable_requested_transform());
2330
2331 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2332 if (parent != nullptr) {
2333 layerInfo->set_parent(parent->sequence);
2334 } else {
2335 layerInfo->set_parent(-1);
2336 }
2337
2338 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2339 if (zOrderRelativeOf != nullptr) {
2340 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2341 } else {
2342 layerInfo->set_z_order_relative_of(-1);
2343 }
2344
2345 layerInfo->set_is_relative_of(state.isRelativeOf);
2346
2347 layerInfo->set_owner_uid(mOwnerUid);
2348
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002349 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002350 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002351 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002352 info = fillInputInfo(
2353 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002354 } else {
2355 info = state.inputInfo;
2356 }
2357
2358 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002359 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002360 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002361
Vishnu Nair00b90132021-11-05 14:03:40 -07002362 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002363 auto protoMap = layerInfo->mutable_metadata();
2364 for (const auto& entry : state.metadata.mMap) {
2365 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2366 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002367 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002368
2369 LayerProtoHelper::writeToProto(state.destinationFrame,
2370 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002371}
2372
Robert Carr2e102c92018-10-23 12:11:15 -07002373bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002374 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002375}
2376
Prabir Pradhan33da9462022-06-14 14:55:57 +00002377// Applies the given transform to the region, while protecting against overflows caused by any
2378// offsets. If applying the offset in the transform to any of the Rects in the region would result
2379// in an overflow, they are not added to the output Region.
2380static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2381 const std::string& debugWindowName) {
2382 // Round the translation using the same rounding strategy used by ui::Transform.
2383 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2384 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2385
2386 ui::Transform transformWithoutOffset = t;
2387 transformWithoutOffset.set(0.f, 0.f);
2388
2389 const Region transformed = transformWithoutOffset.transform(r);
2390
2391 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2392 Region ret;
2393 for (const auto& rect : transformed) {
2394 Rect newRect;
2395 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2396 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2397 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2398 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2399 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2400 debugWindowName.c_str());
2401 continue;
2402 }
2403 ret.orSelf(newRect);
2404 }
2405 return ret;
2406}
2407
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002408void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002409 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2410 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002411 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002412 }
2413
Vishnu Nairfed7c122023-03-18 01:54:43 +00002414 const Rect roundedFrameInDisplay = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002415 info.frameLeft = roundedFrameInDisplay.left;
2416 info.frameTop = roundedFrameInDisplay.top;
2417 info.frameRight = roundedFrameInDisplay.right;
2418 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002419
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002420 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002421 inputToLayer.set(inputBounds.left, inputBounds.top);
2422 const ui::Transform layerToScreen = getInputTransform();
2423 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002424
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002425 // InputDispatcher expects a display-to-input transform.
2426 info.transform = inputToDisplay.inverse();
2427
2428 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002429 info.touchableRegion =
2430 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002431}
2432
chaviw3277faf2021-05-19 16:45:23 -05002433void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002434 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002435 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002436 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002437 }
2438 if (p != nullptr) {
2439 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2440 }
2441}
2442
Vishnu Naira066d902021-09-13 18:40:17 -07002443gui::DropInputMode Layer::getDropInputMode() const {
2444 gui::DropInputMode mode = mDrawingState.dropInputMode;
2445 if (mode == gui::DropInputMode::ALL) {
2446 return mode;
2447 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002448 sp<Layer> parent = mDrawingParent.promote();
2449 if (parent) {
2450 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002451 if (parentMode != gui::DropInputMode::NONE) {
2452 return parentMode;
2453 }
2454 }
2455 return mode;
2456}
2457
2458void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002459 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002460 return;
2461 }
2462
2463 // Check if we need to drop input unconditionally
2464 gui::DropInputMode dropInputMode = getDropInputMode();
2465 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002466 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002467 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2468 return;
2469 }
2470
2471 // Check if we need to check if the window is obscured by parent
2472 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2473 return;
2474 }
2475
2476 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002477 sp<Layer> parent = mDrawingParent.promote();
2478 if (parent && parent->getAlpha() != 1.0_hf) {
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 because alpha=%f", getDebugName(),
2481 static_cast<float>(getAlpha()));
2482 }
2483
2484 // Check if the parent has cropped the buffer
2485 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2486 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002487 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002488 return;
2489 }
2490
2491 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2492 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2493 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2494 // match then the layer has not been cropped by its parents.
2495 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2496 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2497
2498 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002499 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002500 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2501 getDebugName());
2502 } else {
2503 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2504 // input if the window is obscured. This check should be done in surfaceflinger but the
2505 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2506 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002507 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002508 }
2509}
2510
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002511WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002512 if (!hasInputInfo()) {
2513 mDrawingState.inputInfo.name = getName();
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002514 mDrawingState.inputInfo.ownerUid = gui::Uid{mOwnerUid};
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00002515 mDrawingState.inputInfo.ownerPid = gui::Pid{mOwnerPid};
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002516 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002517 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002518 }
2519
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002520 const ui::Transform& displayTransform =
2521 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2522
chaviw3277faf2021-05-19 16:45:23 -05002523 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002524 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002525 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002526
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002527 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002528
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002529 if (displayArgs.transform == nullptr) {
2530 // Do not let the window receive touches if it is not associated with a valid display
2531 // transform. We still allow the window to receive keys and prevent ANRs.
2532 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2533 }
2534
Patrick Williams1caf3b72023-03-31 10:59:10 -05002535 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !isVisibleForInput());
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002536
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002537 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002538 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002539 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002540
Vishnu Nair16a938f2021-09-24 07:14:54 -07002541 // If the window will be blacked out on a display because the display does not have the secure
2542 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002543 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002544 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002545 }
2546
Vishnu Nairfed7c122023-03-18 01:54:43 +00002547 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002548 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002549 Rect inputBoundsInDisplaySpace;
2550 if (!cropLayer) {
2551 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2552 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2553 } else {
2554 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2555 inputBoundsInDisplaySpace =
2556 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2557 }
2558 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002559 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002560 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2561 Rect inputBoundsInDisplaySpace =
2562 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2563 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002564 }
2565
Winson Chunga30f7c92021-06-29 15:42:56 -07002566 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2567 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002568 if (isTrustedOverlay()) {
2569 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2570 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002571
chaviwaf87b3e2019-10-01 16:59:28 -07002572 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2573 // touches from going outside the cloned area.
2574 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002575 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002576 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2577 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002578 info.touchableRegion = info.touchableRegion.intersect(rect);
2579 }
2580 }
2581
Robert Carr720e5062018-07-30 17:45:14 -07002582 return info;
2583}
2584
Vishnu Nairfed7c122023-03-18 01:54:43 +00002585Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2586 const ui::Transform& screenToDisplay) {
2587 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2588 // frame and transform used for the layer, which determines the bounds and the coordinate space
2589 // within which the layer will receive input.
2590
2591 // Coordinate space definitions:
2592 // - display: The display device's coordinate space. Correlates to pixels on the display.
2593 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2594 // - layer: The coordinate space of this layer.
2595 // - input: The coordinate space in which this layer will receive input events. This could be
2596 // different than layer space if a surfaceInset is used, which changes the origin
2597 // of the input space.
2598
2599 // Crop the input bounds to ensure it is within the parent's bounds.
2600 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2601 const ui::Transform layerToScreen = getInputTransform();
2602 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2603 return Rect{layerToDisplay.transform(croppedInputBounds)};
2604}
2605
chaviwaf87b3e2019-10-01 16:59:28 -07002606sp<Layer> Layer::getClonedRoot() {
2607 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002608 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002609 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002610 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002611 return nullptr;
2612 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002613 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002614}
2615
Robert Carredd13602020-04-13 17:24:34 -07002616bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002617 return mDrawingState.inputInfo.token != nullptr ||
2618 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002619}
2620
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002621compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002622 const DisplayDevice* display) const {
2623 if (!display) return nullptr;
Lloyd Pique30db6402023-06-26 18:56:51 +00002624 if (!mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00002625 return display->getCompositionDisplay()->getOutputLayerForLayer(
2626 getCompositionEngineLayerFE());
2627 }
2628 sp<LayerFE> layerFE;
2629 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2630 for (auto& [p, layer] : mLayerFEs) {
2631 if (p == path) {
2632 layerFE = layer;
2633 }
2634 }
2635
2636 if (!layerFE) return nullptr;
2637 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002638}
2639
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002640compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
2641 const DisplayDevice* display, const frontend::LayerHierarchy::TraversalPath& path) const {
2642 if (!display) return nullptr;
Vishnu Naire9ee0002023-07-01 03:14:51 +00002643 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2644 return display->getCompositionDisplay()->getOutputLayerForLayer(
2645 getCompositionEngineLayerFE());
2646 }
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002647 sp<LayerFE> layerFE;
2648 for (auto& [p, layer] : mLayerFEs) {
2649 if (p == path) {
2650 layerFE = layer;
2651 }
2652 }
2653
2654 if (!layerFE) return nullptr;
2655 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
2656}
2657
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002658Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2659 const auto outputLayer = findOutputLayerForDisplay(display);
2660 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002661}
2662
Vishnu Nairde177252023-04-21 12:44:10 -07002663void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom, uint32_t mirrorRootId) {
2664 mSnapshot->path.id = clonedFrom->getSequence();
2665 mSnapshot->path.mirrorRootId = mirrorRootId;
2666
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002667 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002668 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002669 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2670 mPotentialCursor = clonedFrom->mPotentialCursor;
2671 mProtectedByApp = clonedFrom->mProtectedByApp;
2672 updateCloneBufferInfo();
2673}
2674
2675void Layer::updateCloneBufferInfo() {
2676 if (!isClone() || !isClonedFromAlive()) {
2677 return;
2678 }
2679
2680 sp<Layer> clonedFrom = getClonedFrom();
2681 mBufferInfo = clonedFrom->mBufferInfo;
2682 mSidebandStream = clonedFrom->mSidebandStream;
2683 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2684 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2685 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2686
2687 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2688 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2689 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2690 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2691 // the cloned drawingState again.
2692 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2693 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2694 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2695 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2696
2697 cloneDrawingState(clonedFrom.get());
2698
2699 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2700 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2701 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2702 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002703}
chaviw74b03172019-08-19 11:09:03 -07002704
Vishnu Nair3be61902023-04-26 19:47:29 -07002705bool Layer::updateMirrorInfo(const std::deque<Layer*>& cloneRootsPendingUpdates) {
chaviw74b03172019-08-19 11:09:03 -07002706 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2707 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2708 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2709 // that case, we want to delete the reference to the clone since we want it to get
2710 // destroyed. The root, this layer, will still be around since the client can continue
2711 // to hold a reference, but no cloned layers will be displayed.
2712 mClonedChild = nullptr;
Vishnu Nair3be61902023-04-26 19:47:29 -07002713 return true;
chaviw74b03172019-08-19 11:09:03 -07002714 }
2715
2716 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2717 // If the real layer exists and is in current state, add the clone as a child of the root.
2718 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2719 // copied to drawingState for the root layer. So the clonedChild is always removed from
2720 // drawingState and then needs to be added back each traversal.
2721 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2722 addChildToDrawing(mClonedChild);
2723 }
2724
2725 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002726 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002727 mClonedChild->updateClonedRelatives(clonedLayersMap);
Vishnu Nair3be61902023-04-26 19:47:29 -07002728
2729 for (Layer* root : cloneRootsPendingUpdates) {
2730 if (clonedLayersMap.find(sp<Layer>::fromExisting(root)) != clonedLayersMap.end()) {
2731 return false;
2732 }
2733 }
2734 return true;
chaviw74b03172019-08-19 11:09:03 -07002735}
2736
2737void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2738 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2739 // to the clone. If the real layer is no longer alive, continue traversing the children
2740 // since we may be able to pull out other children that are still alive.
2741 if (isClonedFromAlive()) {
2742 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002743 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002744 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002745 }
2746
2747 // The clone layer may have children in drawingState since they may have been created and
2748 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2749 // that already exist, since we can just re-use them.
2750 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2751 // not updated in the regular traversal. They are skipped since the root will lose the
2752 // reference to them when it copies its currentChildren to drawing.
2753 for (sp<Layer>& child : mDrawingChildren) {
2754 child->updateClonedDrawingState(clonedLayersMap);
2755 }
2756}
2757
2758void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2759 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2760 mDrawingChildren.clear();
2761
2762 if (!isClonedFromAlive()) {
2763 return;
2764 }
2765
2766 sp<Layer> clonedFrom = getClonedFrom();
2767 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2768 if (child == mirrorRoot) {
2769 // This is to avoid cyclical mirroring.
2770 continue;
2771 }
2772 sp<Layer> clonedChild = clonedLayersMap[child];
2773 if (clonedChild == nullptr) {
Vishnu Nairde177252023-04-21 12:44:10 -07002774 clonedChild = child->createClone(mirrorRoot->getSequence());
chaviw74b03172019-08-19 11:09:03 -07002775 clonedLayersMap[child] = clonedChild;
2776 }
2777 addChildToDrawing(clonedChild);
2778 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2779 }
2780}
2781
chaviwaf87b3e2019-10-01 16:59:28 -07002782void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2783 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2784 if (cropLayer != nullptr) {
2785 if (clonedLayersMap.count(cropLayer) == 0) {
2786 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2787 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002788 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002789 } else {
2790 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2791 mDrawingState.touchableRegionCrop = clonedCropLayer;
2792 }
2793 }
2794 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2795 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002796 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002797}
2798
2799void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002800 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002801 mDrawingState.zOrderRelatives.clear();
2802
2803 if (!isClonedFromAlive()) {
2804 return;
2805 }
2806
chaviwaf87b3e2019-10-01 16:59:28 -07002807 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002808 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002809 const sp<Layer>& relative = relativeWeak.promote();
2810 if (clonedLayersMap.count(relative) > 0) {
2811 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002812 mDrawingState.zOrderRelatives.add(clonedRelative);
2813 }
2814 }
2815
2816 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2817 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2818 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2819 // still traverse the children, but the layer with the missing relativeOf will not be shown
2820 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002821 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2822 if (clonedLayersMap.count(relativeOf) > 0) {
2823 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002824 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2825 }
2826
chaviwaf87b3e2019-10-01 16:59:28 -07002827 updateClonedInputInfo(clonedLayersMap);
2828
chaviw74b03172019-08-19 11:09:03 -07002829 for (sp<Layer>& child : mDrawingChildren) {
2830 child->updateClonedRelatives(clonedLayersMap);
2831 }
2832}
2833
2834void Layer::addChildToDrawing(const sp<Layer>& layer) {
2835 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002836 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002837}
2838
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002839bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002840 const State& s(mDrawingState);
2841 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2842 return true;
2843 }
2844
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002845 sp<Layer> parent = mDrawingParent.promote();
2846 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002847}
2848
Robert Carr6a0382d2021-07-01 15:57:17 -07002849void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2850 mClonedChild = clonedChild;
2851 mHadClonedChild = true;
Vishnu Nair3be61902023-04-26 19:47:29 -07002852 mFlinger->mLayerMirrorRoots.push_back(this);
Robert Carr6a0382d2021-07-01 15:57:17 -07002853}
2854
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002855bool Layer::setDropInputMode(gui::DropInputMode mode) {
2856 if (mDrawingState.dropInputMode == mode) {
2857 return false;
2858 }
2859 mDrawingState.dropInputMode = mode;
2860 return true;
2861}
2862
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002863void Layer::cloneDrawingState(const Layer* from) {
2864 mDrawingState = from->mDrawingState;
2865 // Skip callback info since they are not applicable for cloned layers.
2866 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002867 // TODO (b/238781169) currently broken for mirror layers because we do not
2868 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002869 mDrawingState.callbackHandles = {};
2870}
2871
Patrick Williamsbb25f802022-08-30 23:02:34 +00002872void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2873 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002874 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002875 if (!listener) {
2876 return;
2877 }
2878 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002879 uint32_t currentMaxAcquiredBufferCount =
2880 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002881 listener->onReleaseBuffer({buffer->getId(), framenumber},
2882 releaseFence ? releaseFence : Fence::NO_FENCE,
2883 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002884}
2885
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002886void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
2887 ui::LayerStack layerStack) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002888 // If we are displayed on multiple displays in a single composition cycle then we would
2889 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2890 // For example we can only use it if all the displays are client comp, and we need
2891 // to merge all the client comp fences. We could do this, but for now we just
2892 // disable the optimization when a layer is composed on multiple displays.
2893 if (mClearClientCompositionFenceOnLayerDisplayed) {
2894 mLastClientCompositionFence = nullptr;
2895 } else {
2896 mClearClientCompositionFenceOnLayerDisplayed = true;
2897 }
2898
2899 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2900 // buffer that was presented on this layer. The first transaction that came in this frame that
2901 // replaced the previous buffer on this layer needs this release fence, because the fence will
2902 // let the client know when that previous buffer is removed from the screen.
2903 //
2904 // Every other transaction on this layer does not need a release fence because no other
2905 // Transactions that were set on this layer this frame are going to have their preceding buffer
2906 // removed from the display this frame.
2907 //
2908 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2909 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2910 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2911 // the previous buffer will be released this frame. The third transaction also contains a
2912 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2913 // transaction will now no longer be presented so it is released immediately and the third
2914 // transaction doesn't need a previous release fence.
2915 sp<CallbackHandle> ch;
2916 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002917 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002918 ch = handle;
2919 break;
2920 }
2921 }
2922
2923 // Prevent tracing the same release multiple times.
2924 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2925 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2926 }
2927
2928 if (ch != nullptr) {
2929 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2930 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2931 ch->name = mName;
2932 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002933 mPreviouslyPresentedLayerStacks.push_back(layerStack);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002934}
2935
2936void Layer::onSurfaceFrameCreated(
2937 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2938 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2939 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2940 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2941 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002942 if (hasBufferOrSidebandStreamInDrawing()) {
2943 // Only log for layers with a buffer, since we expect the jank data to be drained for
2944 // these, while there may be no jank listeners for bufferless layers.
2945 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2946 mName.c_str());
2947 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2948 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2949 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002950 mPendingJankClassifications.pop_front();
2951 }
2952 mPendingJankClassifications.emplace_back(surfaceFrame);
2953}
2954
2955void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2956 for (const auto& handle : mDrawingState.callbackHandles) {
Lloyd Pique30db6402023-06-26 18:56:51 +00002957 if (mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -07002958 handle->transformHint = mTransformHint;
2959 } else {
2960 handle->transformHint = mSkipReportingTransformHint
2961 ? std::nullopt
2962 : std::make_optional<uint32_t>(mTransformHintLegacy);
2963 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002964 handle->dequeueReadyTime = dequeueReadyTime;
2965 handle->currentMaxAcquiredBufferCount =
2966 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2967 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2968 handle->previousReleaseCallbackId.framenumber);
2969 }
2970
2971 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002972 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002973 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2974 break;
2975 }
2976 }
2977
2978 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002979 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002980 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2981 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002982 mDrawingState.callbackHandles = {};
2983}
2984
2985bool Layer::willPresentCurrentTransaction() const {
2986 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2987 return (getSidebandStreamChanged() || getAutoRefresh() ||
2988 (mDrawingState.modified &&
2989 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2990}
2991
2992bool Layer::setTransform(uint32_t transform) {
2993 if (mDrawingState.bufferTransform == transform) return false;
2994 mDrawingState.bufferTransform = transform;
2995 mDrawingState.modified = true;
2996 setTransactionFlags(eTransactionNeeded);
2997 return true;
2998}
2999
3000bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
3001 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
3002 mDrawingState.sequence++;
3003 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
3004 mDrawingState.modified = true;
3005 setTransactionFlags(eTransactionNeeded);
3006 return true;
3007}
3008
3009bool Layer::setBufferCrop(const Rect& bufferCrop) {
3010 if (mDrawingState.bufferCrop == bufferCrop) return false;
3011
3012 mDrawingState.sequence++;
3013 mDrawingState.bufferCrop = bufferCrop;
3014
3015 mDrawingState.modified = true;
3016 setTransactionFlags(eTransactionNeeded);
3017 return true;
3018}
3019
3020bool Layer::setDestinationFrame(const Rect& destinationFrame) {
3021 if (mDrawingState.destinationFrame == destinationFrame) return false;
3022
3023 mDrawingState.sequence++;
3024 mDrawingState.destinationFrame = destinationFrame;
3025
3026 mDrawingState.modified = true;
3027 setTransactionFlags(eTransactionNeeded);
3028 return true;
3029}
3030
3031// Translate destination frame into scale and position. If a destination frame is not set, use the
3032// provided scale and position
3033bool Layer::updateGeometry() {
3034 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
3035 mDrawingState.destinationFrame.isEmpty()) {
3036 // If destination frame is not set, use the requested transform set via
3037 // Layer::setPosition and Layer::setMatrix.
3038 return assignTransform(&mDrawingState.transform, mRequestedTransform);
3039 }
3040
3041 Rect destRect = mDrawingState.destinationFrame;
3042 int32_t destW = destRect.width();
3043 int32_t destH = destRect.height();
3044 if (destRect.left < 0) {
3045 destRect.left = 0;
3046 destRect.right = destW;
3047 }
3048 if (destRect.top < 0) {
3049 destRect.top = 0;
3050 destRect.bottom = destH;
3051 }
3052
3053 if (!mDrawingState.buffer) {
3054 ui::Transform t;
3055 t.set(destRect.left, destRect.top);
3056 return assignTransform(&mDrawingState.transform, t);
3057 }
3058
3059 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3060 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3061 // Undo any transformations on the buffer.
3062 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3063 std::swap(bufferWidth, bufferHeight);
3064 }
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003065 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003066 if (mDrawingState.transformToDisplayInverse) {
3067 if (invTransform & ui::Transform::ROT_90) {
3068 std::swap(bufferWidth, bufferHeight);
3069 }
3070 }
3071
3072 float sx = destW / static_cast<float>(bufferWidth);
3073 float sy = destH / static_cast<float>(bufferHeight);
3074 ui::Transform t;
3075 t.set(sx, 0, 0, sy);
3076 t.set(destRect.left, destRect.top);
3077 return assignTransform(&mDrawingState.transform, t);
3078}
3079
3080bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3081 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3082 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3083 return false;
3084 }
3085
3086 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3087
3088 mDrawingState.sequence++;
3089 mDrawingState.modified = true;
3090 setTransactionFlags(eTransactionNeeded);
3091
3092 return true;
3093}
3094
3095bool Layer::setPosition(float x, float y) {
3096 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3097 return false;
3098 }
3099
3100 mRequestedTransform.set(x, y);
3101
3102 mDrawingState.sequence++;
3103 mDrawingState.modified = true;
3104 setTransactionFlags(eTransactionNeeded);
3105
3106 return true;
3107}
3108
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003109void Layer::resetDrawingStateBufferInfo() {
3110 mDrawingState.producerId = 0;
3111 mDrawingState.frameNumber = 0;
3112 mDrawingState.releaseBufferListener = nullptr;
3113 mDrawingState.buffer = nullptr;
3114 mDrawingState.acquireFence = sp<Fence>::make(-1);
3115 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3116 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3117 mDrawingState.releaseBufferEndpoint = nullptr;
3118}
3119
Patrick Williamsbb25f802022-08-30 23:02:34 +00003120bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3121 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3122 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003123 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003124 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003125
3126 const bool frameNumberChanged =
3127 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3128 const uint64_t frameNumber =
3129 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003130 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003131
3132 if (mDrawingState.buffer) {
3133 mReleasePreviousBuffer = true;
3134 if (!mBufferInfo.mBuffer ||
3135 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3136 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3137 // If mDrawingState has a buffer, and we are about to update again
3138 // before swapping to drawing state, then the first buffer will be
3139 // dropped and we should decrement the pending buffer count and
3140 // call any release buffer callbacks if set.
3141 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3142 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003143 mDrawingState.acquireFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003144 decrementPendingBufferCount();
3145 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3146 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
Ady Abraham5a3e3562023-06-07 10:32:08 -07003147 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX, systemTime());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003148 mDrawingState.bufferSurfaceFrameTX.reset();
3149 }
3150 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3151 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3152 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003153 mLastClientCompositionFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003154 mLastClientCompositionFence = nullptr;
3155 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003156 } else if (buffer) {
Vishnu Nairc09c0232023-03-02 03:22:35 +00003157 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3158 // we don't want to incorrectly classify a frame if we miss the desired present time.
3159 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003160 }
3161
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003162 mDrawingState.desiredPresentTime = desiredPresentTime;
3163 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3164 mDrawingState.latchedVsyncId = info.vsyncId;
Ady Abraham55269162023-05-09 11:26:06 -07003165 mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003166 mDrawingState.modified = true;
3167 if (!buffer) {
3168 resetDrawingStateBufferInfo();
3169 setTransactionFlags(eTransactionNeeded);
3170 mDrawingState.bufferSurfaceFrameTX = nullptr;
3171 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3172 return true;
3173 }
3174
Vishnu Naird1f74982023-06-15 20:16:51 -07003175 if ((mDrawingState.producerId > bufferData.producerId) ||
3176 ((mDrawingState.producerId == bufferData.producerId) &&
3177 (mDrawingState.frameNumber > frameNumber))) {
3178 ALOGE("Out of order buffers detected for %s producedId=%d frameNumber=%" PRIu64
3179 " -> producedId=%d frameNumber=%" PRIu64,
3180 getDebugName(), mDrawingState.producerId, mDrawingState.frameNumber,
3181 bufferData.producerId, frameNumber);
3182 TransactionTraceWriter::getInstance().invoke("out_of_order_buffers_", /*overwrite=*/false);
3183 }
3184
liulijuneb489f62022-10-17 22:02:14 +08003185 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -07003186 mDrawingState.barrierProducerId =
3187 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003188 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -07003189 mDrawingState.barrierFrameNumber =
3190 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
3191
Patrick Williamsbb25f802022-08-30 23:02:34 +00003192 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3193 mDrawingState.buffer = std::move(buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003194 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3195 ? bufferData.acquireFence
3196 : Fence::NO_FENCE;
3197 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3198 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3199 // We latched this buffer unsiganled, so we need to pass the acquire fence
3200 // on the callback instead of just the acquire time, since it's unknown at
3201 // this point.
3202 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3203 } else {
3204 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3205 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003206 setTransactionFlags(eTransactionNeeded);
3207
3208 const int32_t layerId = getSequence();
3209 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3210 mOwnerUid, postTime, getGameMode());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003211
Lloyd Pique30db6402023-06-26 18:56:51 +00003212 if (mFlinger->mLegacyFrontEndEnabled) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003213 recordLayerHistoryBufferUpdate(getLayerProps());
3214 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003215
3216 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3217
3218 if (dequeueTime && *dequeueTime != 0) {
3219 const uint64_t bufferId = mDrawingState.buffer->getId();
3220 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3221 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3222 FrameTracer::FrameEvent::DEQUEUE);
3223 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3224 FrameTracer::FrameEvent::QUEUE);
3225 }
3226
3227 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3228 return true;
3229}
3230
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003231void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3232 mDrawingState.desiredPresentTime = desiredPresentTime;
3233 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3234}
3235
3236void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps) {
Ady Abraham55269162023-05-09 11:26:06 -07003237 ATRACE_CALL();
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003238 const nsecs_t presentTime = [&] {
Ady Abraham55269162023-05-09 11:26:06 -07003239 if (!mDrawingState.isAutoTimestamp) {
3240 ATRACE_FORMAT_INSTANT("desiredPresentTime");
3241 return mDrawingState.desiredPresentTime;
3242 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003243
Ady Abraham55269162023-05-09 11:26:06 -07003244 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3245 const auto prediction =
3246 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3247 mDrawingState.latchedVsyncId);
3248 if (prediction.has_value()) {
3249 ATRACE_FORMAT_INSTANT("predictedPresentTime");
3250 return prediction->presentTime;
3251 }
3252 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003253
3254 return static_cast<nsecs_t>(0);
3255 }();
Ady Abraham55269162023-05-09 11:26:06 -07003256
3257 if (ATRACE_ENABLED() && presentTime > 0) {
3258 const auto presentIn = TimePoint::fromNs(presentTime) - TimePoint::now();
3259 ATRACE_FORMAT_INSTANT("presentIn %s", to_string(presentIn).c_str());
3260 }
3261
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003262 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3263 scheduler::LayerHistory::LayerUpdateType::Buffer);
3264}
3265
3266void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps) {
3267 const nsecs_t presentTime =
3268 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
3269 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3270 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3271}
3272
Patrick Williamsbb25f802022-08-30 23:02:34 +00003273bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003274 if (mDrawingState.dataspace == dataspace) return false;
3275 mDrawingState.dataspace = dataspace;
3276 mDrawingState.modified = true;
3277 setTransactionFlags(eTransactionNeeded);
3278 return true;
3279}
3280
John Reck68796592023-01-25 13:47:12 -05003281bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07003282 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3283 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05003284 return false;
Sally Qi963049b2023-03-23 14:06:21 -07003285 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3286 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05003287 mDrawingState.modified = true;
3288 setTransactionFlags(eTransactionNeeded);
3289 return true;
3290}
3291
Alec Mourif4af03e2023-02-11 00:25:24 +00003292bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3293 if (mDrawingState.cachingHint == cachingHint) return false;
3294 mDrawingState.cachingHint = cachingHint;
3295 mDrawingState.modified = true;
3296 setTransactionFlags(eTransactionNeeded);
3297 return true;
3298}
3299
Patrick Williamsbb25f802022-08-30 23:02:34 +00003300bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3301 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3302 mDrawingState.hdrMetadata = hdrMetadata;
3303 mDrawingState.modified = true;
3304 setTransactionFlags(eTransactionNeeded);
3305 return true;
3306}
3307
3308bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003309 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003310 mDrawingState.surfaceDamageRegion = surfaceDamage;
3311 mDrawingState.modified = true;
3312 setTransactionFlags(eTransactionNeeded);
3313 return true;
3314}
3315
3316bool Layer::setApi(int32_t api) {
3317 if (mDrawingState.api == api) return false;
3318 mDrawingState.api = api;
3319 mDrawingState.modified = true;
3320 setTransactionFlags(eTransactionNeeded);
3321 return true;
3322}
3323
3324bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3325 if (mDrawingState.sidebandStream == sidebandStream) return false;
3326
3327 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3328 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3329 } else if (sidebandStream != nullptr) {
3330 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3331 }
3332
3333 mDrawingState.sidebandStream = sidebandStream;
3334 mDrawingState.modified = true;
3335 setTransactionFlags(eTransactionNeeded);
3336 if (!mSidebandStreamChanged.exchange(true)) {
3337 // mSidebandStreamChanged was false
3338 mFlinger->onLayerUpdate();
3339 }
3340 return true;
3341}
3342
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003343bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3344 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003345 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3346 if (handles.empty()) {
3347 mReleasePreviousBuffer = false;
3348 return false;
3349 }
3350
Pascal Muetschard81cef292023-02-06 12:18:52 +01003351 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003352 for (const auto& handle : handles) {
3353 // If this transaction set a buffer on this layer, release its previous buffer
3354 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3355
3356 // If this layer will be presented in this frame
3357 if (willPresent) {
3358 // If this transaction set an acquire fence on this layer, set its acquire time
3359 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3360 handle->frameNumber = mDrawingState.frameNumber;
3361
3362 // Store so latched time and release fence can be set
3363 mDrawingState.callbackHandles.push_back(handle);
3364
3365 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003366 // Queue this handle to be notified below.
3367 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003368 }
3369 }
3370
Pascal Muetschard81cef292023-02-06 12:18:52 +01003371 if (!remainingHandles.empty()) {
3372 // Notify the transaction completed threads these handles are done. These are only the
3373 // handles that were not added to the mDrawingState, which will be notified later.
3374 std::vector<JankData> jankData;
3375 transferAvailableJankData(remainingHandles, jankData);
3376 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3377 }
3378
Patrick Williamsbb25f802022-08-30 23:02:34 +00003379 mReleasePreviousBuffer = false;
3380 mCallbackHandleAcquireTimeOrFence = -1;
3381
3382 return willPresent;
3383}
3384
3385Rect Layer::getBufferSize(const State& /*s*/) const {
3386 // for buffer state layers we use the display frame size as the buffer size.
3387
3388 if (mBufferInfo.mBuffer == nullptr) {
3389 return Rect::INVALID_RECT;
3390 }
3391
3392 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3393 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3394
3395 // Undo any transformations on the buffer and return the result.
3396 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3397 std::swap(bufWidth, bufHeight);
3398 }
3399
3400 if (getTransformToDisplayInverse()) {
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003401 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003402 if (invTransform & ui::Transform::ROT_90) {
3403 std::swap(bufWidth, bufHeight);
3404 }
3405 }
3406
3407 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3408}
3409
3410FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3411 if (mBufferInfo.mBuffer == nullptr) {
3412 return parentBounds;
3413 }
3414
3415 return getBufferSize(getDrawingState()).toFloatRect();
3416}
3417
3418bool Layer::fenceHasSignaled() const {
3419 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3420 return true;
3421 }
3422
3423 const bool fenceSignaled =
3424 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3425 if (!fenceSignaled) {
3426 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3427 TimeStats::LatchSkipReason::LateAcquire);
3428 }
3429
3430 return fenceSignaled;
3431}
3432
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003433void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003434 for (const auto& handle : mDrawingState.callbackHandles) {
3435 handle->refreshStartTime = refreshStartTime;
3436 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003437}
3438
3439void Layer::setAutoRefresh(bool autoRefresh) {
3440 mDrawingState.autoRefresh = autoRefresh;
3441}
3442
3443bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3444 // 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 +00003445 auto* snapshot = editLayerSnapshot();
3446 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003447
3448 if (mSidebandStreamChanged.exchange(false)) {
3449 const State& s(getDrawingState());
3450 // mSidebandStreamChanged was true
3451 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003452 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003453 if (mSidebandStream != nullptr) {
3454 setTransactionFlags(eTransactionNeeded);
3455 mFlinger->setTransactionFlags(eTraversalNeeded);
3456 }
3457 recomputeVisibleRegions = true;
3458
3459 return true;
3460 }
3461 return false;
3462}
3463
3464bool Layer::hasFrameUpdate() const {
3465 const State& c(getDrawingState());
3466 return (mDrawingStateModified || mDrawingState.modified) &&
3467 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3468}
3469
Vishnu Naird47bcee2023-02-24 18:08:51 +00003470void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003471 const State& s(getDrawingState());
3472
3473 if (!s.buffer) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003474 if (bgColorOnly || mBufferInfo.mBuffer) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003475 for (auto& handle : mDrawingState.callbackHandles) {
3476 handle->latchTime = latchTime;
3477 }
3478 }
3479 return;
3480 }
3481
3482 for (auto& handle : mDrawingState.callbackHandles) {
3483 if (handle->frameNumber == mDrawingState.frameNumber) {
3484 handle->latchTime = latchTime;
3485 }
3486 }
3487
3488 const int32_t layerId = getSequence();
3489 const uint64_t bufferId = mDrawingState.buffer->getId();
3490 const uint64_t frameNumber = mDrawingState.frameNumber;
3491 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3492 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3493 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3494
3495 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3496 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3497 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3498 FrameTracer::FrameEvent::LATCH);
3499
3500 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3501 if (bufferSurfaceFrame != nullptr &&
3502 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3503 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3504 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3505 // are processing the next state.
3506 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3507 mDrawingState.acquireFenceTime->getSignalTime(),
3508 latchTime);
3509 mDrawingState.bufferSurfaceFrameTX.reset();
3510 }
3511
3512 std::deque<sp<CallbackHandle>> remainingHandles;
3513 mFlinger->getTransactionCallbackInvoker()
3514 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3515 mDrawingState.callbackHandles = remainingHandles;
3516
3517 mDrawingStateModified = false;
3518}
3519
3520void Layer::gatherBufferInfo() {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003521 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3522 mPreviousReleaseBufferEndpoint = mBufferInfo.mReleaseBufferEndpoint;
3523 if (!mDrawingState.buffer) {
3524 mBufferInfo = {};
3525 return;
3526 }
3527
3528 if ((!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer))) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003529 decrementPendingBufferCount();
3530 }
3531
Patrick Williamsbb25f802022-08-30 23:02:34 +00003532 mBufferInfo.mBuffer = mDrawingState.buffer;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003533 mBufferInfo.mReleaseBufferEndpoint = mDrawingState.releaseBufferEndpoint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003534 mBufferInfo.mFence = mDrawingState.acquireFence;
3535 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3536 mBufferInfo.mPixelFormat =
3537 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3538 mBufferInfo.mFrameLatencyNeeded = true;
3539 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3540 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3541 mBufferInfo.mFence = mDrawingState.acquireFence;
3542 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3543 auto lastDataspace = mBufferInfo.mDataspace;
3544 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003545 if (mBufferInfo.mBuffer != nullptr) {
3546 auto& mapper = GraphicBufferMapper::get();
3547 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
3548 // and don't need to possibly remaps buffers.
3549 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
3550 status_t err = OK;
3551 {
3552 ATRACE_NAME("getDataspace");
3553 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
3554 }
3555 if (err != OK || dataspace != mBufferInfo.mDataspace) {
3556 {
3557 ATRACE_NAME("setDataspace");
3558 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
3559 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
3560 }
3561
3562 // Some GPU drivers may cache gralloc metadata which means before we composite we need
3563 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
3564 // compatible with old vendors, with a ticking clock.
3565 static const int32_t kVendorVersion =
3566 base::GetIntProperty("ro.vndk.version", __ANDROID_API_FUTURE__);
3567 if (const auto format =
3568 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
3569 mBufferInfo.mBuffer->getPixelFormat());
3570 err == OK && kVendorVersion < __ANDROID_API_U__ &&
3571 (format ==
3572 aidl::android::hardware::graphics::common::PixelFormat::
3573 IMPLEMENTATION_DEFINED ||
3574 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
3575 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
3576 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
3577 mBufferInfo.mBuffer->remapBuffer();
3578 }
3579 }
3580 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003581 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003582 mFlinger->mHdrLayerInfoChanged = true;
3583 }
Sally Qi963049b2023-03-23 14:06:21 -07003584 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3585 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05003586 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003587 }
3588 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3589 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3590 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3591 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3592 mBufferInfo.mApi = mDrawingState.api;
3593 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003594}
3595
3596Rect Layer::computeBufferCrop(const State& s) {
3597 if (s.buffer && !s.bufferCrop.isEmpty()) {
3598 Rect bufferCrop;
3599 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3600 return bufferCrop;
3601 } else if (s.buffer) {
3602 return s.buffer->getBounds();
3603 } else {
3604 return s.bufferCrop;
3605 }
3606}
3607
Vishnu Nairde177252023-04-21 12:44:10 -07003608sp<Layer> Layer::createClone(uint32_t mirrorRootId) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003609 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3610 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003611 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Vishnu Nairde177252023-04-21 12:44:10 -07003612 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this), mirrorRootId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003613 return layer;
3614}
3615
Patrick Williamsbb25f802022-08-30 23:02:34 +00003616void Layer::decrementPendingBufferCount() {
3617 int32_t pendingBuffers = --mPendingBufferTransactions;
3618 tracePendingBufferCount(pendingBuffers);
3619}
3620
3621void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3622 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3623}
3624
3625/*
3626 * We don't want to send the layer's transform to input, but rather the
3627 * parent's transform. This is because Layer's transform is
3628 * information about how the buffer is placed on screen. The parent's
3629 * transform makes more sense to send since it's information about how the
3630 * layer is placed on screen. This transform is used by input to determine
3631 * how to go from screen space back to window space.
3632 */
3633ui::Transform Layer::getInputTransform() const {
3634 if (!hasBufferOrSidebandStream()) {
3635 return getTransform();
3636 }
3637 sp<Layer> parent = mDrawingParent.promote();
3638 if (parent == nullptr) {
3639 return ui::Transform();
3640 }
3641
3642 return parent->getTransform();
3643}
3644
3645/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003646 * Returns the bounds used to fill the input frame and the touchable region.
3647 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003648 * Similar to getInputTransform, we need to update the bounds to include the transform.
3649 * This is because bounds don't include the buffer transform, where the input assumes
3650 * that's already included.
3651 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003652std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3653 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3654 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3655 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3656 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3657 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003658 }
3659
Vishnu Nairfed7c122023-03-18 01:54:43 +00003660 bool inputBoundsValid = croppedBufferSize.isValid();
3661 if (!inputBoundsValid) {
3662 /**
3663 * Input bounds are based on the layer crop or buffer size. But if we are using
3664 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3665 * we can use the parent bounds as the input bounds if the layer does not have buffer
3666 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3667 * use the parent bounds. A layer without a buffer can get input. So when a window is
3668 * initially added, its touchable region can fill its parent layer bounds and that can
3669 * have negative consequences.
3670 */
3671 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003672 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003673
3674 // Clamp surface inset to the input bounds.
3675 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3676 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3677 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3678
3679 // Apply the insets to the input bounds.
3680 inputBounds.left += xSurfaceInset;
3681 inputBounds.top += ySurfaceInset;
3682 inputBounds.right -= xSurfaceInset;
3683 inputBounds.bottom -= ySurfaceInset;
3684
3685 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003686}
3687
Ady Abraham005398b2023-06-05 13:59:41 -07003688bool Layer::isSimpleBufferUpdate(const layer_state_t& s) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003689 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3690
3691 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3692 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3693 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3694 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3695 layer_state_t::eReparent;
3696
Patrick Williamsbb25f802022-08-30 23:02:34 +00003697 if ((s.what & requiredFlags) != requiredFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003698 ATRACE_FORMAT_INSTANT("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3699 (s.what | requiredFlags) & ~s.what);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003700 return false;
3701 }
3702
3703 if (s.what & deniedFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003704 ATRACE_FORMAT_INSTANT("%s: false [has denied flags 0x%" PRIx64 "]", __func__,
3705 s.what & deniedFlags);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003706 return false;
3707 }
3708
Patrick Williamsbb25f802022-08-30 23:02:34 +00003709 if (s.what & layer_state_t::ePositionChanged) {
3710 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
Ady Abraham005398b2023-06-05 13:59:41 -07003711 ATRACE_FORMAT_INSTANT("%s: false [ePositionChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003712 return false;
3713 }
3714 }
3715
3716 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003717 if (mDrawingState.color.a != s.color.a) {
Ady Abraham005398b2023-06-05 13:59:41 -07003718 ATRACE_FORMAT_INSTANT("%s: false [eAlphaChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003719 return false;
3720 }
3721 }
3722
3723 if (s.what & layer_state_t::eColorTransformChanged) {
3724 if (mDrawingState.colorTransform != s.colorTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003725 ATRACE_FORMAT_INSTANT("%s: false [eColorTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003726 return false;
3727 }
3728 }
3729
3730 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003731 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Ady Abraham005398b2023-06-05 13:59:41 -07003732 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundColorChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003733 return false;
3734 }
3735 }
3736
3737 if (s.what & layer_state_t::eMatrixChanged) {
3738 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3739 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3740 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3741 mRequestedTransform.dsdy() != s.matrix.dsdy) {
Ady Abraham005398b2023-06-05 13:59:41 -07003742 ATRACE_FORMAT_INSTANT("%s: false [eMatrixChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003743 return false;
3744 }
3745 }
3746
3747 if (s.what & layer_state_t::eCornerRadiusChanged) {
3748 if (mDrawingState.cornerRadius != s.cornerRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003749 ATRACE_FORMAT_INSTANT("%s: false [eCornerRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003750 return false;
3751 }
3752 }
3753
3754 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3755 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
Ady Abraham005398b2023-06-05 13:59:41 -07003756 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003757 return false;
3758 }
3759 }
3760
Vishnu Nairbbceb462022-10-10 04:52:13 +00003761 if (s.what & layer_state_t::eBufferTransformChanged) {
3762 if (mDrawingState.bufferTransform != s.bufferTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003763 ATRACE_FORMAT_INSTANT("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003764 return false;
3765 }
3766 }
3767
3768 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3769 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
Ady Abraham005398b2023-06-05 13:59:41 -07003770 ATRACE_FORMAT_INSTANT("%s: false [eTransformToDisplayInverseChanged changed]",
3771 __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003772 return false;
3773 }
3774 }
3775
3776 if (s.what & layer_state_t::eCropChanged) {
3777 if (mDrawingState.crop != s.crop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003778 ATRACE_FORMAT_INSTANT("%s: false [eCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003779 return false;
3780 }
3781 }
3782
3783 if (s.what & layer_state_t::eDataspaceChanged) {
3784 if (mDrawingState.dataspace != s.dataspace) {
Ady Abraham005398b2023-06-05 13:59:41 -07003785 ATRACE_FORMAT_INSTANT("%s: false [eDataspaceChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003786 return false;
3787 }
3788 }
3789
3790 if (s.what & layer_state_t::eHdrMetadataChanged) {
3791 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
Ady Abraham005398b2023-06-05 13:59:41 -07003792 ATRACE_FORMAT_INSTANT("%s: false [eHdrMetadataChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003793 return false;
3794 }
3795 }
3796
3797 if (s.what & layer_state_t::eSidebandStreamChanged) {
3798 if (mDrawingState.sidebandStream != s.sidebandStream) {
Ady Abraham005398b2023-06-05 13:59:41 -07003799 ATRACE_FORMAT_INSTANT("%s: false [eSidebandStreamChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003800 return false;
3801 }
3802 }
3803
3804 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3805 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
Ady Abraham005398b2023-06-05 13:59:41 -07003806 ATRACE_FORMAT_INSTANT("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003807 return false;
3808 }
3809 }
3810
3811 if (s.what & layer_state_t::eShadowRadiusChanged) {
3812 if (mDrawingState.shadowRadius != s.shadowRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003813 ATRACE_FORMAT_INSTANT("%s: false [eShadowRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003814 return false;
3815 }
3816 }
3817
3818 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3819 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
Ady Abraham005398b2023-06-05 13:59:41 -07003820 ATRACE_FORMAT_INSTANT("%s: false [eFixedTransformHintChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003821 return false;
3822 }
3823 }
3824
3825 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3826 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
Ady Abraham005398b2023-06-05 13:59:41 -07003827 ATRACE_FORMAT_INSTANT("%s: false [eTrustedOverlayChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003828 return false;
3829 }
3830 }
3831
3832 if (s.what & layer_state_t::eStretchChanged) {
3833 StretchEffect temp = s.stretchEffect;
3834 temp.sanitize();
3835 if (mDrawingState.stretchEffect != temp) {
Ady Abraham005398b2023-06-05 13:59:41 -07003836 ATRACE_FORMAT_INSTANT("%s: false [eStretchChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003837 return false;
3838 }
3839 }
3840
3841 if (s.what & layer_state_t::eBufferCropChanged) {
3842 if (mDrawingState.bufferCrop != s.bufferCrop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003843 ATRACE_FORMAT_INSTANT("%s: false [eBufferCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003844 return false;
3845 }
3846 }
3847
3848 if (s.what & layer_state_t::eDestinationFrameChanged) {
3849 if (mDrawingState.destinationFrame != s.destinationFrame) {
Ady Abraham005398b2023-06-05 13:59:41 -07003850 ATRACE_FORMAT_INSTANT("%s: false [eDestinationFrameChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003851 return false;
3852 }
3853 }
3854
3855 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3856 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
Ady Abraham005398b2023-06-05 13:59:41 -07003857 ATRACE_FORMAT_INSTANT("%s: false [eDimmingEnabledChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003858 return false;
3859 }
3860 }
3861
John Reck68796592023-01-25 13:47:12 -05003862 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07003863 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
3864 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
Ady Abraham005398b2023-06-05 13:59:41 -07003865 ATRACE_FORMAT_INSTANT("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05003866 return false;
3867 }
3868 }
3869
Patrick Williamsbb25f802022-08-30 23:02:34 +00003870 return true;
3871}
3872
Vishnu Naire14c6b32022-08-06 04:20:15 +00003873sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003874 // 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 +00003875 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003876}
3877
Vishnu Naire14c6b32022-08-06 04:20:15 +00003878const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003879 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003880}
3881
Vishnu Naire14c6b32022-08-06 04:20:15 +00003882LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003883 return mSnapshot.get();
3884}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003885
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003886std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3887 return std::move(mSnapshot);
3888}
3889
3890void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3891 mSnapshot = std::move(snapshot);
3892}
3893
Patrick Williamsbb25f802022-08-30 23:02:34 +00003894const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003895 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003896}
3897
Patrick Williams7584c6a2022-10-29 02:10:58 +00003898sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003899 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003900 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3901 return result;
3902}
3903
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003904sp<LayerFE> Layer::getCompositionEngineLayerFE(
3905 const frontend::LayerHierarchy::TraversalPath& path) {
3906 for (auto& [p, layerFE] : mLayerFEs) {
3907 if (p == path) {
3908 return layerFE;
3909 }
3910 }
3911 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3912 mLayerFEs.emplace_back(path, layerFE);
3913 return layerFE;
3914}
3915
Patrick Williamsbb25f802022-08-30 23:02:34 +00003916void Layer::useSurfaceDamage() {
3917 if (mFlinger->mForceFullDamage) {
3918 surfaceDamageRegion = Region::INVALID_REGION;
3919 } else {
3920 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3921 }
3922}
3923
3924void Layer::useEmptyDamage() {
3925 surfaceDamageRegion.clear();
3926}
3927
3928bool Layer::isOpaque(const Layer::State& s) const {
3929 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3930 // layer's opaque flag.
3931 if (!hasSomethingToDraw()) {
3932 return false;
3933 }
3934
3935 // if the layer has the opaque flag, then we're always opaque
3936 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3937 return true;
3938 }
3939
3940 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003941 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003942 return true;
3943 }
3944
3945 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3946 return fillsColor() && getAlpha() == 1.0_hf;
3947}
3948
3949bool Layer::canReceiveInput() const {
3950 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3951}
3952
3953bool Layer::isVisible() const {
3954 if (!hasSomethingToDraw()) {
3955 return false;
3956 }
3957
3958 if (isHiddenByPolicy()) {
3959 return false;
3960 }
3961
3962 return getAlpha() > 0.0f || hasBlur();
3963}
3964
3965void Layer::onPostComposition(const DisplayDevice* display,
3966 const std::shared_ptr<FenceTime>& glDoneFence,
3967 const std::shared_ptr<FenceTime>& presentFence,
3968 const CompositorTiming& compositorTiming) {
3969 // mFrameLatencyNeeded is true when a new frame was latched for the
3970 // composition.
3971 if (!mBufferInfo.mFrameLatencyNeeded) return;
3972
3973 for (const auto& handle : mDrawingState.callbackHandles) {
3974 handle->gpuCompositionDoneFence = glDoneFence;
3975 handle->compositorTiming = compositorTiming;
3976 }
3977
3978 // Update mFrameTracker.
3979 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3980 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3981
3982 const int32_t layerId = getSequence();
3983 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3984
3985 const auto outputLayer = findOutputLayerForDisplay(display);
3986 if (outputLayer && outputLayer->requiresClientComposition()) {
3987 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3988 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3989 clientCompositionTimestamp,
3990 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3991 // Update the SurfaceFrames in the drawing state
3992 if (mDrawingState.bufferSurfaceFrameTX) {
3993 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3994 }
3995 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3996 surfaceFrame->setGpuComposition();
3997 }
3998 }
3999
4000 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
4001 if (frameReadyFence->isValid()) {
4002 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
4003 } else {
4004 // There was no fence for this frame, so assume that it was ready
4005 // to be presented at the desired present time.
4006 mFrameTracker.setFrameReadyTime(desiredPresentTime);
4007 }
4008
4009 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08004010 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004011 const std::optional<Fps> renderRate =
4012 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
4013
4014 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
4015 const auto gameMode = getGameMode();
4016
4017 if (presentFence->isValid()) {
4018 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
4019 refreshRate, renderRate, vote, gameMode);
4020 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4021 presentFence,
4022 FrameTracer::FrameEvent::PRESENT_FENCE);
4023 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
4024 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
4025 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04004026 // The HWC doesn't support present fences, so use the present timestamp instead.
4027 const nsecs_t presentTimestamp =
4028 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
4029
4030 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
4031 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
4032 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
4033
Patrick Williamsbb25f802022-08-30 23:02:34 +00004034 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
4035 refreshRate, renderRate, vote, gameMode);
4036 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
4037 mCurrentFrameNumber, actualPresentTime,
4038 FrameTracer::FrameEvent::PRESENT_FENCE);
4039 mFrameTracker.setActualPresentTime(actualPresentTime);
4040 }
4041 }
4042
4043 mFrameTracker.advanceFrame();
4044 mBufferInfo.mFrameLatencyNeeded = false;
4045}
4046
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004047bool Layer::willReleaseBufferOnLatch() const {
4048 return !mDrawingState.buffer && mBufferInfo.mBuffer;
4049}
4050
Patrick Williamsbb25f802022-08-30 23:02:34 +00004051bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00004052 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
4053 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
4054}
4055
4056bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004057 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
4058 getDrawingState().frameNumber);
4059
4060 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
4061
4062 if (refreshRequired) {
4063 return refreshRequired;
4064 }
4065
4066 // If the head buffer's acquire fence hasn't signaled yet, return and
4067 // try again later
4068 if (!fenceHasSignaled()) {
4069 ATRACE_NAME("!fenceHasSignaled()");
4070 mFlinger->onLayerUpdate();
4071 return false;
4072 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00004073 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004074
4075 // Capture the old state of the layer for comparisons later
4076 BufferInfo oldBufferInfo = mBufferInfo;
4077 const bool oldOpacity = isOpaque(mDrawingState);
4078 mPreviousFrameNumber = mCurrentFrameNumber;
4079 mCurrentFrameNumber = mDrawingState.frameNumber;
4080 gatherBufferInfo();
4081
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004082 if (mBufferInfo.mBuffer) {
4083 // We latched a buffer that will be presented soon. Clear the previously presented layer
4084 // stack list.
4085 mPreviouslyPresentedLayerStacks.clear();
4086 }
4087
4088 if (mDrawingState.buffer == nullptr) {
4089 const bool bufferReleased = oldBufferInfo.mBuffer != nullptr;
4090 recomputeVisibleRegions = bufferReleased;
4091 return bufferReleased;
4092 }
4093
Patrick Williamsbb25f802022-08-30 23:02:34 +00004094 if (oldBufferInfo.mBuffer == nullptr) {
4095 // the first time we receive a buffer, we need to trigger a
4096 // geometry invalidation.
4097 recomputeVisibleRegions = true;
4098 }
4099
4100 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
4101 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
4102 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
4103 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
4104 recomputeVisibleRegions = true;
4105 }
4106
4107 if (oldBufferInfo.mBuffer != nullptr) {
4108 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
4109 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
4110 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
4111 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
4112 recomputeVisibleRegions = true;
4113 }
4114 }
4115
4116 if (oldOpacity != isOpaque(mDrawingState)) {
4117 recomputeVisibleRegions = true;
4118 }
4119
4120 return true;
4121}
4122
4123bool Layer::hasReadyFrame() const {
4124 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4125}
4126
4127bool Layer::isProtected() const {
4128 return (mBufferInfo.mBuffer != nullptr) &&
4129 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4130}
4131
Patrick Williamsbb25f802022-08-30 23:02:34 +00004132void Layer::latchAndReleaseBuffer() {
4133 if (hasReadyFrame()) {
4134 bool ignored = false;
4135 latchBuffer(ignored, systemTime());
4136 }
4137 releasePendingBuffer(systemTime());
4138}
4139
4140PixelFormat Layer::getPixelFormat() const {
4141 return mBufferInfo.mPixelFormat;
4142}
4143
4144bool Layer::getTransformToDisplayInverse() const {
4145 return mBufferInfo.mTransformToDisplayInverse;
4146}
4147
4148Rect Layer::getBufferCrop() const {
4149 // this is the crop rectangle that applies to the buffer
4150 // itself (as opposed to the window)
4151 if (!mBufferInfo.mCrop.isEmpty()) {
4152 // if the buffer crop is defined, we use that
4153 return mBufferInfo.mCrop;
4154 } else if (mBufferInfo.mBuffer != nullptr) {
4155 // otherwise we use the whole buffer
4156 return mBufferInfo.mBuffer->getBounds();
4157 } else {
4158 // if we don't have a buffer yet, we use an empty/invalid crop
4159 return Rect();
4160 }
4161}
4162
4163uint32_t Layer::getBufferTransform() const {
4164 return mBufferInfo.mTransform;
4165}
4166
4167ui::Dataspace Layer::getDataSpace() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004168 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4169}
4170
4171ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4172 ui::Dataspace updatedDataspace = dataspace;
4173 // translate legacy dataspaces to modern dataspaces
4174 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00004175 // Treat unknown dataspaces as V0_sRGB
4176 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00004177 case ui::Dataspace::SRGB:
4178 updatedDataspace = ui::Dataspace::V0_SRGB;
4179 break;
4180 case ui::Dataspace::SRGB_LINEAR:
4181 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4182 break;
4183 case ui::Dataspace::JFIF:
4184 updatedDataspace = ui::Dataspace::V0_JFIF;
4185 break;
4186 case ui::Dataspace::BT601_625:
4187 updatedDataspace = ui::Dataspace::V0_BT601_625;
4188 break;
4189 case ui::Dataspace::BT601_525:
4190 updatedDataspace = ui::Dataspace::V0_BT601_525;
4191 break;
4192 case ui::Dataspace::BT709:
4193 updatedDataspace = ui::Dataspace::V0_BT709;
4194 break;
4195 default:
4196 break;
4197 }
4198
4199 return updatedDataspace;
4200}
4201
4202sp<GraphicBuffer> Layer::getBuffer() const {
4203 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4204}
4205
Vishnu Nairb76d99a2023-03-19 18:22:31 -07004206void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4207 mTransformHintLegacy = getFixedTransformHint();
4208 if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4209 mTransformHintLegacy = displayTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004210 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004211 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004212}
4213
4214const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4215 return mBufferInfo.mBuffer;
4216}
4217
4218bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004219 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004220 return false;
4221 }
4222
4223 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004224 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004225 mDrawingState.modified = true;
4226 setTransactionFlags(eTransactionNeeded);
4227 return true;
4228}
4229
4230bool Layer::fillsColor() const {
4231 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4232 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4233}
4234
4235bool Layer::hasBlur() const {
4236 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4237}
4238
Vishnu Nairba354102022-08-01 00:14:18 +00004239void Layer::updateSnapshot(bool updateGeometry) {
4240 if (!getCompositionEngineLayerFE()) {
4241 return;
4242 }
4243
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004244 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004245 if (updateGeometry) {
4246 prepareBasicGeometryCompositionState();
4247 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004248 snapshot->roundedCorner = getRoundedCornerState();
4249 snapshot->stretchEffect = getStretchEffect();
4250 snapshot->transformedBounds = mScreenBounds;
4251 if (mEffectiveShadowRadius > 0.f) {
4252 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4253
4254 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4255 // it if transparent regions are present. This may not be necessary since shadows are
4256 // typically cast by layers without transparent regions.
4257 snapshot->shadowSettings.boundaries = mBounds;
4258
4259 const float casterAlpha = snapshot->alpha;
4260 const bool casterIsOpaque =
4261 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4262
4263 // If the casting layer is translucent, we need to fill in the shadow underneath the
4264 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4265 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4266 snapshot->shadowSettings.ambientColor *= casterAlpha;
4267 snapshot->shadowSettings.spotColor *= casterAlpha;
4268 }
4269 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004270 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004271 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004272 snapshot->layerOpaqueFlagSet =
4273 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004274 sp<Layer> p = mDrawingParent.promote();
4275 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004276 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004277 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004278 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004279 }
4280 snapshot->bufferSize = getBufferSize(mDrawingState);
4281 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004282 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004283 preparePerFrameCompositionState();
4284}
4285
Vishnu Naire14c6b32022-08-06 04:20:15 +00004286void Layer::updateChildrenSnapshots(bool updateGeometry) {
4287 for (const sp<Layer>& child : mDrawingChildren) {
4288 child->updateSnapshot(updateGeometry);
4289 child->updateChildrenSnapshots(updateGeometry);
4290 }
4291}
4292
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004293void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4294 mSnapshot->layerMetadata = parentMetadata;
4295 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4296 for (const sp<Layer>& child : mDrawingChildren) {
4297 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4298 }
4299}
4300
4301void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4302 std::unordered_set<Layer*>& visited) {
4303 if (visited.find(this) != visited.end()) {
4304 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4305 return;
4306 }
4307 visited.insert(this);
4308
4309 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4310
4311 if (mDrawingState.zOrderRelatives.empty()) {
4312 return;
4313 }
4314 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4315 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4316 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4317 sp<Layer> relative = weakRelative.promote();
4318 if (!relative) {
4319 continue;
4320 }
4321 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4322 }
4323}
4324
Chavi Weingarten328a8312023-01-26 21:17:52 +00004325bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004326 TrustedPresentationListener const& listener) {
4327 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4328 mTrustedPresentationListener = listener;
4329 mTrustedPresentationThresholds = thresholds;
4330 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4331 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4332 mFlinger->mNumTrustedPresentationListeners++;
4333 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4334 mFlinger->mNumTrustedPresentationListeners--;
4335 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004336
4337 // Reset trusted presentation states to ensure we start the time again.
4338 mEnteredTrustedPresentationStateTime = -1;
4339 mLastReportedTrustedPresentationState = false;
4340 mLastComputedTrustedPresentationState = false;
4341
4342 // If there's a new trusted presentation listener, the code needs to go through the composite
4343 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4344 // we're already in the requested state.
4345 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004346}
4347
Vishnu Naira156f482023-02-22 00:23:38 +00004348void Layer::updateLastLatchTime(nsecs_t latchTime) {
4349 mLastLatchTime = latchTime;
4350}
4351
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004352} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004353
4354#if defined(__gl_h_)
4355#error "don't include gl/gl.h in this file"
4356#endif
4357
4358#if defined(__gl2_h_)
4359#error "don't include gl2/gl2.h in this file"
4360#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004361
4362// TODO(b/129481165): remove the #pragma below and fix conversion issues
4363#pragma clang diagnostic pop // ignored "-Wconversion"