blob: 93ebc8cc932ef47a036cea7e909df7b211b194d0 [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>
Steven Thomas62a4cf82020-01-31 12:04:03 -080030#include <android/native_window.h>
Vishnu Nair0f085c62019-08-30 08:49:12 -070031#include <binder/IPCThreadState.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000032#include <compositionengine/CompositionEngine.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080033#include <compositionengine/Display.h>
Lloyd Piquea83776c2019-01-29 18:42:32 -080034#include <compositionengine/LayerFECompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080035#include <compositionengine/OutputLayer.h>
36#include <compositionengine/impl/OutputLayerCompositionState.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070037#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070038#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070039#include <cutils/properties.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070040#include <ftl/enum.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080041#include <ftl/fake_guard.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080042#include <gui/BufferItem.h>
43#include <gui/LayerDebugInfo.h>
44#include <gui/Surface.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000045#include <gui/TraceUtils.h>
Alec Mourie60041e2019-06-14 18:59:51 -070046#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070047#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070049#include <stdint.h>
50#include <stdlib.h>
51#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000052#include <system/graphics-base-v1.0.h>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070053#include <ui/DataspaceUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080054#include <ui/DebugUtils.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000055#include <ui/FloatRect.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080056#include <ui/GraphicBuffer.h>
57#include <ui/PixelFormat.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000058#include <ui/Rect.h>
59#include <ui/Transform.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060#include <utils/Errors.h>
61#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080062#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080064#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065
Alec Mourie60041e2019-06-14 18:59:51 -070066#include <algorithm>
67#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070068#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070069#include <sstream>
70
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070071#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080072#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070073#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070074#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +000075#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000076#include "FrontEnd/LayerHandle.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080077#include "LayerProtoHelper.h"
Josh Gao194ff392022-09-08 16:19:29 -070078#include "MutexUtils.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080080#include "TimeStats/TimeStats.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070081#include "TunnelModeEnabledReporter.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070082
David Sodman41fdfc92017-11-06 16:09:56 -080083#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000084#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086namespace android {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010087namespace {
88constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000089
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000090const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000091
Patrick Williamsbb25f802022-08-30 23:02:34 +000092bool assignTransform(ui::Transform* dst, ui::Transform& from) {
93 if (*dst == from) {
94 return false;
95 }
96 *dst = from;
97 return true;
98}
99
100TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
101 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
102 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
103 const auto frameRateCompatibility = [frameRate] {
104 switch (frameRate.type) {
105 case Layer::FrameRateCompatibility::Default:
106 return FrameRateCompatibility::Default;
107 case Layer::FrameRateCompatibility::ExactOrMultiple:
108 return FrameRateCompatibility::ExactOrMultiple;
109 default:
110 return FrameRateCompatibility::Undefined;
111 }
112 }();
113
114 const auto seamlessness = [frameRate] {
115 switch (frameRate.seamlessness) {
116 case scheduler::Seamlessness::OnlySeamless:
117 return Seamlessness::ShouldBeSeamless;
118 case scheduler::Seamlessness::SeamedAndSeamless:
119 return Seamlessness::NotRequired;
120 default:
121 return Seamlessness::Undefined;
122 }
123 }();
124
125 return TimeStats::SetFrameRateVote{.frameRate = frameRate.rate.getValue(),
126 .frameRateCompatibility = frameRateCompatibility,
127 .seamlessness = seamlessness};
128}
129
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100130} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800131
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700132using namespace ftl::flag_operators;
133
Yiwei Zhang5434a782018-12-05 18:06:32 -0800134using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000135using frontend::LayerSnapshot;
136using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800137using gui::GameMode;
138using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500139using gui::WindowInfo;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800140
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700141using PresentState = frametimeline::SurfaceFrame::PresentState;
142
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700143Layer::Layer(const LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000144 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700145 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000146 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700147 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800148 mWindowType(static_cast<WindowInfo::Type>(
149 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000150 mLayerCreationFlags(args.flags),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000151 mBorderEnabled(false),
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();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000216 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000217 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800218}
219
220void Layer::onFirstRef() {
221 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700222}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700223
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700224Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000225 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
226 "Layer destructor called off the main thread.");
227
Patrick Williamsbb25f802022-08-30 23:02:34 +0000228 // The original layer and the clone layer share the same texture and buffer. Therefore, only
229 // one of the layers, in this case the original layer, needs to handle the deletion. The
230 // original layer and the clone should be removed at the same time so there shouldn't be any
231 // issue with the clone layer trying to use the texture.
232 if (mBufferInfo.mBuffer != nullptr) {
233 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
234 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800235 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000236 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000237 const int32_t layerId = getSequence();
238 mFlinger->mTimeStats->onDestroy(layerId);
239 mFlinger->mFrameTracer->onDestroy(layerId);
240
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000241 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700242 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700243
244 if (mDrawingState.sidebandStream != nullptr) {
245 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
246 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700247 if (mHadClonedChild) {
Vishnu Nair3be61902023-04-26 19:47:29 -0700248 auto& roots = mFlinger->mLayerMirrorRoots;
249 roots.erase(std::remove(roots.begin(), roots.end(), this), roots.end());
Robert Carr6a0382d2021-07-01 15:57:17 -0700250 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000251 if (hasTrustedPresentationListener()) {
252 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000253 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000254 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700255}
256
Mathias Agopian13127d82013-03-05 17:47:11 -0800257// ---------------------------------------------------------------------------
258// callbacks
259// ---------------------------------------------------------------------------
260
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700261void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700262 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700263 return;
264 }
Robert Carr2e102c92018-10-23 12:11:15 -0700265
Robert Carr6a160312021-05-17 12:08:20 -0700266 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700267 if (strongRelative == nullptr) {
268 setZOrderRelativeOf(nullptr);
269 return;
270 }
271
272 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700273 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700274 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800275 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700276 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700277}
278
279void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700280 if (!mRemovedFromDrawingState) {
281 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700282 mFlinger->mScheduler->deregisterLayer(this);
283 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000284 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000285
Ady Abrahamd11bade2022-08-01 16:18:03 -0700286 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700287}
Chia-I Wu38512252017-05-17 14:36:16 -0700288
chaviw68d4dab2020-06-08 15:07:32 -0700289sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000290 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700291 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700292 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700293 }
294 return parent->getRootLayer();
295}
296
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700297void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700298 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
299 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700300 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700301
Josh Gao194ff392022-09-08 16:19:29 -0700302 REQUIRE_MUTEX(mFlinger->mStateLock);
303 traverse(LayerVector::StateSet::Current,
304 [&](Layer* layer) REQUIRES(layer->mFlinger->mStateLock) {
305 layer->removeFromCurrentState();
306 layer->removeRelativeZ(layersInTree);
307 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700308}
309
chaviw61626f22018-11-15 16:26:27 -0800310void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700311 if (mRemovedFromDrawingState) {
312 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700313 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700314 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700315 }
chaviw61626f22018-11-15 16:26:27 -0800316
317 for (const auto& child : mCurrentChildren) {
318 child->addToCurrentState();
319 }
320}
321
Mathias Agopian13127d82013-03-05 17:47:11 -0800322// ---------------------------------------------------------------------------
323// set-up
324// ---------------------------------------------------------------------------
325
chaviw13fdc492017-06-27 12:40:18 -0700326bool Layer::getPremultipledAlpha() const {
327 return mPremultipliedAlpha;
328}
329
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700330sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800331 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700332 if (mGetHandleCalled) {
333 ALOGE("Get handle called twice" );
334 return nullptr;
335 }
336 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700337 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000338 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800339}
340
341// ---------------------------------------------------------------------------
342// h/w composer set-up
343// ---------------------------------------------------------------------------
344
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700345static Rect reduce(const Rect& win, const Region& exclude) {
346 if (CC_LIKELY(exclude.isEmpty())) {
347 return win;
348 }
349 if (exclude.isRect()) {
350 return win.reduce(exclude.getBounds());
351 }
352 return Region(win).subtract(exclude).getBounds();
353}
354
Dan Stoza80d61162017-12-20 15:57:52 -0800355static FloatRect reduce(const FloatRect& win, const Region& exclude) {
356 if (CC_LIKELY(exclude.isEmpty())) {
357 return win;
358 }
359 // Convert through Rect (by rounding) for lack of FloatRegion
360 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
361}
362
Vishnu Nair4351ad52019-02-11 14:13:02 -0800363Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800364 if (!reduceTransparentRegion) {
365 return Rect{mScreenBounds};
366 }
367
368 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800369 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800370 // Transform to screen space.
371 bounds = t.transform(bounds);
372 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700373}
374
Vishnu Nair4351ad52019-02-11 14:13:02 -0800375FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000376 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800377 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700378}
379
Vishnu Nairf0c28512019-02-08 12:40:28 -0800380FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
381 // Subtract the transparent region and snap to the bounds.
382 return reduce(mBounds, activeTransparentRegion);
383}
384
Chavi Weingarten076acac2023-01-19 17:20:43 +0000385// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000386void Layer::updateTrustedPresentationState(const DisplayDevice* display,
387 const frontend::LayerSnapshot* snapshot,
388 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000389 if (!hasTrustedPresentationListener()) {
390 return;
391 }
392 const bool lastState = mLastComputedTrustedPresentationState;
393 mLastComputedTrustedPresentationState = false;
394
395 if (!leaveState) {
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000396 const auto outputLayer = findOutputLayerForDisplay(display, snapshot->path);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000397 if (outputLayer != nullptr) {
398 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
399 Region coveredRegion =
400 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
401 mLastComputedTrustedPresentationState =
402 computeTrustedPresentationState(snapshot->geomLayerBounds,
403 snapshot->sourceBounds(), coveredRegion,
404 snapshot->transformedBounds,
405 snapshot->alpha,
406 snapshot->geomLayerTransform,
407 mTrustedPresentationThresholds);
408 } else {
409 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
410 "TrustedPresentationState",
411 getDebugName());
412 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000413 }
414 }
415 const bool newState = mLastComputedTrustedPresentationState;
416 if (lastState && !newState) {
417 // We were in the trusted presentation state, but now we left it,
418 // emit the callback if needed
419 if (mLastReportedTrustedPresentationState) {
420 mLastReportedTrustedPresentationState = false;
421 mTrustedPresentationListener.invoke(false);
422 }
423 // Reset the timer
424 mEnteredTrustedPresentationStateTime = -1;
425 } else if (!lastState && newState) {
426 // We were not in the trusted presentation state, but we entered it, begin the timer
427 // and make sure this gets called at least once more!
428 mEnteredTrustedPresentationStateTime = time_in_ms;
429 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
430 }
431
432 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
433 if (!mLastReportedTrustedPresentationState && newState &&
434 (time_in_ms - mEnteredTrustedPresentationStateTime >
435 mTrustedPresentationThresholds.stabilityRequirementMs)) {
436 mLastReportedTrustedPresentationState = true;
437 mTrustedPresentationListener.invoke(true);
438 }
439}
440
441/**
442 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
443 * of how the parameters and thresholds are interpreted. The general spirit is
444 * to produce an upper bound on the amount of the buffer which was presented.
445 */
446bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
447 const Region& coveredRegion,
448 const FloatRect& screenBounds, float alpha,
449 const ui::Transform& effectiveTransform,
450 const TrustedPresentationThresholds& thresholds) {
451 if (alpha < thresholds.minAlpha) {
452 return false;
453 }
454 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
455 return false;
456 }
457 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
458 return false;
459 }
460
461 const float sx = effectiveTransform.dsdx();
462 const float sy = effectiveTransform.dsdy();
463 float fractionRendered = std::min(sx * sy, 1.0f);
464
465 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
466 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
467 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
468
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000469 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
470 // Compute the size of all the rects since they may be disconnected.
471 float coveredSize = 0;
472 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
473 float size = rect->width() * rect->height();
474 coveredSize += size;
475 }
476
477 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000478
479 if (fractionRendered < thresholds.minFractionRendered) {
480 return false;
481 }
482
483 return true;
484}
485
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700486void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
487 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800488 const State& s(getDrawingState());
489
490 // Calculate effective layer transform
491 mEffectiveTransform = parentTransform * getActiveTransform(s);
492
Garfield Tan2c1782c2022-02-16 15:25:05 -0800493 if (CC_UNLIKELY(!isTransformValid())) {
494 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
495 getDebugName());
496 return;
497 }
498
Vishnu Nair4351ad52019-02-11 14:13:02 -0800499 // Transform parent bounds to layer space
500 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
501
Vishnu Nairc652ff82019-03-15 12:48:54 -0700502 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800503 mSourceBounds = computeSourceBounds(parentBounds);
504
505 // Calculate bounds by croping diplay frame with layer crop and parent bounds
506 FloatRect bounds = mSourceBounds;
507 const Rect layerCrop = getCrop(s);
508 if (!layerCrop.isEmpty()) {
509 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
510 }
511 bounds = bounds.intersect(parentBounds);
512
513 mBounds = bounds;
514 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700515
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700516 // Use the layer's own shadow radius if set. Otherwise get the radius from
517 // parent.
518 if (s.shadowRadius > 0.f) {
519 mEffectiveShadowRadius = s.shadowRadius;
520 } else {
521 mEffectiveShadowRadius = parentShadowRadius;
522 }
523
524 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
525 // don't pass it to its children.
526 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
527
Vishnu Nair4351ad52019-02-11 14:13:02 -0800528 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700529 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800530 }
Vishnu Nairba354102022-08-01 00:14:18 +0000531
532 if (mPotentialCursor) {
533 prepareCursorCompositionState();
534 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800535}
536
Vishnu Nair60356342018-11-13 13:00:45 -0800537Rect Layer::getCroppedBufferSize(const State& s) const {
538 Rect size = getBufferSize(s);
539 Rect crop = getCrop(s);
540 if (!crop.isEmpty() && size.isValid()) {
541 size.intersect(crop, &size);
542 } else if (!crop.isEmpty()) {
543 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700544 }
Vishnu Nair60356342018-11-13 13:00:45 -0800545 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800546}
547
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700548void Layer::setupRoundedCornersCropCoordinates(Rect win,
549 const FloatRect& roundedCornersCrop) const {
550 // Translate win by the rounded corners rect coordinates, to have all values in
551 // layer coordinate space.
552 win.left -= roundedCornersCrop.left;
553 win.right -= roundedCornersCrop.left;
554 win.top -= roundedCornersCrop.top;
555 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700556}
557
Lloyd Piquede196652020-01-22 17:29:58 -0800558void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800559 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800560 const auto alpha = static_cast<float>(getAlpha());
561 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700562 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800563
564 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
565 if (!opaque || alpha != 1.0f) {
566 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
567 : Hwc2::IComposerClient::BlendMode::COVERAGE;
568 }
569
Alec Mourif4af03e2023-02-11 00:25:24 +0000570 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000571 auto* snapshot = editLayerSnapshot();
572 snapshot->outputFilter = getOutputFilter();
573 snapshot->isVisible = isVisible();
574 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
575 snapshot->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800576
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000577 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800578 contentDirty = false;
579
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000580 snapshot->geomLayerBounds = mBounds;
581 snapshot->geomLayerTransform = getTransform();
582 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
583 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000584 snapshot->localTransform = getActiveTransform(drawingState);
585 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000586 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
587 snapshot->alpha = alpha;
Vishnu Nairc6384702023-07-31 12:22:20 -0700588 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
589 snapshot->blurRegions = getBlurRegions();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000590 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800591}
592
Lloyd Piquede196652020-01-22 17:29:58 -0800593void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800594 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000595 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700596
Alec Mourif4af03e2023-02-11 00:25:24 +0000597 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000598 snapshot->geomBufferSize = getBufferSize(drawingState);
599 snapshot->geomContentCrop = getBufferCrop();
600 snapshot->geomCrop = getCrop(drawingState);
601 snapshot->geomBufferTransform = getBufferTransform();
602 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
603 snapshot->geomUsesSourceCrop = usesSourceCrop();
604 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800605
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000606 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800607 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
608 for (const auto& [key, mandatory] : supportedMetadata) {
609 const auto& genericLayerMetadataCompatibilityMap =
610 mFlinger->getGenericLayerMetadataKeyMap();
611 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
612 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
613 continue;
614 }
615 const uint32_t id = compatIter->second;
616
617 auto it = drawingState.metadata.mMap.find(id);
618 if (it == std::end(drawingState.metadata.mMap)) {
619 continue;
620 }
621
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000622 snapshot->metadata.emplace(key,
623 compositionengine::GenericLayerMetadataEntry{mandatory,
624 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800625 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800626}
David Sodmanba340492018-08-05 21:51:33 -0700627
Lloyd Piquede196652020-01-22 17:29:58 -0800628void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800629 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000630 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000631 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800632
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000633 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800634
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000635 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
636 snapshot->dataspace = getDataSpace();
637 snapshot->colorTransform = getColorTransform();
638 snapshot->colorTransformIsIdentity = !hasColorTransform();
639 snapshot->surfaceDamage = surfaceDamageRegion;
640 snapshot->hasProtectedContent = isProtected();
641 snapshot->dimmingEnabled = isDimmingEnabled();
Sally Qi963049b2023-03-23 14:06:21 -0700642 snapshot->currentHdrSdrRatio = getCurrentHdrSdrRatio();
643 snapshot->desiredHdrSdrRatio = getDesiredHdrSdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000644 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800645
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700646 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700647
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000648 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800649
650 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400651 // Rounded corners no longer force client composition, since we may use a
652 // hole punch so that the layer will appear to have rounded corners.
Alec Mouri994761f2023-08-04 21:50:55 +0000653 if (drawShadows() || snapshot->stretchEffect.hasEffect()) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000654 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800655 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700656 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairc6384702023-07-31 12:22:20 -0700657 snapshot->blurRegions = getBlurRegions();
658 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400659
660 // Layer framerate is used in caching decisions.
661 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
662 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000663 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000664
665 if (hasBufferOrSidebandStream()) {
666 preparePerFrameBufferCompositionState();
667 } else {
668 preparePerFrameEffectsCompositionState();
669 }
670}
671
672void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000673 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000674 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000675 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000676 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
677 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000678 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
679 return;
680 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000681 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000682 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800683 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
684 snapshot->compositionType =
685 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000686 } else {
687 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000688 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
689 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000690 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
691 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
692 }
693
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000694 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000695 snapshot->acquireFence = mBufferInfo.mFence;
696 snapshot->frameNumber = mBufferInfo.mFrameNumber;
697 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000698}
699
700void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000701 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000702 auto* snapshot = editLayerSnapshot();
703 snapshot->color = getColor();
704 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000705 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800706}
707
Lloyd Piquede196652020-01-22 17:29:58 -0800708void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800709 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000710 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000711 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800712
713 // Apply the layer's transform, followed by the display's global transform
714 // Here we're guaranteed that the layer's transform preserves rects
715 Rect win = getCroppedBufferSize(drawingState);
716 // Subtract the transparent region and snap to the bounds
717 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
718 Rect frame(getTransform().transform(bounds));
719
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000720 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800721}
722
Lloyd Piquea83776c2019-01-29 18:42:32 -0800723const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700724 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800725}
726
Mathias Agopian13127d82013-03-05 17:47:11 -0800727// ---------------------------------------------------------------------------
728// drawing...
729// ---------------------------------------------------------------------------
730
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500731aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
732 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700733 const auto outputLayer = findOutputLayerForDisplay(&display);
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000734 return getCompositionType(outputLayer);
735}
736
737aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
738 const compositionengine::OutputLayer* outputLayer) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -0800739 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500740 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800741 }
742 if (outputLayer->getState().hwc) {
743 return (*outputLayer->getState().hwc).hwcCompositionType;
744 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500745 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800746 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800747}
748
Mathias Agopian13127d82013-03-05 17:47:11 -0800749// ----------------------------------------------------------------------------
750// local state
751// ----------------------------------------------------------------------------
752
David Sodman41fdfc92017-11-06 16:09:56 -0800753bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800754 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700755 if (s.flags & layer_state_t::eLayerSecure) {
756 return true;
757 }
758
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000759 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700760 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700761}
762
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100763void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
764 std::vector<JankData>& jankData) {
765 if (mPendingJankClassifications.empty() ||
766 !mPendingJankClassifications.front()->getJankType()) {
767 return;
768 }
769
770 bool includeJankData = false;
771 for (const auto& handle : handles) {
772 for (const auto& cb : handle->callbackIds) {
773 if (cb.includeJankData) {
774 includeJankData = true;
775 break;
776 }
777 }
778
779 if (includeJankData) {
780 jankData.reserve(mPendingJankClassifications.size());
781 break;
782 }
783 }
784
785 while (!mPendingJankClassifications.empty() &&
786 mPendingJankClassifications.front()->getJankType()) {
787 if (includeJankData) {
788 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
789 mPendingJankClassifications.front();
790 jankData.emplace_back(
791 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
792 }
793 mPendingJankClassifications.pop_front();
794 }
795}
796
Mathias Agopian13127d82013-03-05 17:47:11 -0800797// ----------------------------------------------------------------------------
798// transaction
799// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800800
Vishnu Naira156f482023-02-22 00:23:38 +0000801uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700802 ATRACE_CALL();
803
Robert Carr0758e5d2021-03-11 22:15:04 -0800804 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700805 mDrawingStateModified = mDrawingState.modified;
806 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700807
Alec Mourib416efd2018-09-06 21:01:59 +0000808 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700809
Robert Carr6a160312021-05-17 12:08:20 -0700810 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800811 // invalidate and recompute the visible regions if needed
812 flags |= Layer::eVisibleRegion;
813 }
814
Robert Carr6a160312021-05-17 12:08:20 -0700815 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800816 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000817 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800818 flags |= eVisibleRegion;
819 this->contentDirty = true;
820
821 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700822 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800823 }
824
Arthur Hung9ed43392022-05-27 06:31:57 +0000825 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
826 mFlinger->mUpdateInputInfo = true;
827 }
828
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700829 commitTransaction();
Robert Carra1257842020-01-31 13:48:28 -0800830
Mathias Agopian13127d82013-03-05 17:47:11 -0800831 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800832}
833
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700834void Layer::commitTransaction() {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000835 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
836 // bufferSurfaceFrameTX will be presented in latchBuffer.
837 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
838 if (surfaceFrame->getPresentState() != PresentState::Presented) {
839 // With applyPendingStates, we could end up having presented surfaceframes from previous
840 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800841 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000842 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
843 }
844 }
Robert Carr6a160312021-05-17 12:08:20 -0700845 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700846}
847
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700848uint32_t Layer::clearTransactionFlags(uint32_t mask) {
849 const auto flags = mTransactionFlags & mask;
850 mTransactionFlags &= ~mask;
851 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800852}
853
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700854void Layer::setTransactionFlags(uint32_t mask) {
855 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800856}
857
Robert Carr1f0a16a2016-10-24 16:27:39 -0700858bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
859 ssize_t idx = mCurrentChildren.indexOf(childLayer);
860 if (idx < 0) {
861 return false;
862 }
863 if (childLayer->setLayer(z)) {
864 mCurrentChildren.removeAt(idx);
865 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800866 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700867 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800868 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700869}
870
Robert Carr503c7042017-09-27 15:06:08 -0700871bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
872 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
873 ssize_t idx = mCurrentChildren.indexOf(childLayer);
874 if (idx < 0) {
875 return false;
876 }
877 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
878 mCurrentChildren.removeAt(idx);
879 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800880 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700881 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800882 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700883}
884
Robert Carrae060832016-11-28 10:51:00 -0800885bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700886 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
887 mDrawingState.sequence++;
888 mDrawingState.z = z;
889 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700890
Robert Carra70e91c2021-06-11 13:59:52 -0700891 mFlinger->mSomeChildrenChanged = true;
892
Robert Carrdb66e622017-04-10 16:55:57 -0700893 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700894 if (mDrawingState.zOrderRelativeOf != nullptr) {
895 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700896 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700897 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700898 }
chaviw606e5cf2019-03-01 10:12:10 -0800899 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700900 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800901 setTransactionFlags(eTransactionNeeded);
902 return true;
903}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700904
Robert Carrdb66e622017-04-10 16:55:57 -0700905void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700906 mDrawingState.zOrderRelatives.remove(relative);
907 mDrawingState.sequence++;
908 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700909 setTransactionFlags(eTransactionNeeded);
910}
911
912void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700913 mDrawingState.zOrderRelatives.add(relative);
914 mDrawingState.modified = true;
915 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700916 setTransactionFlags(eTransactionNeeded);
917}
918
chaviw606e5cf2019-03-01 10:12:10 -0800919void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700920 mDrawingState.zOrderRelativeOf = relativeOf;
921 mDrawingState.sequence++;
922 mDrawingState.modified = true;
923 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700924
chaviw606e5cf2019-03-01 10:12:10 -0800925 setTransactionFlags(eTransactionNeeded);
926}
927
Robert Carr503d2bd2017-12-04 15:49:47 -0800928bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000929 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700930 if (relative == nullptr) {
931 return false;
932 }
933
Robert Carr6a160312021-05-17 12:08:20 -0700934 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
935 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800936 return false;
937 }
938
Robert Carr88b85e12022-03-21 15:47:35 -0700939 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
940 (relative->mDrawingState.zOrderRelativeOf == this)) {
941 ALOGE("Detected relative layer loop between %s and %s",
942 mName.c_str(), relative->mName.c_str());
943 ALOGE("Ignoring new call to set relative layer");
944 return false;
945 }
946
Robert Carra70e91c2021-06-11 13:59:52 -0700947 mFlinger->mSomeChildrenChanged = true;
948
Robert Carr6a160312021-05-17 12:08:20 -0700949 mDrawingState.sequence++;
950 mDrawingState.modified = true;
951 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700952
Robert Carr6a160312021-05-17 12:08:20 -0700953 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700954 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700955 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700956 }
chaviw606e5cf2019-03-01 10:12:10 -0800957 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700958 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700959
960 setTransactionFlags(eTransactionNeeded);
961
962 return true;
963}
964
Winson Chunga30f7c92021-06-29 15:42:56 -0700965bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
966 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
967 mDrawingState.isTrustedOverlay = isTrustedOverlay;
968 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000969 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700970 setTransactionFlags(eTransactionNeeded);
971 return true;
972}
973
974bool Layer::isTrustedOverlay() const {
975 if (getDrawingState().isTrustedOverlay) {
976 return true;
977 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000978 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700979 return (p != nullptr) && p->isTrustedOverlay();
980}
981
Dan Stoza9e56aa02015-11-02 13:00:03 -0800982bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700983 if (mDrawingState.color.a == alpha) return false;
984 mDrawingState.sequence++;
985 mDrawingState.color.a = alpha;
986 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800987 setTransactionFlags(eTransactionNeeded);
988 return true;
989}
chaviw13fdc492017-06-27 12:40:18 -0700990
Valerie Haudd0b7572019-01-29 14:59:27 -0800991bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700992 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700993 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800994 }
Robert Carr6a160312021-05-17 12:08:20 -0700995 mDrawingState.sequence++;
996 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800997 setTransactionFlags(eTransactionNeeded);
998
Robert Carr6a160312021-05-17 12:08:20 -0700999 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001000 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001001 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001002 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001003 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08001004 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001005 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001006
Valerie Haudd0b7572019-01-29 14:59:27 -08001007 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001008 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001009 mFlinger->mLayersAdded = true;
1010 // set up SF to handle added color layer
1011 if (isRemovedFromCurrentState()) {
Josh Gao194ff392022-09-08 16:19:29 -07001012 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001013 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001014 }
1015 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001016 } else if (mDrawingState.bgColorLayer && alpha == 0) {
Josh Gao194ff392022-09-08 16:19:29 -07001017 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001018 mDrawingState.bgColorLayer->reparent(nullptr);
1019 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001020 return true;
1021 }
1022
Robert Carr6a160312021-05-17 12:08:20 -07001023 mDrawingState.bgColorLayer->setColor(color);
1024 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1025 mDrawingState.bgColorLayer->setAlpha(alpha);
1026 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001027
chaviw13fdc492017-06-27 12:40:18 -07001028 return true;
1029}
1030
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001031bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001032 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001033
Robert Carr6a160312021-05-17 12:08:20 -07001034 mDrawingState.sequence++;
1035 mDrawingState.cornerRadius = cornerRadius;
1036 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001037 setTransactionFlags(eTransactionNeeded);
1038 return true;
1039}
1040
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001041bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001042 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001043 // If we start or stop drawing blur then the layer's visibility state may change so increment
1044 // the magic sequence number.
1045 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1046 mDrawingState.sequence++;
1047 }
Robert Carr6a160312021-05-17 12:08:20 -07001048 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1049 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001050 setTransactionFlags(eTransactionNeeded);
1051 return true;
1052}
Marissa Wall61c58622018-07-18 10:12:20 -07001053
Mathias Agopian13127d82013-03-05 17:47:11 -08001054bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001055 mDrawingState.sequence++;
1056 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001057 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001058 setTransactionFlags(eTransactionNeeded);
1059 return true;
1060}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001061
Lucas Dupinc3800b82020-10-02 16:24:48 -07001062bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001063 // If we start or stop drawing blur then the layer's visibility state may change so increment
1064 // the magic sequence number.
1065 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1066 mDrawingState.sequence++;
1067 }
Robert Carr6a160312021-05-17 12:08:20 -07001068 mDrawingState.blurRegions = blurRegions;
1069 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001070 setTransactionFlags(eTransactionNeeded);
1071 return true;
1072}
1073
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001074bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001075 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1076 if (mDrawingState.flags == newFlags) return false;
1077 mDrawingState.sequence++;
1078 mDrawingState.flags = newFlags;
1079 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001080 setTransactionFlags(eTransactionNeeded);
1081 return true;
1082}
Robert Carr99e27f02016-06-16 15:18:02 -07001083
chaviw25714502021-02-11 10:01:08 -08001084bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001085 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001086 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001087 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001088
Robert Carr6a160312021-05-17 12:08:20 -07001089 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001090 setTransactionFlags(eTransactionNeeded);
1091 return true;
1092}
Robert Carr8d5227b2017-03-16 15:41:03 -07001093
Evan Roskyef876c92019-01-25 17:46:06 -08001094bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001095 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1096 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001097 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001098 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001099}
1100
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001101bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001102 if (mDrawingState.layerStack == layerStack) return false;
1103 mDrawingState.sequence++;
1104 mDrawingState.layerStack = layerStack;
1105 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001106 setTransactionFlags(eTransactionNeeded);
1107 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001108}
1109
Peiyong Linc502cb72019-03-01 15:00:23 -08001110bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001111 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001112 return false;
1113 }
Robert Carr6a160312021-05-17 12:08:20 -07001114 mDrawingState.sequence++;
1115 mDrawingState.colorSpaceAgnostic = agnostic;
1116 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001117 setTransactionFlags(eTransactionNeeded);
1118 return true;
1119}
1120
Sally Qi81d95e62022-03-21 19:41:33 -07001121bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1122 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1123
1124 mDrawingState.sequence++;
1125 mDrawingState.dimmingEnabled = dimmingEnabled;
1126 mDrawingState.modified = true;
1127 setTransactionFlags(eTransactionNeeded);
1128 return true;
1129}
1130
Ana Krulecc84d09b2019-11-02 23:10:29 +01001131bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001132 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1133 mDrawingState.frameRateSelectionPriority = priority;
1134 mDrawingState.sequence++;
1135 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001136 setTransactionFlags(eTransactionNeeded);
1137 return true;
1138}
1139
1140int32_t Layer::getFrameRateSelectionPriority() const {
1141 // Check if layer has priority set.
1142 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1143 return mDrawingState.frameRateSelectionPriority;
1144 }
1145 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001146 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001147 if (parent != nullptr) {
1148 return parent->getFrameRateSelectionPriority();
1149 }
1150
1151 return Layer::PRIORITY_UNSET;
1152}
1153
Andy Labrada096227e2022-06-15 16:58:11 +00001154bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1155 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1156 mDrawingState.defaultFrameRateCompatibility = compatibility;
1157 mDrawingState.modified = true;
1158 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1159 setTransactionFlags(eTransactionNeeded);
1160 return true;
1161}
1162
1163scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1164 return mDrawingState.defaultFrameRateCompatibility;
1165}
1166
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001167bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1168 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1169};
1170
Vishnu Nair73908d12022-10-24 21:46:42 -07001171ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1172 bool useDrawing = state == LayerVector::StateSet::Drawing;
1173 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1174 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001175 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001176 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001177 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001178}
1179
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001180bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001181 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001182 return false;
1183 }
1184
Robert Carr6a160312021-05-17 12:08:20 -07001185 mDrawingState.sequence++;
1186 mDrawingState.shadowRadius = shadowRadius;
1187 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001188 setTransactionFlags(eTransactionNeeded);
1189 return true;
1190}
1191
Vishnu Nair6213bd92020-05-08 17:42:25 -07001192bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001193 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001194 return false;
1195 }
1196
Robert Carr6a160312021-05-17 12:08:20 -07001197 mDrawingState.sequence++;
1198 mDrawingState.fixedTransformHint = fixedTransformHint;
1199 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001200 setTransactionFlags(eTransactionNeeded);
1201 return true;
1202}
1203
John Reckcdb4ed72021-02-04 13:39:33 -05001204bool Layer::setStretchEffect(const StretchEffect& effect) {
1205 StretchEffect temp = effect;
1206 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001207 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001208 return false;
1209 }
Robert Carr6a160312021-05-17 12:08:20 -07001210 mDrawingState.sequence++;
1211 mDrawingState.stretchEffect = temp;
1212 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001213 setTransactionFlags(eTransactionNeeded);
1214 return true;
1215}
1216
John Reckc00c6692021-02-16 11:37:33 -05001217StretchEffect Layer::getStretchEffect() const {
1218 if (mDrawingState.stretchEffect.hasEffect()) {
1219 return mDrawingState.stretchEffect;
1220 }
1221
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001222 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001223 if (parent != nullptr) {
1224 auto effect = parent->getStretchEffect();
1225 if (effect.hasEffect()) {
1226 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1227 return effect;
1228 }
1229 }
1230 return StretchEffect{};
1231}
1232
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001233bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1234 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001235 return false;
1236 }
1237 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001238 mBorderWidth = width;
1239 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001240 return true;
1241}
1242
1243bool Layer::isBorderEnabled() {
1244 return mBorderEnabled;
1245}
1246
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001247float Layer::getBorderWidth() {
1248 return mBorderWidth;
1249}
1250
1251const half4& Layer::getBorderColor() {
1252 return mBorderColor;
1253}
1254
Ady Abrahama850c182021-08-04 13:04:37 -07001255bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1256 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1257 const auto frameRate = [&] {
1258 if (mDrawingState.frameRate.rate.isValid() ||
1259 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1260 return mDrawingState.frameRate;
1261 }
1262
1263 return parentFrameRate;
1264 }();
1265
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001266 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001267
1268 // The frame rate is propagated to the children
1269 bool childrenHaveFrameRate = false;
1270 for (const sp<Layer>& child : mCurrentChildren) {
1271 childrenHaveFrameRate |=
1272 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1273 }
1274
1275 // If we don't have a valid frame rate, but the children do, we set this
1276 // layer as NoVote to allow the children to control the refresh rate
1277 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1278 childrenHaveFrameRate) {
1279 *transactionNeeded |=
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001280 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001281 }
1282
1283 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1284 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001285 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001286 const auto layerVotedWithDefaultCompatibility =
1287 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1288 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1289 const auto layerVotedWithExactCompatibility =
1290 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1291 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1292 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1293}
1294
Ady Abraham60e42ea2020-03-09 19:17:31 -07001295void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001296 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001297 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001298 while (auto parent = layer->getParent()) {
1299 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001300 }
Ady Abrahama850c182021-08-04 13:04:37 -07001301 return layer;
1302 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001303
Ady Abraham60e42ea2020-03-09 19:17:31 -07001304 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001305 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001306
Ady Abrahama850c182021-08-04 13:04:37 -07001307 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001308 if (transactionNeeded) {
1309 mFlinger->setTransactionFlags(eTraversalNeeded);
1310 }
1311}
1312
Ady Abraham71c437d2020-01-31 15:56:57 -08001313bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001314 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001315 return false;
1316 }
1317
Robert Carr6a160312021-05-17 12:08:20 -07001318 mDrawingState.sequence++;
1319 mDrawingState.frameRate = frameRate;
1320 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001321
1322 updateTreeHasFrameRateVote();
1323
Steven Thomas3172e202020-01-06 19:25:30 -08001324 setTransactionFlags(eTransactionNeeded);
1325 return true;
1326}
1327
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001328void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1329 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001330 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001331
1332 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1333 // there are two transactions with the same token, the first one without a buffer and the
1334 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1335 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001336 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1337 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001338 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001339 mDrawingState.bufferSurfaceFrameTX = it->second;
1340 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1341 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1342 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001343 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001344 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001345 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1346 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001347
1348 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001349}
1350
1351void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1352 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001353 mDrawingState.frameTimelineInfo = info;
1354 mDrawingState.postTime = postTime;
1355 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001356 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001357
Robert Carr6a160312021-05-17 12:08:20 -07001358 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001359 bufferSurfaceFrameTX != nullptr) {
1360 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1361 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1362 // being used for BufferSurfaceFrame, don't create a new one.
1363 return;
1364 }
1365 }
1366 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1367 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1368 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001369 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1370 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001371 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001372 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001373 } else {
1374 if (it->second->getPresentState() == PresentState::Presented) {
1375 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1376 // have been from previous vsync.
1377 it->second = createSurfaceFrameForTransaction(info, postTime);
1378 }
1379 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001380
1381 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001382}
1383
1384void Layer::addSurfaceFrameDroppedForBuffer(
Ady Abraham5a3e3562023-06-07 10:32:08 -07001385 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t dropTime) {
1386 surfaceFrame->setDropTime(dropTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001387 surfaceFrame->setPresentState(PresentState::Dropped);
1388 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1389}
1390
1391void Layer::addSurfaceFramePresentedForBuffer(
1392 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1393 nsecs_t currentLatchTime) {
1394 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1395 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1396 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001397 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001398}
1399
1400std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1401 const FrameTimelineInfo& info, nsecs_t postTime) {
1402 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001403 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1404 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001405 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001406 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001407 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001408 // For Transactions, the post time is considered to be both queue and acquire fence time.
1409 surfaceFrame->setActualQueueTime(postTime);
1410 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001411 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1412 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001413 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001414 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001415 onSurfaceFrameCreated(surfaceFrame);
1416 return surfaceFrame;
1417}
1418
1419std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1420 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1421 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001422 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001423 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001424 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001425 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001426 // For buffers, acquire fence time will set during latch.
1427 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001428 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1429 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001430 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001431 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001432 onSurfaceFrameCreated(surfaceFrame);
1433 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001434}
1435
Ady Abraham5a3e3562023-06-07 10:32:08 -07001436void Layer::setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
1437 std::string debugName) {
1438 if (info.skippedFrameVsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
1439 return;
1440 }
1441
1442 FrameTimelineInfo skippedFrameTimelineInfo = info;
1443 skippedFrameTimelineInfo.vsyncId = info.skippedFrameVsyncId;
1444
1445 auto surfaceFrame =
1446 mFlinger->mFrameTimeline->createSurfaceFrameForToken(skippedFrameTimelineInfo,
1447 mOwnerPid, mOwnerUid,
1448 getSequence(), mName, debugName,
1449 /*isBuffer*/ false, getGameMode());
1450 surfaceFrame->setActualStartTime(skippedFrameTimelineInfo.skippedFrameStartTimeNanos);
1451 // For Transactions, the post time is considered to be both queue and acquire fence time.
1452 surfaceFrame->setActualQueueTime(postTime);
1453 surfaceFrame->setAcquireFenceTime(postTime);
1454 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1455 if (fps) {
1456 surfaceFrame->setRenderRate(*fps);
1457 }
1458 onSurfaceFrameCreated(surfaceFrame);
1459 addSurfaceFrameDroppedForBuffer(surfaceFrame, postTime);
1460}
1461
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001462bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001463 if (mDrawingState.frameRateForLayerTree == frameRate) {
1464 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001465 }
1466
Ady Abrahama850c182021-08-04 13:04:37 -07001467 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001468
Ady Abrahama850c182021-08-04 13:04:37 -07001469 // TODO(b/195668952): we probably don't need to dirty visible regions here
1470 // or even store frameRateForLayerTree in mDrawingState
1471 mDrawingState.sequence++;
1472 mDrawingState.modified = true;
1473 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001474
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001475 mFlinger->mScheduler
1476 ->recordLayerHistory(sequence, getLayerProps(), systemTime(),
1477 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1478 return true;
1479}
Ady Abrahama850c182021-08-04 13:04:37 -07001480
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001481bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps) {
1482 if (mDrawingState.frameRateForLayerTree == frameRate) {
1483 return false;
1484 }
1485
1486 mDrawingState.frameRateForLayerTree = frameRate;
1487 mFlinger->mScheduler
1488 ->recordLayerHistory(sequence, layerProps, systemTime(),
1489 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001490 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001491}
1492
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001493Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1494 return getDrawingState().frameRateForLayerTree;
1495}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001496
Robert Carr1f0a16a2016-10-24 16:27:39 -07001497bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001498 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001499 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001500 if (parent != nullptr && parent->isHiddenByPolicy()) {
1501 return true;
1502 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001503 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1504 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1505 if (zOrderRelativeOf != nullptr) {
1506 if (zOrderRelativeOf->isHiddenByPolicy()) {
1507 return true;
1508 }
1509 }
1510 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001511 if (CC_UNLIKELY(!isTransformValid())) {
1512 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1513 return true;
1514 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001515 return s.flags & layer_state_t::eLayerHidden;
1516}
1517
David Sodman41fdfc92017-11-06 16:09:56 -08001518uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001519 // TODO: should we do something special if mSecure is set?
1520 if (mProtectedByApp) {
1521 // need a hardware-protected path to external video sink
1522 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001523 }
Riley Andrews03414a12014-07-01 14:22:59 -07001524 if (mPotentialCursor) {
1525 usage |= GraphicBuffer::USAGE_CURSOR;
1526 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001527 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001528 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001529}
1530
Vishnu Nair71fcf912022-10-18 09:14:20 -07001531void Layer::skipReportingTransformHint() {
1532 mSkipReportingTransformHint = true;
1533}
1534
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001535void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1536 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1537 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001538 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001539
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001540 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001541}
1542
Mathias Agopian13127d82013-03-05 17:47:11 -08001543// ----------------------------------------------------------------------------
1544// debugging
1545// ----------------------------------------------------------------------------
1546
Marissa Wall61c58622018-07-18 10:12:20 -07001547// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001548gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001549 using namespace std::string_literals;
1550
Huihong Luo05539a12022-02-23 10:29:40 -08001551 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001552 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001553 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001554 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001555 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001556 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001557
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001558 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001559 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001560 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001561 info.mX = ds.transform.tx();
1562 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001563 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001564 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001565 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001566 info.mFlags = ds.flags;
1567 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001568 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001569 info.mMatrix[0][0] = ds.transform[0][0];
1570 info.mMatrix[0][1] = ds.transform[0][1];
1571 info.mMatrix[1][0] = ds.transform[1][0];
1572 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001573 {
chaviwd62d3062019-09-04 14:48:02 -07001574 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001575 if (buffer != 0) {
1576 info.mActiveBufferWidth = buffer->getWidth();
1577 info.mActiveBufferHeight = buffer->getHeight();
1578 info.mActiveBufferStride = buffer->getStride();
1579 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001580 } else {
1581 info.mActiveBufferWidth = 0;
1582 info.mActiveBufferHeight = 0;
1583 info.mActiveBufferStride = 0;
1584 info.mActiveBufferFormat = 0;
1585 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001586 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001587 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001588 info.mIsOpaque = isOpaque(ds);
1589 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001590 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001591 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001592}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001593
Yiwei Zhang5434a782018-12-05 18:06:32 -08001594void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001595 result.append(kDumpTableRowLength, '-');
1596 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001597 result.append(" Layer name\n");
1598 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001599 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001600 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001601 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001602 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001603 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001604 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1605 result.append(kDumpTableRowLength, '-');
1606 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001607}
1608
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001609void Layer::miniDumpLegacy(std::string& result, const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001610 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001611 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001612 return;
1613 }
1614
Yiwei Zhang5434a782018-12-05 18:06:32 -08001615 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001616 if (mName.length() > 77) {
1617 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001618 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001619 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001620 shortened.append(mName, mName.length() - 36);
1621 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001622 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001623 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001624 }
1625
Yiwei Zhang5434a782018-12-05 18:06:32 -08001626 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001627
Alec Mourib416efd2018-09-06 21:01:59 +00001628 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001629 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001630
Chia-I Wu1e043612018-03-01 09:45:09 -08001631 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001632 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001633 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001634 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001635 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001636 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001637 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001638 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1639 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001640 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001641 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001642 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001643 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001644 const auto frameRate = getFrameRateForLayerTree();
1645 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1646 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001647 ftl::enum_string(frameRate.type).c_str(),
1648 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001649 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001650 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001651 }
Dan Stozae22aec72016-08-01 13:20:59 -07001652
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001653 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1654 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1655
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001656 result.append(kDumpTableRowLength, '-');
1657 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001658}
Dan Stozae22aec72016-08-01 13:20:59 -07001659
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001660void Layer::miniDump(std::string& result, const frontend::LayerSnapshot& snapshot,
1661 const DisplayDevice& display) const {
1662 const auto outputLayer = findOutputLayerForDisplay(&display, snapshot.path);
1663 if (!outputLayer) {
1664 return;
1665 }
1666
1667 StringAppendF(&result, " %s\n", snapshot.debugName.c_str());
1668 StringAppendF(&result, " %10zu | ", snapshot.globalZ);
1669 StringAppendF(&result, " %10d | ",
1670 snapshot.layerMetadata.getInt32(gui::METADATA_WINDOW_TYPE, 0));
1671 StringAppendF(&result, "%10s | ", toString(getCompositionType(outputLayer)).c_str());
1672 const auto& outputLayerState = outputLayer->getState();
1673 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1674 const Rect& frame = outputLayerState.displayFrame;
1675 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1676 const FloatRect& crop = outputLayerState.sourceCrop;
1677 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
1678 crop.bottom);
1679 const auto frameRate = snapshot.frameRate;
1680 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1681 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
1682 ftl::enum_string(frameRate.type).c_str(),
1683 ftl::enum_string(frameRate.seamlessness).c_str());
1684 } else {
1685 result.append(41, ' ');
1686 }
1687
1688 const auto focused = isLayerFocusedBasedOnPriority(snapshot.frameRateSelectionPriority);
1689 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1690
1691 result.append(kDumpTableRowLength, '-');
1692 result.append("\n");
1693}
1694
Yiwei Zhang5434a782018-12-05 18:06:32 -08001695void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001696 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001697}
1698
Svetoslavd85084b2014-03-20 10:28:31 -07001699void Layer::clearFrameStats() {
1700 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001701}
1702
Jamie Gennis6547ff42013-07-16 20:12:42 -07001703void Layer::logFrameStats() {
1704 mFrameTracker.logAndResetStats(mName);
1705}
1706
Svetoslavd85084b2014-03-20 10:28:31 -07001707void Layer::getFrameStats(FrameStats* outStats) const {
1708 mFrameTracker.getStats(outStats);
1709}
1710
Vishnu Nair76554eb2022-12-09 03:38:36 +00001711void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1712 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
Vishnu Nair3be61902023-04-26 19:47:29 -07001713 StringAppendF(&result, "Layer %s%s pid:%d uid:%d%s\n", getName().c_str(), hasBuffer.c_str(),
1714 mOwnerPid, mOwnerUid, isHandleAlive() ? " handleAlive" : "");
Vishnu Nair0f085c62019-08-30 08:49:12 -07001715}
1716
Brian Anderson5ea5e592016-12-01 16:54:33 -08001717void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001718 const int32_t layerId = getSequence();
1719 mFlinger->mTimeStats->onDestroy(layerId);
1720 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001721}
1722
Vishnu Nair787aa782023-03-17 13:46:46 -07001723size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001724 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001725 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001726 count += 1 + child->getChildrenCount();
1727 }
1728 return count;
1729}
1730
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001731void Layer::setGameModeForTree(GameMode gameMode) {
1732 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001733 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1734 gameMode =
1735 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001736 }
1737 setGameMode(gameMode);
1738 for (const sp<Layer>& child : mCurrentChildren) {
1739 child->setGameModeForTree(gameMode);
1740 }
1741}
1742
Robert Carr1f0a16a2016-10-24 16:27:39 -07001743void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001744 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001745 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001746
Robert Carr1f0a16a2016-10-24 16:27:39 -07001747 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001748 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001749 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001750 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001751}
1752
1753ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001754 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001755 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001756
Robert Carr1323c952019-01-28 18:13:27 -08001757 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001758 const auto removeResult = mCurrentChildren.remove(layer);
1759
1760 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001761 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001762 layer->updateTreeHasFrameRateVote();
1763
1764 return removeResult;
1765}
1766
Robert Carr15eae092018-03-23 13:43:53 -07001767void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001768 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001769 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001770 const float parentShadowRadius =
1771 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001772 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001773 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001774 }
1775}
1776
chaviwf1961f72017-09-18 16:41:07 -07001777bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001778 sp<Layer> newParent;
1779 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001780 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001781 if (newParent == nullptr) {
1782 ALOGE("Unable to promote Layer handle");
1783 return false;
1784 }
1785 if (newParent == this) {
1786 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1787 return false;
1788 }
1789 }
1790
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001791 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001792 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001793 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001794 }
1795
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001796 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001797 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001798 if (!newParent->isRemovedFromCurrentState()) {
1799 addToCurrentState();
1800 } else {
1801 onRemovedFromCurrentState();
1802 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001803 } else {
1804 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001805 }
1806
chaviw06178942017-07-27 10:25:59 -07001807 return true;
1808}
1809
Peiyong Lind3788632018-09-18 16:01:31 -07001810bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001811 static const mat4 identityMatrix = mat4();
1812
Robert Carr6a160312021-05-17 12:08:20 -07001813 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001814 return false;
1815 }
Robert Carr6a160312021-05-17 12:08:20 -07001816 ++mDrawingState.sequence;
1817 mDrawingState.colorTransform = matrix;
1818 mDrawingState.hasColorTransform = matrix != identityMatrix;
1819 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001820 setTransactionFlags(eTransactionNeeded);
1821 return true;
1822}
1823
chaviwf66724d2018-11-28 16:35:21 -08001824mat4 Layer::getColorTransform() const {
1825 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001826 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001827 colorTransform = parent->getColorTransform() * colorTransform;
1828 }
1829 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001830}
1831
1832bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001833 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001834 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001835 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1836 }
1837 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001838}
1839
Chia-I Wu11481472018-05-04 10:43:19 -07001840bool Layer::isLegacyDataSpace() const {
1841 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001842 return !(getDataSpace() &
1843 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1844 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001845}
1846
Robert Carr1f0a16a2016-10-24 16:27:39 -07001847void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001848 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001849}
1850
Robert Carr6a160312021-05-17 12:08:20 -07001851int32_t Layer::getZ(LayerVector::StateSet) const {
1852 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001853}
1854
Robert Carr1c5481e2019-07-01 14:42:27 -07001855bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001856 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001857 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001858 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001859}
1860
David Sodman41fdfc92017-11-06 16:09:56 -08001861__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001862 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001863 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1864 "makeTraversalList received invalid stateSet");
1865 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1866 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001867 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001868
Robert Carr29abff82017-12-04 13:51:20 -08001869 if (state.zOrderRelatives.size() == 0) {
1870 *outSkipRelativeZUsers = true;
1871 return children;
1872 }
1873
chaviwfd462612018-05-31 16:11:27 -07001874 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001875 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001876 sp<Layer> strongRelative = weakRelative.promote();
1877 if (strongRelative != nullptr) {
1878 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001879 }
1880 }
1881
Dan Stoza412903f2017-04-27 13:42:17 -07001882 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001883 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001884 continue;
1885 }
Robert Carrdb66e622017-04-10 16:55:57 -07001886 traverse.add(child);
1887 }
1888
1889 return traverse;
1890}
1891
Robert Carr1f0a16a2016-10-24 16:27:39 -07001892/**
Robert Carrdb66e622017-04-10 16:55:57 -07001893 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001894 */
Dan Stoza412903f2017-04-27 13:42:17 -07001895void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001896 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1897 // produce a new list for traversing, including our relatives, and not including our children
1898 // who are relatives of another surface. In the case that there are no relative Z,
1899 // makeTraversalList returns our children directly to avoid significant overhead.
1900 // However in this case we need to take the responsibility for filtering children which
1901 // are relatives of another surface here.
1902 bool skipRelativeZUsers = false;
1903 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001904
Robert Carr1f0a16a2016-10-24 16:27:39 -07001905 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001906 for (; i < list.size(); i++) {
1907 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001908 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1909 continue;
1910 }
1911
chaviw301b1d82019-11-06 13:15:09 -08001912 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001913 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001914 }
Dan Stoza412903f2017-04-27 13:42:17 -07001915 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001916 }
Robert Carr29abff82017-12-04 13:51:20 -08001917
Dan Stoza412903f2017-04-27 13:42:17 -07001918 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001919 for (; i < list.size(); i++) {
1920 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001921
Robert Carr29abff82017-12-04 13:51:20 -08001922 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1923 continue;
1924 }
Dan Stoza412903f2017-04-27 13:42:17 -07001925 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001926 }
1927}
1928
1929/**
Robert Carrdb66e622017-04-10 16:55:57 -07001930 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001931 */
Dan Stoza412903f2017-04-27 13:42:17 -07001932void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1933 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001934 // See traverseInZOrder for documentation.
1935 bool skipRelativeZUsers = false;
1936 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001937
Robert Carr1f0a16a2016-10-24 16:27:39 -07001938 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001939 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001940 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001941
1942 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1943 continue;
1944 }
1945
chaviw301b1d82019-11-06 13:15:09 -08001946 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001947 break;
1948 }
Dan Stoza412903f2017-04-27 13:42:17 -07001949 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001950 }
Dan Stoza412903f2017-04-27 13:42:17 -07001951 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001952 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001953 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001954
1955 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1956 continue;
1957 }
1958
Dan Stoza412903f2017-04-27 13:42:17 -07001959 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001960 }
1961}
1962
Edgar Arriaga844fa672020-01-16 14:21:42 -08001963void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1964 visitor(this);
1965 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001966 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001967 for (const sp<Layer>& child : children) {
1968 child->traverse(state, visitor);
1969 }
1970}
1971
Vishnu Nair787aa782023-03-17 13:46:46 -07001972void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
1973 for (const sp<Layer>& child : mDrawingChildren) {
1974 visitor(child.get());
1975 }
1976}
1977
chaviw4b129c22018-04-09 16:19:43 -07001978LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1979 const std::vector<Layer*>& layersInTree) {
1980 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1981 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001982 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1983 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001984 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001985
chaviwfd462612018-05-31 16:11:27 -07001986 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001987 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1988 sp<Layer> strongRelative = weakRelative.promote();
1989 // Only add relative layers that are also descendents of the top most parent of the tree.
1990 // If a relative layer is not a descendent, then it should be ignored.
1991 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1992 traverse.add(strongRelative);
1993 }
1994 }
1995
1996 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001997 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001998 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1999 // descendent of the top most parent of the tree. If it's not a descendent, then just add
2000 // the child here since it won't be added later as a relative.
2001 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
2002 childState.zOrderRelativeOf.promote().get())) {
2003 continue;
2004 }
2005 traverse.add(child);
2006 }
2007
2008 return traverse;
2009}
2010
2011void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
2012 LayerVector::StateSet stateSet,
2013 const LayerVector::Visitor& visitor) {
2014 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07002015
2016 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07002017 for (; i < list.size(); i++) {
2018 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08002019 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07002020 break;
2021 }
chaviw4b129c22018-04-09 16:19:43 -07002022 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002023 }
chaviw4b129c22018-04-09 16:19:43 -07002024
chaviwa76b2712017-09-20 12:02:26 -07002025 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07002026 for (; i < list.size(); i++) {
2027 const auto& relative = list[i];
2028 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002029 }
2030}
2031
chaviw4b129c22018-04-09 16:19:43 -07002032std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2033 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2034 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2035
2036 std::vector<Layer*> layersInTree = {this};
2037 for (size_t i = 0; i < children.size(); i++) {
2038 const auto& child = children[i];
2039 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2040 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2041 }
2042
2043 return layersInTree;
2044}
2045
2046void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2047 const LayerVector::Visitor& visitor) {
2048 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2049 std::sort(layersInTree.begin(), layersInTree.end());
2050 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2051}
2052
Peiyong Linefefaac2018-08-17 12:27:51 -07002053ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08002054 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002055}
2056
Garfield Tan2c1782c2022-02-16 15:25:05 -08002057bool Layer::isTransformValid() const {
2058 float transformDet = getTransform().det();
2059 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2060}
2061
chaviw13fdc492017-06-27 12:40:18 -07002062half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002063 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002064
chaviw13fdc492017-06-27 12:40:18 -07002065 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2066 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002067}
Robert Carr6452f122017-03-21 10:41:29 -07002068
Vishnu Nair6213bd92020-05-08 17:42:25 -07002069ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002070 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002071 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2072 return fixedTransformHint;
2073 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002074 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002075 if (!p) return fixedTransformHint;
2076 return p->getFixedTransformHint();
2077}
2078
chaviw13fdc492017-06-27 12:40:18 -07002079half4 Layer::getColor() const {
2080 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002081 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002082}
Robert Carr6452f122017-03-21 10:41:29 -07002083
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002084int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002085 if (getDrawingState().backgroundBlurRadius == 0) {
2086 return 0;
2087 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002088
Vishnu Nair29810f72022-07-01 16:38:41 +00002089 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002090 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2091 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002092}
2093
Galia Peychevae0acf382021-04-12 21:22:34 +02002094const std::vector<BlurRegion> Layer::getBlurRegions() const {
2095 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002096 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002097 for (auto& region : regionsCopy) {
2098 region.alpha = region.alpha * layerAlpha;
2099 }
2100 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002101}
2102
Vishnu Naire14c6b32022-08-06 04:20:15 +00002103RoundedCornerState Layer::getRoundedCornerState() const {
Leon Scroggins IIIc1dbfcb2022-03-21 16:48:10 -04002104 // Today's DPUs cannot do rounded corners. If RenderEngine cannot render
2105 // protected content, remove rounded corners from protected content so it
2106 // can be rendered by the DPU.
2107 if (isProtected() && !mFlinger->getRenderEngine().supportsProtectedContent()) {
2108 return {};
2109 }
2110
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002111 // Get parent settings
2112 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002113 const auto& parent = mDrawingParent.promote();
2114 if (parent != nullptr) {
2115 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002116 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002117 ui::Transform t = getActiveTransform(getDrawingState());
2118 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002119 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002120 parentSettings.radius.x *= t.getScaleX();
2121 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002122 }
2123 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002124
2125 // Get layer settings
2126 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002127 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002128 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002129 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002130
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002131 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002132 // If the parent and the layer have rounded corner settings, use the parent settings if the
2133 // parent crop is entirely inside the layer crop.
2134 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2135 if (parentSettings.cropRect.left > layerCropRect.left &&
2136 parentSettings.cropRect.top > layerCropRect.top &&
2137 parentSettings.cropRect.right < layerCropRect.right &&
2138 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2139 return parentSettings;
2140 } else {
2141 return layerSettings;
2142 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002143 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002144 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002145 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002146 return parentSettings;
2147 }
2148 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002149}
2150
Robert Carr88b85e12022-03-21 15:47:35 -07002151bool Layer::findInHierarchy(const sp<Layer>& l) {
2152 if (l == this) {
2153 return true;
2154 }
2155 for (auto& child : mDrawingChildren) {
2156 if (child->findInHierarchy(l)) {
2157 return true;
2158 }
2159 }
2160 return false;
2161}
2162
Robert Carr1f0a16a2016-10-24 16:27:39 -07002163void Layer::commitChildList() {
2164 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2165 const auto& child = mCurrentChildren[i];
2166 child->commitChildList();
2167 }
2168 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002169 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002170 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2171 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2172 if (zOrderRelativeOf == nullptr) return;
2173 if (findInHierarchy(zOrderRelativeOf)) {
2174 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2175 zOrderRelativeOf->mName.c_str());
2176 ALOGE("Severing rel Z loop, potentially dangerous");
2177 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002178 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002179 }
2180 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002181}
2182
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002183
chaviw3277faf2021-05-19 16:45:23 -05002184void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002185 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002186 mDrawingState.touchableRegionCrop =
2187 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002188 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002189 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002190 setTransactionFlags(eTransactionNeeded);
2191}
2192
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002193LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002194 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002195 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002196 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2197
Vishnu Nair00b90132021-11-05 14:03:40 -07002198 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nair2f65e972023-04-04 16:36:28 +00002199 ui::LayerStack layerStack =
2200 (mSnapshot) ? mSnapshot->outputFilter.layerStack : ui::INVALID_LAYER_STACK;
2201 writeCompositionStateToProto(layerProto, layerStack);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002202 }
2203
chaviw08f3cb22020-01-13 13:17:21 -08002204 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002205 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002206 }
chaviw6d89e2d2020-01-14 14:42:01 -08002207
2208 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002209}
2210
Vishnu Nair2f65e972023-04-04 16:36:28 +00002211void Layer::writeCompositionStateToProto(LayerProto* layerProto, ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002212 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002213 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +00002214
2215 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002216 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002217 const auto compositionType = getCompositionType(*display);
2218 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +00002219 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +00002220 [&]() { return layerProto->mutable_visible_region(); });
2221 }
2222}
2223
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002224void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002225 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002226 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002227 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002228 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002229 [&]() { return layerInfo->mutable_active_buffer(); });
2230 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2231 layerInfo->mutable_buffer_transform());
2232 }
2233 layerInfo->set_invalidate(contentDirty);
2234 layerInfo->set_is_protected(isProtected());
2235 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2236 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002237 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002238 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002239 layerInfo->set_corner_radius(
2240 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002241 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2242 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2243 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2244 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2245 [&]() { return layerInfo->mutable_position(); });
2246 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002247 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2248 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002249
Vishnu Nair00b90132021-11-05 14:03:40 -07002250 if (hasColorTransform()) {
2251 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002252 }
2253
Vishnu Nair60db8c02020-04-02 11:55:16 -07002254 LayerProtoHelper::writeToProto(mSourceBounds,
2255 [&]() { return layerInfo->mutable_source_bounds(); });
2256 LayerProtoHelper::writeToProto(mScreenBounds,
2257 [&]() { return layerInfo->mutable_screen_bounds(); });
2258 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2259 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2260 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002261}
2262
2263void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002264 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002265 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2266 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002267 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002268
chaviw766c9c52021-02-10 17:36:47 -08002269 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002270
Vishnu Nair00b90132021-11-05 14:03:40 -07002271 layerInfo->set_id(sequence);
2272 layerInfo->set_name(getName().c_str());
2273 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002274
Vishnu Nair00b90132021-11-05 14:03:40 -07002275 for (const auto& child : children) {
2276 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002277 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002278
Vishnu Nair00b90132021-11-05 14:03:40 -07002279 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2280 sp<Layer> strongRelative = weakRelative.promote();
2281 if (strongRelative != nullptr) {
2282 layerInfo->add_relatives(strongRelative->sequence);
2283 }
2284 }
2285
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002286 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002287 [&]() { return layerInfo->mutable_transparent_region(); });
2288
2289 layerInfo->set_layer_stack(getLayerStack().id);
2290 layerInfo->set_z(state.z);
2291
2292 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2293 return layerInfo->mutable_requested_position();
2294 });
2295
Vishnu Nair00b90132021-11-05 14:03:40 -07002296 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2297
2298 layerInfo->set_is_opaque(isOpaque(state));
2299
2300 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2301 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2302 LayerProtoHelper::writeToProto(state.color,
2303 [&]() { return layerInfo->mutable_requested_color(); });
2304 layerInfo->set_flags(state.flags);
2305
2306 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2307 layerInfo->mutable_requested_transform());
2308
2309 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2310 if (parent != nullptr) {
2311 layerInfo->set_parent(parent->sequence);
2312 } else {
2313 layerInfo->set_parent(-1);
2314 }
2315
2316 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2317 if (zOrderRelativeOf != nullptr) {
2318 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2319 } else {
2320 layerInfo->set_z_order_relative_of(-1);
2321 }
2322
2323 layerInfo->set_is_relative_of(state.isRelativeOf);
2324
2325 layerInfo->set_owner_uid(mOwnerUid);
2326
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002327 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002328 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002329 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002330 info = fillInputInfo(
2331 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002332 } else {
2333 info = state.inputInfo;
2334 }
2335
2336 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002337 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002338 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002339
Vishnu Nair00b90132021-11-05 14:03:40 -07002340 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002341 auto protoMap = layerInfo->mutable_metadata();
2342 for (const auto& entry : state.metadata.mMap) {
2343 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2344 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002345 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002346
2347 LayerProtoHelper::writeToProto(state.destinationFrame,
2348 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002349}
2350
Robert Carr2e102c92018-10-23 12:11:15 -07002351bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002352 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002353}
2354
Prabir Pradhan33da9462022-06-14 14:55:57 +00002355// Applies the given transform to the region, while protecting against overflows caused by any
2356// offsets. If applying the offset in the transform to any of the Rects in the region would result
2357// in an overflow, they are not added to the output Region.
2358static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2359 const std::string& debugWindowName) {
2360 // Round the translation using the same rounding strategy used by ui::Transform.
2361 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2362 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2363
2364 ui::Transform transformWithoutOffset = t;
2365 transformWithoutOffset.set(0.f, 0.f);
2366
2367 const Region transformed = transformWithoutOffset.transform(r);
2368
2369 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2370 Region ret;
2371 for (const auto& rect : transformed) {
2372 Rect newRect;
2373 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2374 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2375 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2376 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2377 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2378 debugWindowName.c_str());
2379 continue;
2380 }
2381 ret.orSelf(newRect);
2382 }
2383 return ret;
2384}
2385
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002386void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002387 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2388 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002389 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002390 }
2391
Vishnu Nairfed7c122023-03-18 01:54:43 +00002392 const Rect roundedFrameInDisplay = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002393 info.frameLeft = roundedFrameInDisplay.left;
2394 info.frameTop = roundedFrameInDisplay.top;
2395 info.frameRight = roundedFrameInDisplay.right;
2396 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002397
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002398 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002399 inputToLayer.set(inputBounds.left, inputBounds.top);
2400 const ui::Transform layerToScreen = getInputTransform();
2401 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002402
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002403 // InputDispatcher expects a display-to-input transform.
2404 info.transform = inputToDisplay.inverse();
2405
2406 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002407 info.touchableRegion =
2408 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002409}
2410
chaviw3277faf2021-05-19 16:45:23 -05002411void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002412 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002413 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002414 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002415 }
2416 if (p != nullptr) {
2417 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2418 }
2419}
2420
Vishnu Naira066d902021-09-13 18:40:17 -07002421gui::DropInputMode Layer::getDropInputMode() const {
2422 gui::DropInputMode mode = mDrawingState.dropInputMode;
2423 if (mode == gui::DropInputMode::ALL) {
2424 return mode;
2425 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002426 sp<Layer> parent = mDrawingParent.promote();
2427 if (parent) {
2428 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002429 if (parentMode != gui::DropInputMode::NONE) {
2430 return parentMode;
2431 }
2432 }
2433 return mode;
2434}
2435
2436void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002437 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002438 return;
2439 }
2440
2441 // Check if we need to drop input unconditionally
2442 gui::DropInputMode dropInputMode = getDropInputMode();
2443 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002444 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002445 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2446 return;
2447 }
2448
2449 // Check if we need to check if the window is obscured by parent
2450 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2451 return;
2452 }
2453
2454 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002455 sp<Layer> parent = mDrawingParent.promote();
2456 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002457 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002458 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2459 static_cast<float>(getAlpha()));
2460 }
2461
2462 // Check if the parent has cropped the buffer
2463 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2464 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002465 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002466 return;
2467 }
2468
2469 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2470 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2471 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2472 // match then the layer has not been cropped by its parents.
2473 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2474 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2475
2476 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002477 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002478 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2479 getDebugName());
2480 } else {
2481 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2482 // input if the window is obscured. This check should be done in surfaceflinger but the
2483 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2484 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002485 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002486 }
2487}
2488
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002489WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002490 if (!hasInputInfo()) {
2491 mDrawingState.inputInfo.name = getName();
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002492 mDrawingState.inputInfo.ownerUid = gui::Uid{mOwnerUid};
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00002493 mDrawingState.inputInfo.ownerPid = gui::Pid{mOwnerPid};
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002494 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002495 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002496 }
2497
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002498 const ui::Transform& displayTransform =
2499 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2500
chaviw3277faf2021-05-19 16:45:23 -05002501 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002502 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002503 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002504
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002505 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002506
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002507 if (displayArgs.transform == nullptr) {
2508 // Do not let the window receive touches if it is not associated with a valid display
2509 // transform. We still allow the window to receive keys and prevent ANRs.
2510 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2511 }
2512
Patrick Williams1caf3b72023-03-31 10:59:10 -05002513 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !isVisibleForInput());
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002514
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002515 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002516 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002517 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002518
Vishnu Nair16a938f2021-09-24 07:14:54 -07002519 // If the window will be blacked out on a display because the display does not have the secure
2520 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002521 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002522 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002523 }
2524
Vishnu Nairfed7c122023-03-18 01:54:43 +00002525 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002526 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002527 Rect inputBoundsInDisplaySpace;
2528 if (!cropLayer) {
2529 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2530 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2531 } else {
2532 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2533 inputBoundsInDisplaySpace =
2534 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2535 }
2536 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002537 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002538 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2539 Rect inputBoundsInDisplaySpace =
2540 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2541 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002542 }
2543
Winson Chunga30f7c92021-06-29 15:42:56 -07002544 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2545 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002546 if (isTrustedOverlay()) {
2547 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2548 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002549
chaviwaf87b3e2019-10-01 16:59:28 -07002550 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2551 // touches from going outside the cloned area.
2552 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002553 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002554 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2555 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002556 info.touchableRegion = info.touchableRegion.intersect(rect);
2557 }
2558 }
2559
Robert Carr720e5062018-07-30 17:45:14 -07002560 return info;
2561}
2562
Vishnu Nairfed7c122023-03-18 01:54:43 +00002563Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2564 const ui::Transform& screenToDisplay) {
2565 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2566 // frame and transform used for the layer, which determines the bounds and the coordinate space
2567 // within which the layer will receive input.
2568
2569 // Coordinate space definitions:
2570 // - display: The display device's coordinate space. Correlates to pixels on the display.
2571 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2572 // - layer: The coordinate space of this layer.
2573 // - input: The coordinate space in which this layer will receive input events. This could be
2574 // different than layer space if a surfaceInset is used, which changes the origin
2575 // of the input space.
2576
2577 // Crop the input bounds to ensure it is within the parent's bounds.
2578 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2579 const ui::Transform layerToScreen = getInputTransform();
2580 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2581 return Rect{layerToDisplay.transform(croppedInputBounds)};
2582}
2583
chaviwaf87b3e2019-10-01 16:59:28 -07002584sp<Layer> Layer::getClonedRoot() {
2585 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002586 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002587 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002588 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002589 return nullptr;
2590 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002591 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002592}
2593
Robert Carredd13602020-04-13 17:24:34 -07002594bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002595 return mDrawingState.inputInfo.token != nullptr ||
2596 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002597}
2598
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002599compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002600 const DisplayDevice* display) const {
2601 if (!display) return nullptr;
Lloyd Pique30db6402023-06-26 18:56:51 +00002602 if (!mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00002603 return display->getCompositionDisplay()->getOutputLayerForLayer(
2604 getCompositionEngineLayerFE());
2605 }
2606 sp<LayerFE> layerFE;
2607 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2608 for (auto& [p, layer] : mLayerFEs) {
2609 if (p == path) {
2610 layerFE = layer;
2611 }
2612 }
2613
2614 if (!layerFE) return nullptr;
2615 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002616}
2617
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002618compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
2619 const DisplayDevice* display, const frontend::LayerHierarchy::TraversalPath& path) const {
2620 if (!display) return nullptr;
Vishnu Naire9ee0002023-07-01 03:14:51 +00002621 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2622 return display->getCompositionDisplay()->getOutputLayerForLayer(
2623 getCompositionEngineLayerFE());
2624 }
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002625 sp<LayerFE> layerFE;
2626 for (auto& [p, layer] : mLayerFEs) {
2627 if (p == path) {
2628 layerFE = layer;
2629 }
2630 }
2631
2632 if (!layerFE) return nullptr;
2633 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
2634}
2635
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002636Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2637 const auto outputLayer = findOutputLayerForDisplay(display);
2638 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002639}
2640
Vishnu Nairde177252023-04-21 12:44:10 -07002641void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom, uint32_t mirrorRootId) {
2642 mSnapshot->path.id = clonedFrom->getSequence();
2643 mSnapshot->path.mirrorRootId = mirrorRootId;
2644
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002645 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002646 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002647 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2648 mPotentialCursor = clonedFrom->mPotentialCursor;
2649 mProtectedByApp = clonedFrom->mProtectedByApp;
2650 updateCloneBufferInfo();
2651}
2652
2653void Layer::updateCloneBufferInfo() {
2654 if (!isClone() || !isClonedFromAlive()) {
2655 return;
2656 }
2657
2658 sp<Layer> clonedFrom = getClonedFrom();
2659 mBufferInfo = clonedFrom->mBufferInfo;
2660 mSidebandStream = clonedFrom->mSidebandStream;
2661 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2662 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2663 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2664
2665 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2666 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2667 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2668 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2669 // the cloned drawingState again.
2670 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2671 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2672 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2673 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2674
2675 cloneDrawingState(clonedFrom.get());
2676
2677 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2678 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2679 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2680 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002681}
chaviw74b03172019-08-19 11:09:03 -07002682
Vishnu Nair3be61902023-04-26 19:47:29 -07002683bool Layer::updateMirrorInfo(const std::deque<Layer*>& cloneRootsPendingUpdates) {
chaviw74b03172019-08-19 11:09:03 -07002684 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2685 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2686 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2687 // that case, we want to delete the reference to the clone since we want it to get
2688 // destroyed. The root, this layer, will still be around since the client can continue
2689 // to hold a reference, but no cloned layers will be displayed.
2690 mClonedChild = nullptr;
Vishnu Nair3be61902023-04-26 19:47:29 -07002691 return true;
chaviw74b03172019-08-19 11:09:03 -07002692 }
2693
2694 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2695 // If the real layer exists and is in current state, add the clone as a child of the root.
2696 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2697 // copied to drawingState for the root layer. So the clonedChild is always removed from
2698 // drawingState and then needs to be added back each traversal.
2699 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2700 addChildToDrawing(mClonedChild);
2701 }
2702
2703 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002704 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002705 mClonedChild->updateClonedRelatives(clonedLayersMap);
Vishnu Nair3be61902023-04-26 19:47:29 -07002706
2707 for (Layer* root : cloneRootsPendingUpdates) {
2708 if (clonedLayersMap.find(sp<Layer>::fromExisting(root)) != clonedLayersMap.end()) {
2709 return false;
2710 }
2711 }
2712 return true;
chaviw74b03172019-08-19 11:09:03 -07002713}
2714
2715void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2716 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2717 // to the clone. If the real layer is no longer alive, continue traversing the children
2718 // since we may be able to pull out other children that are still alive.
2719 if (isClonedFromAlive()) {
2720 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002721 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002722 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002723 }
2724
2725 // The clone layer may have children in drawingState since they may have been created and
2726 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2727 // that already exist, since we can just re-use them.
2728 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2729 // not updated in the regular traversal. They are skipped since the root will lose the
2730 // reference to them when it copies its currentChildren to drawing.
2731 for (sp<Layer>& child : mDrawingChildren) {
2732 child->updateClonedDrawingState(clonedLayersMap);
2733 }
2734}
2735
2736void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2737 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2738 mDrawingChildren.clear();
2739
2740 if (!isClonedFromAlive()) {
2741 return;
2742 }
2743
2744 sp<Layer> clonedFrom = getClonedFrom();
2745 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2746 if (child == mirrorRoot) {
2747 // This is to avoid cyclical mirroring.
2748 continue;
2749 }
2750 sp<Layer> clonedChild = clonedLayersMap[child];
2751 if (clonedChild == nullptr) {
Vishnu Nairde177252023-04-21 12:44:10 -07002752 clonedChild = child->createClone(mirrorRoot->getSequence());
chaviw74b03172019-08-19 11:09:03 -07002753 clonedLayersMap[child] = clonedChild;
2754 }
2755 addChildToDrawing(clonedChild);
2756 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2757 }
2758}
2759
chaviwaf87b3e2019-10-01 16:59:28 -07002760void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2761 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2762 if (cropLayer != nullptr) {
2763 if (clonedLayersMap.count(cropLayer) == 0) {
2764 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2765 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002766 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002767 } else {
2768 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2769 mDrawingState.touchableRegionCrop = clonedCropLayer;
2770 }
2771 }
2772 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2773 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002774 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002775}
2776
2777void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002778 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002779 mDrawingState.zOrderRelatives.clear();
2780
2781 if (!isClonedFromAlive()) {
2782 return;
2783 }
2784
chaviwaf87b3e2019-10-01 16:59:28 -07002785 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002786 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002787 const sp<Layer>& relative = relativeWeak.promote();
2788 if (clonedLayersMap.count(relative) > 0) {
2789 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002790 mDrawingState.zOrderRelatives.add(clonedRelative);
2791 }
2792 }
2793
2794 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2795 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2796 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2797 // still traverse the children, but the layer with the missing relativeOf will not be shown
2798 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002799 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2800 if (clonedLayersMap.count(relativeOf) > 0) {
2801 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002802 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2803 }
2804
chaviwaf87b3e2019-10-01 16:59:28 -07002805 updateClonedInputInfo(clonedLayersMap);
2806
chaviw74b03172019-08-19 11:09:03 -07002807 for (sp<Layer>& child : mDrawingChildren) {
2808 child->updateClonedRelatives(clonedLayersMap);
2809 }
2810}
2811
2812void Layer::addChildToDrawing(const sp<Layer>& layer) {
2813 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002814 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002815}
2816
Steven Thomas62a4cf82020-01-31 12:04:03 -08002817Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2818 switch (compatibility) {
2819 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2820 return FrameRateCompatibility::Default;
2821 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2822 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002823 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2824 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002825 case ANATIVEWINDOW_FRAME_RATE_MIN:
2826 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002827 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2828 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002829 default:
2830 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2831 return FrameRateCompatibility::Default;
2832 }
2833}
2834
Marin Shalamanovc5986772021-03-16 16:09:49 +01002835scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2836 switch (strategy) {
2837 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2838 return Seamlessness::OnlySeamless;
2839 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2840 return Seamlessness::SeamedAndSeamless;
2841 default:
2842 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2843 return Seamlessness::Default;
2844 }
2845}
2846
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002847bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002848 const State& s(mDrawingState);
2849 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2850 return true;
2851 }
2852
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002853 sp<Layer> parent = mDrawingParent.promote();
2854 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002855}
2856
Robert Carr6a0382d2021-07-01 15:57:17 -07002857void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2858 mClonedChild = clonedChild;
2859 mHadClonedChild = true;
Vishnu Nair3be61902023-04-26 19:47:29 -07002860 mFlinger->mLayerMirrorRoots.push_back(this);
Robert Carr6a0382d2021-07-01 15:57:17 -07002861}
2862
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002863bool Layer::setDropInputMode(gui::DropInputMode mode) {
2864 if (mDrawingState.dropInputMode == mode) {
2865 return false;
2866 }
2867 mDrawingState.dropInputMode = mode;
2868 return true;
2869}
2870
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002871void Layer::cloneDrawingState(const Layer* from) {
2872 mDrawingState = from->mDrawingState;
2873 // Skip callback info since they are not applicable for cloned layers.
2874 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002875 // TODO (b/238781169) currently broken for mirror layers because we do not
2876 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002877 mDrawingState.callbackHandles = {};
2878}
2879
Patrick Williamsbb25f802022-08-30 23:02:34 +00002880void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2881 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002882 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002883 if (!listener) {
2884 return;
2885 }
2886 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002887 uint32_t currentMaxAcquiredBufferCount =
2888 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002889 listener->onReleaseBuffer({buffer->getId(), framenumber},
2890 releaseFence ? releaseFence : Fence::NO_FENCE,
2891 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002892}
2893
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002894void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
2895 ui::LayerStack layerStack) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002896 // If we are displayed on multiple displays in a single composition cycle then we would
2897 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2898 // For example we can only use it if all the displays are client comp, and we need
2899 // to merge all the client comp fences. We could do this, but for now we just
2900 // disable the optimization when a layer is composed on multiple displays.
2901 if (mClearClientCompositionFenceOnLayerDisplayed) {
2902 mLastClientCompositionFence = nullptr;
2903 } else {
2904 mClearClientCompositionFenceOnLayerDisplayed = true;
2905 }
2906
2907 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2908 // buffer that was presented on this layer. The first transaction that came in this frame that
2909 // replaced the previous buffer on this layer needs this release fence, because the fence will
2910 // let the client know when that previous buffer is removed from the screen.
2911 //
2912 // Every other transaction on this layer does not need a release fence because no other
2913 // Transactions that were set on this layer this frame are going to have their preceding buffer
2914 // removed from the display this frame.
2915 //
2916 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2917 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2918 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2919 // the previous buffer will be released this frame. The third transaction also contains a
2920 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2921 // transaction will now no longer be presented so it is released immediately and the third
2922 // transaction doesn't need a previous release fence.
2923 sp<CallbackHandle> ch;
2924 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002925 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002926 ch = handle;
2927 break;
2928 }
2929 }
2930
2931 // Prevent tracing the same release multiple times.
2932 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2933 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2934 }
2935
2936 if (ch != nullptr) {
2937 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2938 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2939 ch->name = mName;
2940 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002941 mPreviouslyPresentedLayerStacks.push_back(layerStack);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002942}
2943
2944void Layer::onSurfaceFrameCreated(
2945 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2946 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2947 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2948 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2949 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002950 if (hasBufferOrSidebandStreamInDrawing()) {
2951 // Only log for layers with a buffer, since we expect the jank data to be drained for
2952 // these, while there may be no jank listeners for bufferless layers.
2953 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2954 mName.c_str());
2955 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2956 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2957 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002958 mPendingJankClassifications.pop_front();
2959 }
2960 mPendingJankClassifications.emplace_back(surfaceFrame);
2961}
2962
2963void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2964 for (const auto& handle : mDrawingState.callbackHandles) {
Lloyd Pique30db6402023-06-26 18:56:51 +00002965 if (mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -07002966 handle->transformHint = mTransformHint;
2967 } else {
2968 handle->transformHint = mSkipReportingTransformHint
2969 ? std::nullopt
2970 : std::make_optional<uint32_t>(mTransformHintLegacy);
2971 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002972 handle->dequeueReadyTime = dequeueReadyTime;
2973 handle->currentMaxAcquiredBufferCount =
2974 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2975 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2976 handle->previousReleaseCallbackId.framenumber);
2977 }
2978
2979 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002980 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002981 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2982 break;
2983 }
2984 }
2985
2986 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002987 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002988 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2989 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002990 mDrawingState.callbackHandles = {};
2991}
2992
2993bool Layer::willPresentCurrentTransaction() const {
2994 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2995 return (getSidebandStreamChanged() || getAutoRefresh() ||
2996 (mDrawingState.modified &&
2997 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2998}
2999
3000bool Layer::setTransform(uint32_t transform) {
3001 if (mDrawingState.bufferTransform == transform) return false;
3002 mDrawingState.bufferTransform = transform;
3003 mDrawingState.modified = true;
3004 setTransactionFlags(eTransactionNeeded);
3005 return true;
3006}
3007
3008bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
3009 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
3010 mDrawingState.sequence++;
3011 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
3012 mDrawingState.modified = true;
3013 setTransactionFlags(eTransactionNeeded);
3014 return true;
3015}
3016
3017bool Layer::setBufferCrop(const Rect& bufferCrop) {
3018 if (mDrawingState.bufferCrop == bufferCrop) return false;
3019
3020 mDrawingState.sequence++;
3021 mDrawingState.bufferCrop = bufferCrop;
3022
3023 mDrawingState.modified = true;
3024 setTransactionFlags(eTransactionNeeded);
3025 return true;
3026}
3027
3028bool Layer::setDestinationFrame(const Rect& destinationFrame) {
3029 if (mDrawingState.destinationFrame == destinationFrame) return false;
3030
3031 mDrawingState.sequence++;
3032 mDrawingState.destinationFrame = destinationFrame;
3033
3034 mDrawingState.modified = true;
3035 setTransactionFlags(eTransactionNeeded);
3036 return true;
3037}
3038
3039// Translate destination frame into scale and position. If a destination frame is not set, use the
3040// provided scale and position
3041bool Layer::updateGeometry() {
3042 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
3043 mDrawingState.destinationFrame.isEmpty()) {
3044 // If destination frame is not set, use the requested transform set via
3045 // Layer::setPosition and Layer::setMatrix.
3046 return assignTransform(&mDrawingState.transform, mRequestedTransform);
3047 }
3048
3049 Rect destRect = mDrawingState.destinationFrame;
3050 int32_t destW = destRect.width();
3051 int32_t destH = destRect.height();
3052 if (destRect.left < 0) {
3053 destRect.left = 0;
3054 destRect.right = destW;
3055 }
3056 if (destRect.top < 0) {
3057 destRect.top = 0;
3058 destRect.bottom = destH;
3059 }
3060
3061 if (!mDrawingState.buffer) {
3062 ui::Transform t;
3063 t.set(destRect.left, destRect.top);
3064 return assignTransform(&mDrawingState.transform, t);
3065 }
3066
3067 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3068 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3069 // Undo any transformations on the buffer.
3070 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3071 std::swap(bufferWidth, bufferHeight);
3072 }
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003073 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003074 if (mDrawingState.transformToDisplayInverse) {
3075 if (invTransform & ui::Transform::ROT_90) {
3076 std::swap(bufferWidth, bufferHeight);
3077 }
3078 }
3079
3080 float sx = destW / static_cast<float>(bufferWidth);
3081 float sy = destH / static_cast<float>(bufferHeight);
3082 ui::Transform t;
3083 t.set(sx, 0, 0, sy);
3084 t.set(destRect.left, destRect.top);
3085 return assignTransform(&mDrawingState.transform, t);
3086}
3087
3088bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3089 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3090 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3091 return false;
3092 }
3093
3094 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3095
3096 mDrawingState.sequence++;
3097 mDrawingState.modified = true;
3098 setTransactionFlags(eTransactionNeeded);
3099
3100 return true;
3101}
3102
3103bool Layer::setPosition(float x, float y) {
3104 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3105 return false;
3106 }
3107
3108 mRequestedTransform.set(x, y);
3109
3110 mDrawingState.sequence++;
3111 mDrawingState.modified = true;
3112 setTransactionFlags(eTransactionNeeded);
3113
3114 return true;
3115}
3116
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003117void Layer::resetDrawingStateBufferInfo() {
3118 mDrawingState.producerId = 0;
3119 mDrawingState.frameNumber = 0;
3120 mDrawingState.releaseBufferListener = nullptr;
3121 mDrawingState.buffer = nullptr;
3122 mDrawingState.acquireFence = sp<Fence>::make(-1);
3123 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3124 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3125 mDrawingState.releaseBufferEndpoint = nullptr;
3126}
3127
Patrick Williamsbb25f802022-08-30 23:02:34 +00003128bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3129 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3130 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003131 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003132 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003133
3134 const bool frameNumberChanged =
3135 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3136 const uint64_t frameNumber =
3137 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003138 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003139
3140 if (mDrawingState.buffer) {
3141 mReleasePreviousBuffer = true;
3142 if (!mBufferInfo.mBuffer ||
3143 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3144 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3145 // If mDrawingState has a buffer, and we are about to update again
3146 // before swapping to drawing state, then the first buffer will be
3147 // dropped and we should decrement the pending buffer count and
3148 // call any release buffer callbacks if set.
3149 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3150 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003151 mDrawingState.acquireFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003152 decrementPendingBufferCount();
3153 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3154 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
Ady Abraham5a3e3562023-06-07 10:32:08 -07003155 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX, systemTime());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003156 mDrawingState.bufferSurfaceFrameTX.reset();
3157 }
3158 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3159 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3160 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003161 mLastClientCompositionFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003162 mLastClientCompositionFence = nullptr;
3163 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003164 } else if (buffer) {
Vishnu Nairc09c0232023-03-02 03:22:35 +00003165 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3166 // we don't want to incorrectly classify a frame if we miss the desired present time.
3167 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003168 }
3169
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003170 mDrawingState.desiredPresentTime = desiredPresentTime;
3171 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3172 mDrawingState.latchedVsyncId = info.vsyncId;
Ady Abraham55269162023-05-09 11:26:06 -07003173 mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003174 mDrawingState.modified = true;
3175 if (!buffer) {
3176 resetDrawingStateBufferInfo();
3177 setTransactionFlags(eTransactionNeeded);
3178 mDrawingState.bufferSurfaceFrameTX = nullptr;
3179 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3180 return true;
3181 }
3182
Vishnu Naird1f74982023-06-15 20:16:51 -07003183 if ((mDrawingState.producerId > bufferData.producerId) ||
3184 ((mDrawingState.producerId == bufferData.producerId) &&
3185 (mDrawingState.frameNumber > frameNumber))) {
3186 ALOGE("Out of order buffers detected for %s producedId=%d frameNumber=%" PRIu64
3187 " -> producedId=%d frameNumber=%" PRIu64,
3188 getDebugName(), mDrawingState.producerId, mDrawingState.frameNumber,
3189 bufferData.producerId, frameNumber);
3190 TransactionTraceWriter::getInstance().invoke("out_of_order_buffers_", /*overwrite=*/false);
3191 }
3192
liulijuneb489f62022-10-17 22:02:14 +08003193 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -07003194 mDrawingState.barrierProducerId =
3195 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003196 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -07003197 mDrawingState.barrierFrameNumber =
3198 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
3199
Patrick Williamsbb25f802022-08-30 23:02:34 +00003200 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3201 mDrawingState.buffer = std::move(buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003202 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3203 ? bufferData.acquireFence
3204 : Fence::NO_FENCE;
3205 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3206 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3207 // We latched this buffer unsiganled, so we need to pass the acquire fence
3208 // on the callback instead of just the acquire time, since it's unknown at
3209 // this point.
3210 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3211 } else {
3212 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3213 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003214 setTransactionFlags(eTransactionNeeded);
3215
3216 const int32_t layerId = getSequence();
3217 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3218 mOwnerUid, postTime, getGameMode());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003219
Lloyd Pique30db6402023-06-26 18:56:51 +00003220 if (mFlinger->mLegacyFrontEndEnabled) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003221 recordLayerHistoryBufferUpdate(getLayerProps());
3222 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003223
3224 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3225
3226 if (dequeueTime && *dequeueTime != 0) {
3227 const uint64_t bufferId = mDrawingState.buffer->getId();
3228 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3229 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3230 FrameTracer::FrameEvent::DEQUEUE);
3231 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3232 FrameTracer::FrameEvent::QUEUE);
3233 }
3234
3235 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3236 return true;
3237}
3238
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003239void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3240 mDrawingState.desiredPresentTime = desiredPresentTime;
3241 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3242}
3243
3244void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps) {
Ady Abraham55269162023-05-09 11:26:06 -07003245 ATRACE_CALL();
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003246 const nsecs_t presentTime = [&] {
Ady Abraham55269162023-05-09 11:26:06 -07003247 if (!mDrawingState.isAutoTimestamp) {
3248 ATRACE_FORMAT_INSTANT("desiredPresentTime");
3249 return mDrawingState.desiredPresentTime;
3250 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003251
Ady Abraham55269162023-05-09 11:26:06 -07003252 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3253 const auto prediction =
3254 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3255 mDrawingState.latchedVsyncId);
3256 if (prediction.has_value()) {
3257 ATRACE_FORMAT_INSTANT("predictedPresentTime");
3258 return prediction->presentTime;
3259 }
3260 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003261
3262 return static_cast<nsecs_t>(0);
3263 }();
Ady Abraham55269162023-05-09 11:26:06 -07003264
3265 if (ATRACE_ENABLED() && presentTime > 0) {
3266 const auto presentIn = TimePoint::fromNs(presentTime) - TimePoint::now();
3267 ATRACE_FORMAT_INSTANT("presentIn %s", to_string(presentIn).c_str());
3268 }
3269
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003270 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3271 scheduler::LayerHistory::LayerUpdateType::Buffer);
3272}
3273
3274void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps) {
3275 const nsecs_t presentTime =
3276 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
3277 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3278 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3279}
3280
Patrick Williamsbb25f802022-08-30 23:02:34 +00003281bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003282 if (mDrawingState.dataspace == dataspace) return false;
3283 mDrawingState.dataspace = dataspace;
3284 mDrawingState.modified = true;
3285 setTransactionFlags(eTransactionNeeded);
3286 return true;
3287}
3288
John Reck68796592023-01-25 13:47:12 -05003289bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07003290 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3291 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05003292 return false;
Sally Qi963049b2023-03-23 14:06:21 -07003293 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3294 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05003295 mDrawingState.modified = true;
3296 setTransactionFlags(eTransactionNeeded);
3297 return true;
3298}
3299
Alec Mourif4af03e2023-02-11 00:25:24 +00003300bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3301 if (mDrawingState.cachingHint == cachingHint) return false;
3302 mDrawingState.cachingHint = cachingHint;
3303 mDrawingState.modified = true;
3304 setTransactionFlags(eTransactionNeeded);
3305 return true;
3306}
3307
Patrick Williamsbb25f802022-08-30 23:02:34 +00003308bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3309 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3310 mDrawingState.hdrMetadata = hdrMetadata;
3311 mDrawingState.modified = true;
3312 setTransactionFlags(eTransactionNeeded);
3313 return true;
3314}
3315
3316bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003317 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003318 mDrawingState.surfaceDamageRegion = surfaceDamage;
3319 mDrawingState.modified = true;
3320 setTransactionFlags(eTransactionNeeded);
3321 return true;
3322}
3323
3324bool Layer::setApi(int32_t api) {
3325 if (mDrawingState.api == api) return false;
3326 mDrawingState.api = api;
3327 mDrawingState.modified = true;
3328 setTransactionFlags(eTransactionNeeded);
3329 return true;
3330}
3331
3332bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3333 if (mDrawingState.sidebandStream == sidebandStream) return false;
3334
3335 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3336 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3337 } else if (sidebandStream != nullptr) {
3338 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3339 }
3340
3341 mDrawingState.sidebandStream = sidebandStream;
3342 mDrawingState.modified = true;
3343 setTransactionFlags(eTransactionNeeded);
3344 if (!mSidebandStreamChanged.exchange(true)) {
3345 // mSidebandStreamChanged was false
3346 mFlinger->onLayerUpdate();
3347 }
3348 return true;
3349}
3350
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003351bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3352 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003353 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3354 if (handles.empty()) {
3355 mReleasePreviousBuffer = false;
3356 return false;
3357 }
3358
Pascal Muetschard81cef292023-02-06 12:18:52 +01003359 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003360 for (const auto& handle : handles) {
3361 // If this transaction set a buffer on this layer, release its previous buffer
3362 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3363
3364 // If this layer will be presented in this frame
3365 if (willPresent) {
3366 // If this transaction set an acquire fence on this layer, set its acquire time
3367 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3368 handle->frameNumber = mDrawingState.frameNumber;
3369
3370 // Store so latched time and release fence can be set
3371 mDrawingState.callbackHandles.push_back(handle);
3372
3373 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003374 // Queue this handle to be notified below.
3375 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003376 }
3377 }
3378
Pascal Muetschard81cef292023-02-06 12:18:52 +01003379 if (!remainingHandles.empty()) {
3380 // Notify the transaction completed threads these handles are done. These are only the
3381 // handles that were not added to the mDrawingState, which will be notified later.
3382 std::vector<JankData> jankData;
3383 transferAvailableJankData(remainingHandles, jankData);
3384 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3385 }
3386
Patrick Williamsbb25f802022-08-30 23:02:34 +00003387 mReleasePreviousBuffer = false;
3388 mCallbackHandleAcquireTimeOrFence = -1;
3389
3390 return willPresent;
3391}
3392
3393Rect Layer::getBufferSize(const State& /*s*/) const {
3394 // for buffer state layers we use the display frame size as the buffer size.
3395
3396 if (mBufferInfo.mBuffer == nullptr) {
3397 return Rect::INVALID_RECT;
3398 }
3399
3400 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3401 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3402
3403 // Undo any transformations on the buffer and return the result.
3404 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3405 std::swap(bufWidth, bufHeight);
3406 }
3407
3408 if (getTransformToDisplayInverse()) {
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003409 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003410 if (invTransform & ui::Transform::ROT_90) {
3411 std::swap(bufWidth, bufHeight);
3412 }
3413 }
3414
3415 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3416}
3417
3418FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3419 if (mBufferInfo.mBuffer == nullptr) {
3420 return parentBounds;
3421 }
3422
3423 return getBufferSize(getDrawingState()).toFloatRect();
3424}
3425
3426bool Layer::fenceHasSignaled() const {
3427 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3428 return true;
3429 }
3430
3431 const bool fenceSignaled =
3432 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3433 if (!fenceSignaled) {
3434 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3435 TimeStats::LatchSkipReason::LateAcquire);
3436 }
3437
3438 return fenceSignaled;
3439}
3440
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003441void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003442 for (const auto& handle : mDrawingState.callbackHandles) {
3443 handle->refreshStartTime = refreshStartTime;
3444 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003445}
3446
3447void Layer::setAutoRefresh(bool autoRefresh) {
3448 mDrawingState.autoRefresh = autoRefresh;
3449}
3450
3451bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3452 // 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 +00003453 auto* snapshot = editLayerSnapshot();
3454 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003455
3456 if (mSidebandStreamChanged.exchange(false)) {
3457 const State& s(getDrawingState());
3458 // mSidebandStreamChanged was true
3459 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003460 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003461 if (mSidebandStream != nullptr) {
3462 setTransactionFlags(eTransactionNeeded);
3463 mFlinger->setTransactionFlags(eTraversalNeeded);
3464 }
3465 recomputeVisibleRegions = true;
3466
3467 return true;
3468 }
3469 return false;
3470}
3471
3472bool Layer::hasFrameUpdate() const {
3473 const State& c(getDrawingState());
3474 return (mDrawingStateModified || mDrawingState.modified) &&
3475 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3476}
3477
Vishnu Naird47bcee2023-02-24 18:08:51 +00003478void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003479 const State& s(getDrawingState());
3480
3481 if (!s.buffer) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003482 if (bgColorOnly || mBufferInfo.mBuffer) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003483 for (auto& handle : mDrawingState.callbackHandles) {
3484 handle->latchTime = latchTime;
3485 }
3486 }
3487 return;
3488 }
3489
3490 for (auto& handle : mDrawingState.callbackHandles) {
3491 if (handle->frameNumber == mDrawingState.frameNumber) {
3492 handle->latchTime = latchTime;
3493 }
3494 }
3495
3496 const int32_t layerId = getSequence();
3497 const uint64_t bufferId = mDrawingState.buffer->getId();
3498 const uint64_t frameNumber = mDrawingState.frameNumber;
3499 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3500 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3501 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3502
3503 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3504 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3505 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3506 FrameTracer::FrameEvent::LATCH);
3507
3508 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3509 if (bufferSurfaceFrame != nullptr &&
3510 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3511 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3512 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3513 // are processing the next state.
3514 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3515 mDrawingState.acquireFenceTime->getSignalTime(),
3516 latchTime);
3517 mDrawingState.bufferSurfaceFrameTX.reset();
3518 }
3519
3520 std::deque<sp<CallbackHandle>> remainingHandles;
3521 mFlinger->getTransactionCallbackInvoker()
3522 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3523 mDrawingState.callbackHandles = remainingHandles;
3524
3525 mDrawingStateModified = false;
3526}
3527
3528void Layer::gatherBufferInfo() {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003529 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3530 mPreviousReleaseBufferEndpoint = mBufferInfo.mReleaseBufferEndpoint;
3531 if (!mDrawingState.buffer) {
3532 mBufferInfo = {};
3533 return;
3534 }
3535
3536 if ((!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer))) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003537 decrementPendingBufferCount();
3538 }
3539
Patrick Williamsbb25f802022-08-30 23:02:34 +00003540 mBufferInfo.mBuffer = mDrawingState.buffer;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003541 mBufferInfo.mReleaseBufferEndpoint = mDrawingState.releaseBufferEndpoint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003542 mBufferInfo.mFence = mDrawingState.acquireFence;
3543 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3544 mBufferInfo.mPixelFormat =
3545 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3546 mBufferInfo.mFrameLatencyNeeded = true;
3547 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3548 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3549 mBufferInfo.mFence = mDrawingState.acquireFence;
3550 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3551 auto lastDataspace = mBufferInfo.mDataspace;
3552 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003553 if (mBufferInfo.mBuffer != nullptr) {
3554 auto& mapper = GraphicBufferMapper::get();
3555 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
3556 // and don't need to possibly remaps buffers.
3557 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
3558 status_t err = OK;
3559 {
3560 ATRACE_NAME("getDataspace");
3561 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
3562 }
3563 if (err != OK || dataspace != mBufferInfo.mDataspace) {
3564 {
3565 ATRACE_NAME("setDataspace");
3566 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
3567 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
3568 }
3569
3570 // Some GPU drivers may cache gralloc metadata which means before we composite we need
3571 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
3572 // compatible with old vendors, with a ticking clock.
3573 static const int32_t kVendorVersion =
3574 base::GetIntProperty("ro.vndk.version", __ANDROID_API_FUTURE__);
3575 if (const auto format =
3576 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
3577 mBufferInfo.mBuffer->getPixelFormat());
3578 err == OK && kVendorVersion < __ANDROID_API_U__ &&
3579 (format ==
3580 aidl::android::hardware::graphics::common::PixelFormat::
3581 IMPLEMENTATION_DEFINED ||
3582 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
3583 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
3584 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
3585 mBufferInfo.mBuffer->remapBuffer();
3586 }
3587 }
3588 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003589 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003590 mFlinger->mHdrLayerInfoChanged = true;
3591 }
Sally Qi963049b2023-03-23 14:06:21 -07003592 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3593 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05003594 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003595 }
3596 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3597 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3598 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3599 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3600 mBufferInfo.mApi = mDrawingState.api;
3601 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003602}
3603
3604Rect Layer::computeBufferCrop(const State& s) {
3605 if (s.buffer && !s.bufferCrop.isEmpty()) {
3606 Rect bufferCrop;
3607 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3608 return bufferCrop;
3609 } else if (s.buffer) {
3610 return s.buffer->getBounds();
3611 } else {
3612 return s.bufferCrop;
3613 }
3614}
3615
Vishnu Nairde177252023-04-21 12:44:10 -07003616sp<Layer> Layer::createClone(uint32_t mirrorRootId) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003617 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
Patrick Williams83f36b22022-09-14 17:57:35 +00003618 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Vishnu Nairde177252023-04-21 12:44:10 -07003619 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this), mirrorRootId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003620 return layer;
3621}
3622
Patrick Williamsbb25f802022-08-30 23:02:34 +00003623void Layer::decrementPendingBufferCount() {
3624 int32_t pendingBuffers = --mPendingBufferTransactions;
3625 tracePendingBufferCount(pendingBuffers);
3626}
3627
3628void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3629 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3630}
3631
3632/*
3633 * We don't want to send the layer's transform to input, but rather the
3634 * parent's transform. This is because Layer's transform is
3635 * information about how the buffer is placed on screen. The parent's
3636 * transform makes more sense to send since it's information about how the
3637 * layer is placed on screen. This transform is used by input to determine
3638 * how to go from screen space back to window space.
3639 */
3640ui::Transform Layer::getInputTransform() const {
3641 if (!hasBufferOrSidebandStream()) {
3642 return getTransform();
3643 }
3644 sp<Layer> parent = mDrawingParent.promote();
3645 if (parent == nullptr) {
3646 return ui::Transform();
3647 }
3648
3649 return parent->getTransform();
3650}
3651
3652/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003653 * Returns the bounds used to fill the input frame and the touchable region.
3654 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003655 * Similar to getInputTransform, we need to update the bounds to include the transform.
3656 * This is because bounds don't include the buffer transform, where the input assumes
3657 * that's already included.
3658 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003659std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3660 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3661 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3662 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3663 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3664 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003665 }
3666
Vishnu Nairfed7c122023-03-18 01:54:43 +00003667 bool inputBoundsValid = croppedBufferSize.isValid();
3668 if (!inputBoundsValid) {
3669 /**
3670 * Input bounds are based on the layer crop or buffer size. But if we are using
3671 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3672 * we can use the parent bounds as the input bounds if the layer does not have buffer
3673 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3674 * use the parent bounds. A layer without a buffer can get input. So when a window is
3675 * initially added, its touchable region can fill its parent layer bounds and that can
3676 * have negative consequences.
3677 */
3678 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003679 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003680
3681 // Clamp surface inset to the input bounds.
3682 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3683 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3684 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3685
3686 // Apply the insets to the input bounds.
3687 inputBounds.left += xSurfaceInset;
3688 inputBounds.top += ySurfaceInset;
3689 inputBounds.right -= xSurfaceInset;
3690 inputBounds.bottom -= ySurfaceInset;
3691
3692 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003693}
3694
Ady Abraham005398b2023-06-05 13:59:41 -07003695bool Layer::isSimpleBufferUpdate(const layer_state_t& s) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003696 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3697
3698 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3699 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3700 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3701 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3702 layer_state_t::eReparent;
3703
Patrick Williamsbb25f802022-08-30 23:02:34 +00003704 if ((s.what & requiredFlags) != requiredFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003705 ATRACE_FORMAT_INSTANT("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3706 (s.what | requiredFlags) & ~s.what);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003707 return false;
3708 }
3709
3710 if (s.what & deniedFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003711 ATRACE_FORMAT_INSTANT("%s: false [has denied flags 0x%" PRIx64 "]", __func__,
3712 s.what & deniedFlags);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003713 return false;
3714 }
3715
Patrick Williamsbb25f802022-08-30 23:02:34 +00003716 if (s.what & layer_state_t::ePositionChanged) {
3717 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
Ady Abraham005398b2023-06-05 13:59:41 -07003718 ATRACE_FORMAT_INSTANT("%s: false [ePositionChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003719 return false;
3720 }
3721 }
3722
3723 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003724 if (mDrawingState.color.a != s.color.a) {
Ady Abraham005398b2023-06-05 13:59:41 -07003725 ATRACE_FORMAT_INSTANT("%s: false [eAlphaChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003726 return false;
3727 }
3728 }
3729
3730 if (s.what & layer_state_t::eColorTransformChanged) {
3731 if (mDrawingState.colorTransform != s.colorTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003732 ATRACE_FORMAT_INSTANT("%s: false [eColorTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003733 return false;
3734 }
3735 }
3736
3737 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003738 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Ady Abraham005398b2023-06-05 13:59:41 -07003739 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundColorChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003740 return false;
3741 }
3742 }
3743
3744 if (s.what & layer_state_t::eMatrixChanged) {
3745 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3746 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3747 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3748 mRequestedTransform.dsdy() != s.matrix.dsdy) {
Ady Abraham005398b2023-06-05 13:59:41 -07003749 ATRACE_FORMAT_INSTANT("%s: false [eMatrixChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003750 return false;
3751 }
3752 }
3753
3754 if (s.what & layer_state_t::eCornerRadiusChanged) {
3755 if (mDrawingState.cornerRadius != s.cornerRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003756 ATRACE_FORMAT_INSTANT("%s: false [eCornerRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003757 return false;
3758 }
3759 }
3760
3761 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3762 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
Ady Abraham005398b2023-06-05 13:59:41 -07003763 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003764 return false;
3765 }
3766 }
3767
Vishnu Nairbbceb462022-10-10 04:52:13 +00003768 if (s.what & layer_state_t::eBufferTransformChanged) {
3769 if (mDrawingState.bufferTransform != s.bufferTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003770 ATRACE_FORMAT_INSTANT("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003771 return false;
3772 }
3773 }
3774
3775 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3776 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
Ady Abraham005398b2023-06-05 13:59:41 -07003777 ATRACE_FORMAT_INSTANT("%s: false [eTransformToDisplayInverseChanged changed]",
3778 __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003779 return false;
3780 }
3781 }
3782
3783 if (s.what & layer_state_t::eCropChanged) {
3784 if (mDrawingState.crop != s.crop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003785 ATRACE_FORMAT_INSTANT("%s: false [eCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003786 return false;
3787 }
3788 }
3789
3790 if (s.what & layer_state_t::eDataspaceChanged) {
3791 if (mDrawingState.dataspace != s.dataspace) {
Ady Abraham005398b2023-06-05 13:59:41 -07003792 ATRACE_FORMAT_INSTANT("%s: false [eDataspaceChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003793 return false;
3794 }
3795 }
3796
3797 if (s.what & layer_state_t::eHdrMetadataChanged) {
3798 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
Ady Abraham005398b2023-06-05 13:59:41 -07003799 ATRACE_FORMAT_INSTANT("%s: false [eHdrMetadataChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003800 return false;
3801 }
3802 }
3803
3804 if (s.what & layer_state_t::eSidebandStreamChanged) {
3805 if (mDrawingState.sidebandStream != s.sidebandStream) {
Ady Abraham005398b2023-06-05 13:59:41 -07003806 ATRACE_FORMAT_INSTANT("%s: false [eSidebandStreamChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003807 return false;
3808 }
3809 }
3810
3811 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3812 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
Ady Abraham005398b2023-06-05 13:59:41 -07003813 ATRACE_FORMAT_INSTANT("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003814 return false;
3815 }
3816 }
3817
3818 if (s.what & layer_state_t::eShadowRadiusChanged) {
3819 if (mDrawingState.shadowRadius != s.shadowRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003820 ATRACE_FORMAT_INSTANT("%s: false [eShadowRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003821 return false;
3822 }
3823 }
3824
3825 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3826 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
Ady Abraham005398b2023-06-05 13:59:41 -07003827 ATRACE_FORMAT_INSTANT("%s: false [eFixedTransformHintChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003828 return false;
3829 }
3830 }
3831
3832 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3833 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
Ady Abraham005398b2023-06-05 13:59:41 -07003834 ATRACE_FORMAT_INSTANT("%s: false [eTrustedOverlayChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003835 return false;
3836 }
3837 }
3838
3839 if (s.what & layer_state_t::eStretchChanged) {
3840 StretchEffect temp = s.stretchEffect;
3841 temp.sanitize();
3842 if (mDrawingState.stretchEffect != temp) {
Ady Abraham005398b2023-06-05 13:59:41 -07003843 ATRACE_FORMAT_INSTANT("%s: false [eStretchChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003844 return false;
3845 }
3846 }
3847
3848 if (s.what & layer_state_t::eBufferCropChanged) {
3849 if (mDrawingState.bufferCrop != s.bufferCrop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003850 ATRACE_FORMAT_INSTANT("%s: false [eBufferCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003851 return false;
3852 }
3853 }
3854
3855 if (s.what & layer_state_t::eDestinationFrameChanged) {
3856 if (mDrawingState.destinationFrame != s.destinationFrame) {
Ady Abraham005398b2023-06-05 13:59:41 -07003857 ATRACE_FORMAT_INSTANT("%s: false [eDestinationFrameChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003858 return false;
3859 }
3860 }
3861
3862 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3863 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
Ady Abraham005398b2023-06-05 13:59:41 -07003864 ATRACE_FORMAT_INSTANT("%s: false [eDimmingEnabledChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003865 return false;
3866 }
3867 }
3868
John Reck68796592023-01-25 13:47:12 -05003869 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07003870 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
3871 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
Ady Abraham005398b2023-06-05 13:59:41 -07003872 ATRACE_FORMAT_INSTANT("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05003873 return false;
3874 }
3875 }
3876
Patrick Williamsbb25f802022-08-30 23:02:34 +00003877 return true;
3878}
3879
Vishnu Naire14c6b32022-08-06 04:20:15 +00003880sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003881 // 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 +00003882 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003883}
3884
Vishnu Naire14c6b32022-08-06 04:20:15 +00003885const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003886 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003887}
3888
Vishnu Naire14c6b32022-08-06 04:20:15 +00003889LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003890 return mSnapshot.get();
3891}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003892
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003893std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3894 return std::move(mSnapshot);
3895}
3896
3897void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3898 mSnapshot = std::move(snapshot);
3899}
3900
Patrick Williamsbb25f802022-08-30 23:02:34 +00003901const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003902 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003903}
3904
Patrick Williams7584c6a2022-10-29 02:10:58 +00003905sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003906 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003907 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3908 return result;
3909}
3910
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003911sp<LayerFE> Layer::getCompositionEngineLayerFE(
3912 const frontend::LayerHierarchy::TraversalPath& path) {
3913 for (auto& [p, layerFE] : mLayerFEs) {
3914 if (p == path) {
3915 return layerFE;
3916 }
3917 }
3918 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3919 mLayerFEs.emplace_back(path, layerFE);
3920 return layerFE;
3921}
3922
Patrick Williamsbb25f802022-08-30 23:02:34 +00003923void Layer::useSurfaceDamage() {
3924 if (mFlinger->mForceFullDamage) {
3925 surfaceDamageRegion = Region::INVALID_REGION;
3926 } else {
3927 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3928 }
3929}
3930
3931void Layer::useEmptyDamage() {
3932 surfaceDamageRegion.clear();
3933}
3934
3935bool Layer::isOpaque(const Layer::State& s) const {
3936 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3937 // layer's opaque flag.
3938 if (!hasSomethingToDraw()) {
3939 return false;
3940 }
3941
3942 // if the layer has the opaque flag, then we're always opaque
3943 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3944 return true;
3945 }
3946
3947 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003948 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003949 return true;
3950 }
3951
3952 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3953 return fillsColor() && getAlpha() == 1.0_hf;
3954}
3955
3956bool Layer::canReceiveInput() const {
3957 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3958}
3959
3960bool Layer::isVisible() const {
3961 if (!hasSomethingToDraw()) {
3962 return false;
3963 }
3964
3965 if (isHiddenByPolicy()) {
3966 return false;
3967 }
3968
3969 return getAlpha() > 0.0f || hasBlur();
3970}
3971
3972void Layer::onPostComposition(const DisplayDevice* display,
3973 const std::shared_ptr<FenceTime>& glDoneFence,
3974 const std::shared_ptr<FenceTime>& presentFence,
3975 const CompositorTiming& compositorTiming) {
3976 // mFrameLatencyNeeded is true when a new frame was latched for the
3977 // composition.
3978 if (!mBufferInfo.mFrameLatencyNeeded) return;
3979
3980 for (const auto& handle : mDrawingState.callbackHandles) {
3981 handle->gpuCompositionDoneFence = glDoneFence;
3982 handle->compositorTiming = compositorTiming;
3983 }
3984
3985 // Update mFrameTracker.
3986 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3987 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3988
3989 const int32_t layerId = getSequence();
3990 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3991
3992 const auto outputLayer = findOutputLayerForDisplay(display);
3993 if (outputLayer && outputLayer->requiresClientComposition()) {
3994 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3995 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3996 clientCompositionTimestamp,
3997 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3998 // Update the SurfaceFrames in the drawing state
3999 if (mDrawingState.bufferSurfaceFrameTX) {
4000 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
4001 }
4002 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
4003 surfaceFrame->setGpuComposition();
4004 }
4005 }
4006
4007 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
4008 if (frameReadyFence->isValid()) {
4009 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
4010 } else {
4011 // There was no fence for this frame, so assume that it was ready
4012 // to be presented at the desired present time.
4013 mFrameTracker.setFrameReadyTime(desiredPresentTime);
4014 }
4015
4016 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08004017 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004018 const std::optional<Fps> renderRate =
4019 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
4020
Alec Mouri7c1d8b52023-08-29 20:14:46 +00004021 const auto vote = frameRateToSetFrameRateVotePayload(getFrameRateForLayerTree());
Patrick Williamsbb25f802022-08-30 23:02:34 +00004022 const auto gameMode = getGameMode();
4023
4024 if (presentFence->isValid()) {
4025 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
4026 refreshRate, renderRate, vote, gameMode);
4027 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4028 presentFence,
4029 FrameTracer::FrameEvent::PRESENT_FENCE);
4030 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
4031 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
4032 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04004033 // The HWC doesn't support present fences, so use the present timestamp instead.
4034 const nsecs_t presentTimestamp =
4035 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
4036
4037 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
4038 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
4039 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
4040
Patrick Williamsbb25f802022-08-30 23:02:34 +00004041 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
4042 refreshRate, renderRate, vote, gameMode);
4043 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
4044 mCurrentFrameNumber, actualPresentTime,
4045 FrameTracer::FrameEvent::PRESENT_FENCE);
4046 mFrameTracker.setActualPresentTime(actualPresentTime);
4047 }
4048 }
4049
4050 mFrameTracker.advanceFrame();
4051 mBufferInfo.mFrameLatencyNeeded = false;
4052}
4053
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004054bool Layer::willReleaseBufferOnLatch() const {
4055 return !mDrawingState.buffer && mBufferInfo.mBuffer;
4056}
4057
Patrick Williamsbb25f802022-08-30 23:02:34 +00004058bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00004059 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
4060 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
4061}
4062
4063bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004064 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
4065 getDrawingState().frameNumber);
4066
4067 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
4068
4069 if (refreshRequired) {
4070 return refreshRequired;
4071 }
4072
4073 // If the head buffer's acquire fence hasn't signaled yet, return and
4074 // try again later
4075 if (!fenceHasSignaled()) {
4076 ATRACE_NAME("!fenceHasSignaled()");
4077 mFlinger->onLayerUpdate();
4078 return false;
4079 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00004080 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004081
4082 // Capture the old state of the layer for comparisons later
4083 BufferInfo oldBufferInfo = mBufferInfo;
4084 const bool oldOpacity = isOpaque(mDrawingState);
4085 mPreviousFrameNumber = mCurrentFrameNumber;
4086 mCurrentFrameNumber = mDrawingState.frameNumber;
4087 gatherBufferInfo();
4088
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004089 if (mBufferInfo.mBuffer) {
4090 // We latched a buffer that will be presented soon. Clear the previously presented layer
4091 // stack list.
4092 mPreviouslyPresentedLayerStacks.clear();
4093 }
4094
4095 if (mDrawingState.buffer == nullptr) {
4096 const bool bufferReleased = oldBufferInfo.mBuffer != nullptr;
4097 recomputeVisibleRegions = bufferReleased;
4098 return bufferReleased;
4099 }
4100
Patrick Williamsbb25f802022-08-30 23:02:34 +00004101 if (oldBufferInfo.mBuffer == nullptr) {
4102 // the first time we receive a buffer, we need to trigger a
4103 // geometry invalidation.
4104 recomputeVisibleRegions = true;
4105 }
4106
4107 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
4108 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
4109 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
4110 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
4111 recomputeVisibleRegions = true;
4112 }
4113
4114 if (oldBufferInfo.mBuffer != nullptr) {
4115 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
4116 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
4117 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
4118 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
4119 recomputeVisibleRegions = true;
4120 }
4121 }
4122
4123 if (oldOpacity != isOpaque(mDrawingState)) {
4124 recomputeVisibleRegions = true;
4125 }
4126
4127 return true;
4128}
4129
4130bool Layer::hasReadyFrame() const {
4131 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4132}
4133
4134bool Layer::isProtected() const {
4135 return (mBufferInfo.mBuffer != nullptr) &&
4136 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4137}
4138
Patrick Williamsbb25f802022-08-30 23:02:34 +00004139void Layer::latchAndReleaseBuffer() {
4140 if (hasReadyFrame()) {
4141 bool ignored = false;
4142 latchBuffer(ignored, systemTime());
4143 }
4144 releasePendingBuffer(systemTime());
4145}
4146
4147PixelFormat Layer::getPixelFormat() const {
4148 return mBufferInfo.mPixelFormat;
4149}
4150
4151bool Layer::getTransformToDisplayInverse() const {
4152 return mBufferInfo.mTransformToDisplayInverse;
4153}
4154
4155Rect Layer::getBufferCrop() const {
4156 // this is the crop rectangle that applies to the buffer
4157 // itself (as opposed to the window)
4158 if (!mBufferInfo.mCrop.isEmpty()) {
4159 // if the buffer crop is defined, we use that
4160 return mBufferInfo.mCrop;
4161 } else if (mBufferInfo.mBuffer != nullptr) {
4162 // otherwise we use the whole buffer
4163 return mBufferInfo.mBuffer->getBounds();
4164 } else {
4165 // if we don't have a buffer yet, we use an empty/invalid crop
4166 return Rect();
4167 }
4168}
4169
4170uint32_t Layer::getBufferTransform() const {
4171 return mBufferInfo.mTransform;
4172}
4173
4174ui::Dataspace Layer::getDataSpace() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004175 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4176}
4177
4178ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4179 ui::Dataspace updatedDataspace = dataspace;
4180 // translate legacy dataspaces to modern dataspaces
4181 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00004182 // Treat unknown dataspaces as V0_sRGB
4183 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00004184 case ui::Dataspace::SRGB:
4185 updatedDataspace = ui::Dataspace::V0_SRGB;
4186 break;
4187 case ui::Dataspace::SRGB_LINEAR:
4188 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4189 break;
4190 case ui::Dataspace::JFIF:
4191 updatedDataspace = ui::Dataspace::V0_JFIF;
4192 break;
4193 case ui::Dataspace::BT601_625:
4194 updatedDataspace = ui::Dataspace::V0_BT601_625;
4195 break;
4196 case ui::Dataspace::BT601_525:
4197 updatedDataspace = ui::Dataspace::V0_BT601_525;
4198 break;
4199 case ui::Dataspace::BT709:
4200 updatedDataspace = ui::Dataspace::V0_BT709;
4201 break;
4202 default:
4203 break;
4204 }
4205
4206 return updatedDataspace;
4207}
4208
4209sp<GraphicBuffer> Layer::getBuffer() const {
4210 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4211}
4212
Vishnu Nairb76d99a2023-03-19 18:22:31 -07004213void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4214 mTransformHintLegacy = getFixedTransformHint();
4215 if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4216 mTransformHintLegacy = displayTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004217 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004218 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004219}
4220
4221const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4222 return mBufferInfo.mBuffer;
4223}
4224
4225bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004226 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004227 return false;
4228 }
4229
4230 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004231 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004232 mDrawingState.modified = true;
4233 setTransactionFlags(eTransactionNeeded);
4234 return true;
4235}
4236
4237bool Layer::fillsColor() const {
4238 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4239 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4240}
4241
4242bool Layer::hasBlur() const {
4243 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4244}
4245
Vishnu Nairba354102022-08-01 00:14:18 +00004246void Layer::updateSnapshot(bool updateGeometry) {
4247 if (!getCompositionEngineLayerFE()) {
4248 return;
4249 }
4250
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004251 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004252 if (updateGeometry) {
4253 prepareBasicGeometryCompositionState();
4254 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004255 snapshot->roundedCorner = getRoundedCornerState();
4256 snapshot->stretchEffect = getStretchEffect();
4257 snapshot->transformedBounds = mScreenBounds;
4258 if (mEffectiveShadowRadius > 0.f) {
4259 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4260
4261 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4262 // it if transparent regions are present. This may not be necessary since shadows are
4263 // typically cast by layers without transparent regions.
4264 snapshot->shadowSettings.boundaries = mBounds;
4265
4266 const float casterAlpha = snapshot->alpha;
4267 const bool casterIsOpaque =
4268 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4269
4270 // If the casting layer is translucent, we need to fill in the shadow underneath the
4271 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4272 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4273 snapshot->shadowSettings.ambientColor *= casterAlpha;
4274 snapshot->shadowSettings.spotColor *= casterAlpha;
4275 }
4276 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004277 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004278 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004279 snapshot->layerOpaqueFlagSet =
4280 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004281 sp<Layer> p = mDrawingParent.promote();
4282 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004283 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004284 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004285 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004286 }
4287 snapshot->bufferSize = getBufferSize(mDrawingState);
4288 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004289 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004290 preparePerFrameCompositionState();
4291}
4292
Vishnu Naire14c6b32022-08-06 04:20:15 +00004293void Layer::updateChildrenSnapshots(bool updateGeometry) {
4294 for (const sp<Layer>& child : mDrawingChildren) {
4295 child->updateSnapshot(updateGeometry);
4296 child->updateChildrenSnapshots(updateGeometry);
4297 }
4298}
4299
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004300void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4301 mSnapshot->layerMetadata = parentMetadata;
4302 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4303 for (const sp<Layer>& child : mDrawingChildren) {
4304 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4305 }
4306}
4307
4308void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4309 std::unordered_set<Layer*>& visited) {
4310 if (visited.find(this) != visited.end()) {
4311 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4312 return;
4313 }
4314 visited.insert(this);
4315
4316 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4317
4318 if (mDrawingState.zOrderRelatives.empty()) {
4319 return;
4320 }
4321 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4322 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4323 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4324 sp<Layer> relative = weakRelative.promote();
4325 if (!relative) {
4326 continue;
4327 }
4328 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4329 }
4330}
4331
Chavi Weingarten328a8312023-01-26 21:17:52 +00004332bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004333 TrustedPresentationListener const& listener) {
4334 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4335 mTrustedPresentationListener = listener;
4336 mTrustedPresentationThresholds = thresholds;
4337 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4338 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4339 mFlinger->mNumTrustedPresentationListeners++;
4340 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4341 mFlinger->mNumTrustedPresentationListeners--;
4342 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004343
4344 // Reset trusted presentation states to ensure we start the time again.
4345 mEnteredTrustedPresentationStateTime = -1;
4346 mLastReportedTrustedPresentationState = false;
4347 mLastComputedTrustedPresentationState = false;
4348
4349 // If there's a new trusted presentation listener, the code needs to go through the composite
4350 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4351 // we're already in the requested state.
4352 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004353}
4354
Vishnu Naira156f482023-02-22 00:23:38 +00004355void Layer::updateLastLatchTime(nsecs_t latchTime) {
4356 mLastLatchTime = latchTime;
4357}
4358
Mathias Agopian13127d82013-03-05 17:47:11 -08004359// ---------------------------------------------------------------------------
4360
Marin Shalamanov46084422020-10-13 12:33:42 +02004361std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004362 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4363 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004364}
4365
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004366} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004367
4368#if defined(__gl_h_)
4369#error "don't include gl/gl.h in this file"
4370#endif
4371
4372#if defined(__gl2_h_)
4373#error "don't include gl2/gl2.h in this file"
4374#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004375
4376// TODO(b/129481165): remove the #pragma below and fix conversion issues
4377#pragma clang diagnostic pop // ignored "-Wconversion"