blob: 3406e924ab418e0f72278d8671bd91d37ef39ec7 [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),
152 mTextureName(args.textureName),
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000153 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000154 ALOGV("Creating Layer %s", getDebugName());
155
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700156 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700157 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
158 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
159 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700160 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
161 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700162 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700163 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700164 mDrawingState.z = 0;
165 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700166 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700167 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700168 mDrawingState.transform.set(0, 0);
169 mDrawingState.frameNumber = 0;
170 mDrawingState.bufferTransform = 0;
171 mDrawingState.transformToDisplayInverse = false;
172 mDrawingState.crop.makeInvalid();
173 mDrawingState.acquireFence = sp<Fence>::make(-1);
174 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
Alec Mouri74c7ae12023-03-26 02:57:47 +0000175 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Robert Carr6a160312021-05-17 12:08:20 -0700176 mDrawingState.hdrMetadata.validTypes = 0;
177 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
178 mDrawingState.cornerRadius = 0.0f;
179 mDrawingState.backgroundBlurRadius = 0;
180 mDrawingState.api = -1;
181 mDrawingState.hasColorTransform = false;
182 mDrawingState.colorSpaceAgnostic = false;
183 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
184 mDrawingState.metadata = args.metadata;
185 mDrawingState.shadowRadius = 0.f;
186 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
187 mDrawingState.frameTimelineInfo = {};
188 mDrawingState.postTime = -1;
189 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000190 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700191 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700192 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000193 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700194
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700195 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
196 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700197 mDrawingState.color.r = -1.0_hf;
198 mDrawingState.color.g = -1.0_hf;
199 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700200 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700201
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500202 mFrameTracker.setDisplayRefreshPeriod(
203 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700204
Vishnu Naircb8be502022-10-12 19:03:23 +0000205 mOwnerUid = args.ownerUid;
206 mOwnerPid = args.ownerPid;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000207
208 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
209 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
210 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000211
212 mSnapshot->sequence = sequence;
213 mSnapshot->name = getDebugName();
214 mSnapshot->textureName = mTextureName;
215 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000216 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800217}
218
219void Layer::onFirstRef() {
220 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700221}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700222
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700223Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000224 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
225 "Layer destructor called off the main thread.");
226
Patrick Williamsbb25f802022-08-30 23:02:34 +0000227 // The original layer and the clone layer share the same texture and buffer. Therefore, only
228 // one of the layers, in this case the original layer, needs to handle the deletion. The
229 // original layer and the clone should be removed at the same time so there shouldn't be any
230 // issue with the clone layer trying to use the texture.
231 if (mBufferInfo.mBuffer != nullptr) {
232 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
233 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800234 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000235 }
236 if (!isClone()) {
237 // The original layer and the clone layer share the same texture. Therefore, only one of
238 // the layers, in this case the original layer, needs to handle the deletion. The original
239 // layer and the clone should be removed at the same time so there shouldn't be any issue
240 // with the clone layer trying to use the deleted texture.
241 mFlinger->deleteTextureAsync(mTextureName);
242 }
243 const int32_t layerId = getSequence();
244 mFlinger->mTimeStats->onDestroy(layerId);
245 mFlinger->mFrameTracer->onDestroy(layerId);
246
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000247 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700248 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700249
250 if (mDrawingState.sidebandStream != nullptr) {
251 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
252 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700253 if (mHadClonedChild) {
254 mFlinger->mNumClones--;
255 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000256 if (hasTrustedPresentationListener()) {
257 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000258 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000259 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700260}
261
Mathias Agopian13127d82013-03-05 17:47:11 -0800262// ---------------------------------------------------------------------------
263// callbacks
264// ---------------------------------------------------------------------------
265
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700266void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700267 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700268 return;
269 }
Robert Carr2e102c92018-10-23 12:11:15 -0700270
Robert Carr6a160312021-05-17 12:08:20 -0700271 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700272 if (strongRelative == nullptr) {
273 setZOrderRelativeOf(nullptr);
274 return;
275 }
276
277 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700278 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700279 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800280 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700281 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700282}
283
284void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700285 if (!mRemovedFromDrawingState) {
286 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700287 mFlinger->mScheduler->deregisterLayer(this);
288 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000289 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000290
Ady Abrahamd11bade2022-08-01 16:18:03 -0700291 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700292}
Chia-I Wu38512252017-05-17 14:36:16 -0700293
chaviw68d4dab2020-06-08 15:07:32 -0700294sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000295 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700296 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700297 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700298 }
299 return parent->getRootLayer();
300}
301
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700302void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700303 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
304 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700305 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700306
Josh Gao194ff392022-09-08 16:19:29 -0700307 REQUIRE_MUTEX(mFlinger->mStateLock);
308 traverse(LayerVector::StateSet::Current,
309 [&](Layer* layer) REQUIRES(layer->mFlinger->mStateLock) {
310 layer->removeFromCurrentState();
311 layer->removeRelativeZ(layersInTree);
312 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700313}
314
chaviw61626f22018-11-15 16:26:27 -0800315void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700316 if (mRemovedFromDrawingState) {
317 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700318 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700319 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700320 }
chaviw61626f22018-11-15 16:26:27 -0800321
322 for (const auto& child : mCurrentChildren) {
323 child->addToCurrentState();
324 }
325}
326
Mathias Agopian13127d82013-03-05 17:47:11 -0800327// ---------------------------------------------------------------------------
328// set-up
329// ---------------------------------------------------------------------------
330
chaviw13fdc492017-06-27 12:40:18 -0700331bool Layer::getPremultipledAlpha() const {
332 return mPremultipliedAlpha;
333}
334
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700335sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800336 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700337 if (mGetHandleCalled) {
338 ALOGE("Get handle called twice" );
339 return nullptr;
340 }
341 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700342 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000343 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800344}
345
346// ---------------------------------------------------------------------------
347// h/w composer set-up
348// ---------------------------------------------------------------------------
349
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700350static Rect reduce(const Rect& win, const Region& exclude) {
351 if (CC_LIKELY(exclude.isEmpty())) {
352 return win;
353 }
354 if (exclude.isRect()) {
355 return win.reduce(exclude.getBounds());
356 }
357 return Region(win).subtract(exclude).getBounds();
358}
359
Dan Stoza80d61162017-12-20 15:57:52 -0800360static FloatRect reduce(const FloatRect& win, const Region& exclude) {
361 if (CC_LIKELY(exclude.isEmpty())) {
362 return win;
363 }
364 // Convert through Rect (by rounding) for lack of FloatRegion
365 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
366}
367
Vishnu Nair4351ad52019-02-11 14:13:02 -0800368Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800369 if (!reduceTransparentRegion) {
370 return Rect{mScreenBounds};
371 }
372
373 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800374 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800375 // Transform to screen space.
376 bounds = t.transform(bounds);
377 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700378}
379
Vishnu Nair4351ad52019-02-11 14:13:02 -0800380FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000381 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800382 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700383}
384
Vishnu Nairf0c28512019-02-08 12:40:28 -0800385FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
386 // Subtract the transparent region and snap to the bounds.
387 return reduce(mBounds, activeTransparentRegion);
388}
389
Chavi Weingarten076acac2023-01-19 17:20:43 +0000390// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000391void Layer::updateTrustedPresentationState(const DisplayDevice* display,
392 const frontend::LayerSnapshot* snapshot,
393 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000394 if (!hasTrustedPresentationListener()) {
395 return;
396 }
397 const bool lastState = mLastComputedTrustedPresentationState;
398 mLastComputedTrustedPresentationState = false;
399
400 if (!leaveState) {
401 const auto outputLayer = findOutputLayerForDisplay(display);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000402 if (outputLayer != nullptr) {
403 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
404 Region coveredRegion =
405 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
406 mLastComputedTrustedPresentationState =
407 computeTrustedPresentationState(snapshot->geomLayerBounds,
408 snapshot->sourceBounds(), coveredRegion,
409 snapshot->transformedBounds,
410 snapshot->alpha,
411 snapshot->geomLayerTransform,
412 mTrustedPresentationThresholds);
413 } else {
414 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
415 "TrustedPresentationState",
416 getDebugName());
417 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000418 }
419 }
420 const bool newState = mLastComputedTrustedPresentationState;
421 if (lastState && !newState) {
422 // We were in the trusted presentation state, but now we left it,
423 // emit the callback if needed
424 if (mLastReportedTrustedPresentationState) {
425 mLastReportedTrustedPresentationState = false;
426 mTrustedPresentationListener.invoke(false);
427 }
428 // Reset the timer
429 mEnteredTrustedPresentationStateTime = -1;
430 } else if (!lastState && newState) {
431 // We were not in the trusted presentation state, but we entered it, begin the timer
432 // and make sure this gets called at least once more!
433 mEnteredTrustedPresentationStateTime = time_in_ms;
434 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
435 }
436
437 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
438 if (!mLastReportedTrustedPresentationState && newState &&
439 (time_in_ms - mEnteredTrustedPresentationStateTime >
440 mTrustedPresentationThresholds.stabilityRequirementMs)) {
441 mLastReportedTrustedPresentationState = true;
442 mTrustedPresentationListener.invoke(true);
443 }
444}
445
446/**
447 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
448 * of how the parameters and thresholds are interpreted. The general spirit is
449 * to produce an upper bound on the amount of the buffer which was presented.
450 */
451bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
452 const Region& coveredRegion,
453 const FloatRect& screenBounds, float alpha,
454 const ui::Transform& effectiveTransform,
455 const TrustedPresentationThresholds& thresholds) {
456 if (alpha < thresholds.minAlpha) {
457 return false;
458 }
459 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
460 return false;
461 }
462 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
463 return false;
464 }
465
466 const float sx = effectiveTransform.dsdx();
467 const float sy = effectiveTransform.dsdy();
468 float fractionRendered = std::min(sx * sy, 1.0f);
469
470 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
471 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
472 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
473
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000474 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
475 // Compute the size of all the rects since they may be disconnected.
476 float coveredSize = 0;
477 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
478 float size = rect->width() * rect->height();
479 coveredSize += size;
480 }
481
482 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000483
484 if (fractionRendered < thresholds.minFractionRendered) {
485 return false;
486 }
487
488 return true;
489}
490
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700491void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
492 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800493 const State& s(getDrawingState());
494
495 // Calculate effective layer transform
496 mEffectiveTransform = parentTransform * getActiveTransform(s);
497
Garfield Tan2c1782c2022-02-16 15:25:05 -0800498 if (CC_UNLIKELY(!isTransformValid())) {
499 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
500 getDebugName());
501 return;
502 }
503
Vishnu Nair4351ad52019-02-11 14:13:02 -0800504 // Transform parent bounds to layer space
505 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
506
Vishnu Nairc652ff82019-03-15 12:48:54 -0700507 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800508 mSourceBounds = computeSourceBounds(parentBounds);
509
510 // Calculate bounds by croping diplay frame with layer crop and parent bounds
511 FloatRect bounds = mSourceBounds;
512 const Rect layerCrop = getCrop(s);
513 if (!layerCrop.isEmpty()) {
514 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
515 }
516 bounds = bounds.intersect(parentBounds);
517
518 mBounds = bounds;
519 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700520
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700521 // Use the layer's own shadow radius if set. Otherwise get the radius from
522 // parent.
523 if (s.shadowRadius > 0.f) {
524 mEffectiveShadowRadius = s.shadowRadius;
525 } else {
526 mEffectiveShadowRadius = parentShadowRadius;
527 }
528
529 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
530 // don't pass it to its children.
531 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
532
Vishnu Nair4351ad52019-02-11 14:13:02 -0800533 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700534 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800535 }
Vishnu Nairba354102022-08-01 00:14:18 +0000536
537 if (mPotentialCursor) {
538 prepareCursorCompositionState();
539 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800540}
541
Vishnu Nair60356342018-11-13 13:00:45 -0800542Rect Layer::getCroppedBufferSize(const State& s) const {
543 Rect size = getBufferSize(s);
544 Rect crop = getCrop(s);
545 if (!crop.isEmpty() && size.isValid()) {
546 size.intersect(crop, &size);
547 } else if (!crop.isEmpty()) {
548 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700549 }
Vishnu Nair60356342018-11-13 13:00:45 -0800550 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800551}
552
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700553void Layer::setupRoundedCornersCropCoordinates(Rect win,
554 const FloatRect& roundedCornersCrop) const {
555 // Translate win by the rounded corners rect coordinates, to have all values in
556 // layer coordinate space.
557 win.left -= roundedCornersCrop.left;
558 win.right -= roundedCornersCrop.left;
559 win.top -= roundedCornersCrop.top;
560 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700561}
562
Lloyd Piquede196652020-01-22 17:29:58 -0800563void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800564 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800565 const auto alpha = static_cast<float>(getAlpha());
566 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700567 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800568
569 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
570 if (!opaque || alpha != 1.0f) {
571 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
572 : Hwc2::IComposerClient::BlendMode::COVERAGE;
573 }
574
Alec Mourif4af03e2023-02-11 00:25:24 +0000575 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000576 auto* snapshot = editLayerSnapshot();
577 snapshot->outputFilter = getOutputFilter();
578 snapshot->isVisible = isVisible();
579 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
580 snapshot->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800581
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000582 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800583 contentDirty = false;
584
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000585 snapshot->geomLayerBounds = mBounds;
586 snapshot->geomLayerTransform = getTransform();
587 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
588 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000589 snapshot->localTransform = getActiveTransform(drawingState);
590 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000591 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
592 snapshot->alpha = alpha;
593 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
594 snapshot->blurRegions = drawingState.blurRegions;
595 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800596}
597
Lloyd Piquede196652020-01-22 17:29:58 -0800598void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800599 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000600 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700601
Alec Mourif4af03e2023-02-11 00:25:24 +0000602 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000603 snapshot->geomBufferSize = getBufferSize(drawingState);
604 snapshot->geomContentCrop = getBufferCrop();
605 snapshot->geomCrop = getCrop(drawingState);
606 snapshot->geomBufferTransform = getBufferTransform();
607 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
608 snapshot->geomUsesSourceCrop = usesSourceCrop();
609 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800610
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000611 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800612 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
613 for (const auto& [key, mandatory] : supportedMetadata) {
614 const auto& genericLayerMetadataCompatibilityMap =
615 mFlinger->getGenericLayerMetadataKeyMap();
616 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
617 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
618 continue;
619 }
620 const uint32_t id = compatIter->second;
621
622 auto it = drawingState.metadata.mMap.find(id);
623 if (it == std::end(drawingState.metadata.mMap)) {
624 continue;
625 }
626
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000627 snapshot->metadata.emplace(key,
628 compositionengine::GenericLayerMetadataEntry{mandatory,
629 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800630 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800631}
David Sodmanba340492018-08-05 21:51:33 -0700632
Lloyd Piquede196652020-01-22 17:29:58 -0800633void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800634 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000635 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000636 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800637
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000638 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800639
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000640 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
641 snapshot->dataspace = getDataSpace();
642 snapshot->colorTransform = getColorTransform();
643 snapshot->colorTransformIsIdentity = !hasColorTransform();
644 snapshot->surfaceDamage = surfaceDamageRegion;
645 snapshot->hasProtectedContent = isProtected();
646 snapshot->dimmingEnabled = isDimmingEnabled();
Sally Qi963049b2023-03-23 14:06:21 -0700647 snapshot->currentHdrSdrRatio = getCurrentHdrSdrRatio();
648 snapshot->desiredHdrSdrRatio = getDesiredHdrSdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000649 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800650
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700651 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700652
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000653 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800654
655 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400656 // Rounded corners no longer force client composition, since we may use a
657 // hole punch so that the layer will appear to have rounded corners.
658 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000659 snapshot->stretchEffect.hasEffect()) {
660 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800661 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700662 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000663 snapshot->blurRegions = drawingState.blurRegions;
664 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400665
666 // Layer framerate is used in caching decisions.
667 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
668 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000669 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000670
671 if (hasBufferOrSidebandStream()) {
672 preparePerFrameBufferCompositionState();
673 } else {
674 preparePerFrameEffectsCompositionState();
675 }
676}
677
678void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000679 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000680 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000681 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000682 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
683 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000684 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
685 return;
686 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000687 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000688 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800689 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
690 snapshot->compositionType =
691 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000692 } else {
693 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000694 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
695 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000696 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
697 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
698 }
699
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000700 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000701 snapshot->acquireFence = mBufferInfo.mFence;
702 snapshot->frameNumber = mBufferInfo.mFrameNumber;
703 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000704}
705
706void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000707 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000708 auto* snapshot = editLayerSnapshot();
709 snapshot->color = getColor();
710 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000711 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800712}
713
Lloyd Piquede196652020-01-22 17:29:58 -0800714void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800715 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000716 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000717 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800718
719 // Apply the layer's transform, followed by the display's global transform
720 // Here we're guaranteed that the layer's transform preserves rects
721 Rect win = getCroppedBufferSize(drawingState);
722 // Subtract the transparent region and snap to the bounds
723 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
724 Rect frame(getTransform().transform(bounds));
725
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000726 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800727}
728
Lloyd Piquea83776c2019-01-29 18:42:32 -0800729const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700730 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800731}
732
Mathias Agopian13127d82013-03-05 17:47:11 -0800733// ---------------------------------------------------------------------------
734// drawing...
735// ---------------------------------------------------------------------------
736
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500737aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
738 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700739 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800740 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500741 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800742 }
743 if (outputLayer->getState().hwc) {
744 return (*outputLayer->getState().hwc).hwcCompositionType;
745 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500746 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800747 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800748}
749
Mathias Agopian13127d82013-03-05 17:47:11 -0800750// ----------------------------------------------------------------------------
751// local state
752// ----------------------------------------------------------------------------
753
David Sodman41fdfc92017-11-06 16:09:56 -0800754bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800755 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700756 if (s.flags & layer_state_t::eLayerSecure) {
757 return true;
758 }
759
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000760 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700761 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700762}
763
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100764void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
765 std::vector<JankData>& jankData) {
766 if (mPendingJankClassifications.empty() ||
767 !mPendingJankClassifications.front()->getJankType()) {
768 return;
769 }
770
771 bool includeJankData = false;
772 for (const auto& handle : handles) {
773 for (const auto& cb : handle->callbackIds) {
774 if (cb.includeJankData) {
775 includeJankData = true;
776 break;
777 }
778 }
779
780 if (includeJankData) {
781 jankData.reserve(mPendingJankClassifications.size());
782 break;
783 }
784 }
785
786 while (!mPendingJankClassifications.empty() &&
787 mPendingJankClassifications.front()->getJankType()) {
788 if (includeJankData) {
789 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
790 mPendingJankClassifications.front();
791 jankData.emplace_back(
792 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
793 }
794 mPendingJankClassifications.pop_front();
795 }
796}
797
Mathias Agopian13127d82013-03-05 17:47:11 -0800798// ----------------------------------------------------------------------------
799// transaction
800// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800801
Vishnu Naira156f482023-02-22 00:23:38 +0000802uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700803 ATRACE_CALL();
804
Robert Carr0758e5d2021-03-11 22:15:04 -0800805 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700806 mDrawingStateModified = mDrawingState.modified;
807 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700808
Alec Mourib416efd2018-09-06 21:01:59 +0000809 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700810
Robert Carr6a160312021-05-17 12:08:20 -0700811 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800812 // invalidate and recompute the visible regions if needed
813 flags |= Layer::eVisibleRegion;
814 }
815
Robert Carr6a160312021-05-17 12:08:20 -0700816 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800817 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000818 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800819 flags |= eVisibleRegion;
820 this->contentDirty = true;
821
822 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700823 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800824 }
825
Arthur Hung9ed43392022-05-27 06:31:57 +0000826 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
827 mFlinger->mUpdateInputInfo = true;
828 }
829
Vishnu Naira156f482023-02-22 00:23:38 +0000830 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800831
Mathias Agopian13127d82013-03-05 17:47:11 -0800832 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800833}
834
Vishnu Naira156f482023-02-22 00:23:38 +0000835void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000836 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
837 // bufferSurfaceFrameTX will be presented in latchBuffer.
838 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
839 if (surfaceFrame->getPresentState() != PresentState::Presented) {
840 // With applyPendingStates, we could end up having presented surfaceframes from previous
841 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800842 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000843 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
844 }
845 }
Robert Carr6a160312021-05-17 12:08:20 -0700846 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700847}
848
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700849uint32_t Layer::clearTransactionFlags(uint32_t mask) {
850 const auto flags = mTransactionFlags & mask;
851 mTransactionFlags &= ~mask;
852 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800853}
854
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700855void Layer::setTransactionFlags(uint32_t mask) {
856 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800857}
858
Robert Carr1f0a16a2016-10-24 16:27:39 -0700859bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
860 ssize_t idx = mCurrentChildren.indexOf(childLayer);
861 if (idx < 0) {
862 return false;
863 }
864 if (childLayer->setLayer(z)) {
865 mCurrentChildren.removeAt(idx);
866 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800867 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700868 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800869 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700870}
871
Robert Carr503c7042017-09-27 15:06:08 -0700872bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
873 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
874 ssize_t idx = mCurrentChildren.indexOf(childLayer);
875 if (idx < 0) {
876 return false;
877 }
878 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
879 mCurrentChildren.removeAt(idx);
880 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800881 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700882 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800883 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700884}
885
Robert Carrae060832016-11-28 10:51:00 -0800886bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700887 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
888 mDrawingState.sequence++;
889 mDrawingState.z = z;
890 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700891
Robert Carra70e91c2021-06-11 13:59:52 -0700892 mFlinger->mSomeChildrenChanged = true;
893
Robert Carrdb66e622017-04-10 16:55:57 -0700894 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700895 if (mDrawingState.zOrderRelativeOf != nullptr) {
896 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700897 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700898 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700899 }
chaviw606e5cf2019-03-01 10:12:10 -0800900 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700901 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800902 setTransactionFlags(eTransactionNeeded);
903 return true;
904}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700905
Robert Carrdb66e622017-04-10 16:55:57 -0700906void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700907 mDrawingState.zOrderRelatives.remove(relative);
908 mDrawingState.sequence++;
909 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700910 setTransactionFlags(eTransactionNeeded);
911}
912
913void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700914 mDrawingState.zOrderRelatives.add(relative);
915 mDrawingState.modified = true;
916 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700917 setTransactionFlags(eTransactionNeeded);
918}
919
chaviw606e5cf2019-03-01 10:12:10 -0800920void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700921 mDrawingState.zOrderRelativeOf = relativeOf;
922 mDrawingState.sequence++;
923 mDrawingState.modified = true;
924 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700925
chaviw606e5cf2019-03-01 10:12:10 -0800926 setTransactionFlags(eTransactionNeeded);
927}
928
Robert Carr503d2bd2017-12-04 15:49:47 -0800929bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000930 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700931 if (relative == nullptr) {
932 return false;
933 }
934
Robert Carr6a160312021-05-17 12:08:20 -0700935 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
936 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800937 return false;
938 }
939
Robert Carr88b85e12022-03-21 15:47:35 -0700940 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
941 (relative->mDrawingState.zOrderRelativeOf == this)) {
942 ALOGE("Detected relative layer loop between %s and %s",
943 mName.c_str(), relative->mName.c_str());
944 ALOGE("Ignoring new call to set relative layer");
945 return false;
946 }
947
Robert Carra70e91c2021-06-11 13:59:52 -0700948 mFlinger->mSomeChildrenChanged = true;
949
Robert Carr6a160312021-05-17 12:08:20 -0700950 mDrawingState.sequence++;
951 mDrawingState.modified = true;
952 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700953
Robert Carr6a160312021-05-17 12:08:20 -0700954 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700955 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700956 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700957 }
chaviw606e5cf2019-03-01 10:12:10 -0800958 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700959 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700960
961 setTransactionFlags(eTransactionNeeded);
962
963 return true;
964}
965
Winson Chunga30f7c92021-06-29 15:42:56 -0700966bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
967 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
968 mDrawingState.isTrustedOverlay = isTrustedOverlay;
969 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000970 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700971 setTransactionFlags(eTransactionNeeded);
972 return true;
973}
974
975bool Layer::isTrustedOverlay() const {
976 if (getDrawingState().isTrustedOverlay) {
977 return true;
978 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000979 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700980 return (p != nullptr) && p->isTrustedOverlay();
981}
982
Dan Stoza9e56aa02015-11-02 13:00:03 -0800983bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700984 if (mDrawingState.color.a == alpha) return false;
985 mDrawingState.sequence++;
986 mDrawingState.color.a = alpha;
987 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800988 setTransactionFlags(eTransactionNeeded);
989 return true;
990}
chaviw13fdc492017-06-27 12:40:18 -0700991
Valerie Haudd0b7572019-01-29 14:59:27 -0800992bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700993 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700994 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800995 }
Robert Carr6a160312021-05-17 12:08:20 -0700996 mDrawingState.sequence++;
997 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800998 setTransactionFlags(eTransactionNeeded);
999
Robert Carr6a160312021-05-17 12:08:20 -07001000 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001001 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001002 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001003 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001004 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08001005 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001006 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001007
Valerie Haudd0b7572019-01-29 14:59:27 -08001008 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001009 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001010 mFlinger->mLayersAdded = true;
1011 // set up SF to handle added color layer
1012 if (isRemovedFromCurrentState()) {
Josh Gao194ff392022-09-08 16:19:29 -07001013 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001014 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001015 }
1016 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001017 } else if (mDrawingState.bgColorLayer && alpha == 0) {
Josh Gao194ff392022-09-08 16:19:29 -07001018 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001019 mDrawingState.bgColorLayer->reparent(nullptr);
1020 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001021 return true;
1022 }
1023
Robert Carr6a160312021-05-17 12:08:20 -07001024 mDrawingState.bgColorLayer->setColor(color);
1025 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1026 mDrawingState.bgColorLayer->setAlpha(alpha);
1027 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001028
chaviw13fdc492017-06-27 12:40:18 -07001029 return true;
1030}
1031
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001032bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001033 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001034
Robert Carr6a160312021-05-17 12:08:20 -07001035 mDrawingState.sequence++;
1036 mDrawingState.cornerRadius = cornerRadius;
1037 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001038 setTransactionFlags(eTransactionNeeded);
1039 return true;
1040}
1041
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001042bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001043 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001044 // If we start or stop drawing blur then the layer's visibility state may change so increment
1045 // the magic sequence number.
1046 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1047 mDrawingState.sequence++;
1048 }
Robert Carr6a160312021-05-17 12:08:20 -07001049 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1050 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001051 setTransactionFlags(eTransactionNeeded);
1052 return true;
1053}
Marissa Wall61c58622018-07-18 10:12:20 -07001054
Mathias Agopian13127d82013-03-05 17:47:11 -08001055bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001056 mDrawingState.sequence++;
1057 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001058 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001059 setTransactionFlags(eTransactionNeeded);
1060 return true;
1061}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001062
Lucas Dupinc3800b82020-10-02 16:24:48 -07001063bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001064 // If we start or stop drawing blur then the layer's visibility state may change so increment
1065 // the magic sequence number.
1066 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1067 mDrawingState.sequence++;
1068 }
Robert Carr6a160312021-05-17 12:08:20 -07001069 mDrawingState.blurRegions = blurRegions;
1070 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001071 setTransactionFlags(eTransactionNeeded);
1072 return true;
1073}
1074
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001075bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001076 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1077 if (mDrawingState.flags == newFlags) return false;
1078 mDrawingState.sequence++;
1079 mDrawingState.flags = newFlags;
1080 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001081 setTransactionFlags(eTransactionNeeded);
1082 return true;
1083}
Robert Carr99e27f02016-06-16 15:18:02 -07001084
chaviw25714502021-02-11 10:01:08 -08001085bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001086 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001087 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001088 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001089
Robert Carr6a160312021-05-17 12:08:20 -07001090 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001091 setTransactionFlags(eTransactionNeeded);
1092 return true;
1093}
Robert Carr8d5227b2017-03-16 15:41:03 -07001094
Evan Roskyef876c92019-01-25 17:46:06 -08001095bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001096 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1097 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001098 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001099 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001100}
1101
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001102bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001103 if (mDrawingState.layerStack == layerStack) return false;
1104 mDrawingState.sequence++;
1105 mDrawingState.layerStack = layerStack;
1106 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001107 setTransactionFlags(eTransactionNeeded);
1108 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001109}
1110
Peiyong Linc502cb72019-03-01 15:00:23 -08001111bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001112 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001113 return false;
1114 }
Robert Carr6a160312021-05-17 12:08:20 -07001115 mDrawingState.sequence++;
1116 mDrawingState.colorSpaceAgnostic = agnostic;
1117 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001118 setTransactionFlags(eTransactionNeeded);
1119 return true;
1120}
1121
Sally Qi81d95e62022-03-21 19:41:33 -07001122bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1123 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1124
1125 mDrawingState.sequence++;
1126 mDrawingState.dimmingEnabled = dimmingEnabled;
1127 mDrawingState.modified = true;
1128 setTransactionFlags(eTransactionNeeded);
1129 return true;
1130}
1131
Ana Krulecc84d09b2019-11-02 23:10:29 +01001132bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001133 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1134 mDrawingState.frameRateSelectionPriority = priority;
1135 mDrawingState.sequence++;
1136 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001137 setTransactionFlags(eTransactionNeeded);
1138 return true;
1139}
1140
1141int32_t Layer::getFrameRateSelectionPriority() const {
1142 // Check if layer has priority set.
1143 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1144 return mDrawingState.frameRateSelectionPriority;
1145 }
1146 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001147 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001148 if (parent != nullptr) {
1149 return parent->getFrameRateSelectionPriority();
1150 }
1151
1152 return Layer::PRIORITY_UNSET;
1153}
1154
Andy Labrada096227e2022-06-15 16:58:11 +00001155bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1156 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1157 mDrawingState.defaultFrameRateCompatibility = compatibility;
1158 mDrawingState.modified = true;
1159 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1160 setTransactionFlags(eTransactionNeeded);
1161 return true;
1162}
1163
1164scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1165 return mDrawingState.defaultFrameRateCompatibility;
1166}
1167
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001168bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1169 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1170};
1171
Vishnu Nair73908d12022-10-24 21:46:42 -07001172ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1173 bool useDrawing = state == LayerVector::StateSet::Drawing;
1174 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1175 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001176 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001177 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001178 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001179}
1180
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001181bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001182 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001183 return false;
1184 }
1185
Robert Carr6a160312021-05-17 12:08:20 -07001186 mDrawingState.sequence++;
1187 mDrawingState.shadowRadius = shadowRadius;
1188 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001189 setTransactionFlags(eTransactionNeeded);
1190 return true;
1191}
1192
Vishnu Nair6213bd92020-05-08 17:42:25 -07001193bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001194 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001195 return false;
1196 }
1197
Robert Carr6a160312021-05-17 12:08:20 -07001198 mDrawingState.sequence++;
1199 mDrawingState.fixedTransformHint = fixedTransformHint;
1200 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001201 setTransactionFlags(eTransactionNeeded);
1202 return true;
1203}
1204
John Reckcdb4ed72021-02-04 13:39:33 -05001205bool Layer::setStretchEffect(const StretchEffect& effect) {
1206 StretchEffect temp = effect;
1207 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001208 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001209 return false;
1210 }
Robert Carr6a160312021-05-17 12:08:20 -07001211 mDrawingState.sequence++;
1212 mDrawingState.stretchEffect = temp;
1213 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001214 setTransactionFlags(eTransactionNeeded);
1215 return true;
1216}
1217
John Reckc00c6692021-02-16 11:37:33 -05001218StretchEffect Layer::getStretchEffect() const {
1219 if (mDrawingState.stretchEffect.hasEffect()) {
1220 return mDrawingState.stretchEffect;
1221 }
1222
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001223 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001224 if (parent != nullptr) {
1225 auto effect = parent->getStretchEffect();
1226 if (effect.hasEffect()) {
1227 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1228 return effect;
1229 }
1230 }
1231 return StretchEffect{};
1232}
1233
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001234bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1235 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001236 return false;
1237 }
1238 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001239 mBorderWidth = width;
1240 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001241 return true;
1242}
1243
1244bool Layer::isBorderEnabled() {
1245 return mBorderEnabled;
1246}
1247
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001248float Layer::getBorderWidth() {
1249 return mBorderWidth;
1250}
1251
1252const half4& Layer::getBorderColor() {
1253 return mBorderColor;
1254}
1255
Ady Abrahama850c182021-08-04 13:04:37 -07001256bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1257 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1258 const auto frameRate = [&] {
1259 if (mDrawingState.frameRate.rate.isValid() ||
1260 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1261 return mDrawingState.frameRate;
1262 }
1263
1264 return parentFrameRate;
1265 }();
1266
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001267 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001268
1269 // The frame rate is propagated to the children
1270 bool childrenHaveFrameRate = false;
1271 for (const sp<Layer>& child : mCurrentChildren) {
1272 childrenHaveFrameRate |=
1273 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1274 }
1275
1276 // If we don't have a valid frame rate, but the children do, we set this
1277 // layer as NoVote to allow the children to control the refresh rate
1278 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1279 childrenHaveFrameRate) {
1280 *transactionNeeded |=
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001281 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001282 }
1283
1284 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1285 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001286 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001287 const auto layerVotedWithDefaultCompatibility =
1288 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1289 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1290 const auto layerVotedWithExactCompatibility =
1291 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1292 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1293 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1294}
1295
Ady Abraham60e42ea2020-03-09 19:17:31 -07001296void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001297 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001298 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001299 while (auto parent = layer->getParent()) {
1300 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001301 }
Ady Abrahama850c182021-08-04 13:04:37 -07001302 return layer;
1303 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001304
Ady Abraham60e42ea2020-03-09 19:17:31 -07001305 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001306 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001307
Ady Abrahama850c182021-08-04 13:04:37 -07001308 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001309 if (transactionNeeded) {
1310 mFlinger->setTransactionFlags(eTraversalNeeded);
1311 }
1312}
1313
Ady Abraham71c437d2020-01-31 15:56:57 -08001314bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001315 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001316 return false;
1317 }
1318
Robert Carr6a160312021-05-17 12:08:20 -07001319 mDrawingState.sequence++;
1320 mDrawingState.frameRate = frameRate;
1321 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001322
1323 updateTreeHasFrameRateVote();
1324
Steven Thomas3172e202020-01-06 19:25:30 -08001325 setTransactionFlags(eTransactionNeeded);
1326 return true;
1327}
1328
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001329void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1330 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001331 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001332
1333 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1334 // there are two transactions with the same token, the first one without a buffer and the
1335 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1336 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001337 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1338 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001339 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001340 mDrawingState.bufferSurfaceFrameTX = it->second;
1341 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1342 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1343 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001344 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001345 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001346 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1347 }
1348}
1349
1350void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1351 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001352 mDrawingState.frameTimelineInfo = info;
1353 mDrawingState.postTime = postTime;
1354 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001355 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001356
Robert Carr6a160312021-05-17 12:08:20 -07001357 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001358 bufferSurfaceFrameTX != nullptr) {
1359 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1360 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1361 // being used for BufferSurfaceFrame, don't create a new one.
1362 return;
1363 }
1364 }
1365 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1366 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1367 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001368 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1369 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001370 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001371 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001372 } else {
1373 if (it->second->getPresentState() == PresentState::Presented) {
1374 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1375 // have been from previous vsync.
1376 it->second = createSurfaceFrameForTransaction(info, postTime);
1377 }
1378 }
1379}
1380
1381void Layer::addSurfaceFrameDroppedForBuffer(
1382 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001383 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001384 surfaceFrame->setPresentState(PresentState::Dropped);
1385 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1386}
1387
1388void Layer::addSurfaceFramePresentedForBuffer(
1389 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1390 nsecs_t currentLatchTime) {
1391 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1392 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1393 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001394 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001395}
1396
1397std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1398 const FrameTimelineInfo& info, nsecs_t postTime) {
1399 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001400 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1401 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001402 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001403 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001404 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001405 // For Transactions, the post time is considered to be both queue and acquire fence time.
1406 surfaceFrame->setActualQueueTime(postTime);
1407 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001408 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1409 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001410 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001411 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001412 onSurfaceFrameCreated(surfaceFrame);
1413 return surfaceFrame;
1414}
1415
1416std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1417 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1418 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001419 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001420 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001421 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001422 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001423 // For buffers, acquire fence time will set during latch.
1424 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001425 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1426 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001427 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001428 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001429 onSurfaceFrameCreated(surfaceFrame);
1430 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001431}
1432
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001433bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001434 if (mDrawingState.frameRateForLayerTree == frameRate) {
1435 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001436 }
1437
Ady Abrahama850c182021-08-04 13:04:37 -07001438 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001439
Ady Abrahama850c182021-08-04 13:04:37 -07001440 // TODO(b/195668952): we probably don't need to dirty visible regions here
1441 // or even store frameRateForLayerTree in mDrawingState
1442 mDrawingState.sequence++;
1443 mDrawingState.modified = true;
1444 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001445
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001446 mFlinger->mScheduler
1447 ->recordLayerHistory(sequence, getLayerProps(), systemTime(),
1448 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1449 return true;
1450}
Ady Abrahama850c182021-08-04 13:04:37 -07001451
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001452bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps) {
1453 if (mDrawingState.frameRateForLayerTree == frameRate) {
1454 return false;
1455 }
1456
1457 mDrawingState.frameRateForLayerTree = frameRate;
1458 mFlinger->mScheduler
1459 ->recordLayerHistory(sequence, layerProps, systemTime(),
1460 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001461 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001462}
1463
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001464Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1465 return getDrawingState().frameRateForLayerTree;
1466}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001467
Robert Carr1f0a16a2016-10-24 16:27:39 -07001468bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001469 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001470 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001471 if (parent != nullptr && parent->isHiddenByPolicy()) {
1472 return true;
1473 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001474 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1475 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1476 if (zOrderRelativeOf != nullptr) {
1477 if (zOrderRelativeOf->isHiddenByPolicy()) {
1478 return true;
1479 }
1480 }
1481 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001482 if (CC_UNLIKELY(!isTransformValid())) {
1483 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1484 return true;
1485 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001486 return s.flags & layer_state_t::eLayerHidden;
1487}
1488
David Sodman41fdfc92017-11-06 16:09:56 -08001489uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001490 // TODO: should we do something special if mSecure is set?
1491 if (mProtectedByApp) {
1492 // need a hardware-protected path to external video sink
1493 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001494 }
Riley Andrews03414a12014-07-01 14:22:59 -07001495 if (mPotentialCursor) {
1496 usage |= GraphicBuffer::USAGE_CURSOR;
1497 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001498 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001499 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001500}
1501
Vishnu Nair71fcf912022-10-18 09:14:20 -07001502void Layer::skipReportingTransformHint() {
1503 mSkipReportingTransformHint = true;
1504}
1505
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001506void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1507 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1508 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001509 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001510
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001511 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001512}
1513
Mathias Agopian13127d82013-03-05 17:47:11 -08001514// ----------------------------------------------------------------------------
1515// debugging
1516// ----------------------------------------------------------------------------
1517
Marissa Wall61c58622018-07-18 10:12:20 -07001518// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001519gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001520 using namespace std::string_literals;
1521
Huihong Luo05539a12022-02-23 10:29:40 -08001522 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001523 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001524 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001525 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001526 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001527 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001528
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001529 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001530 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001531 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001532 info.mX = ds.transform.tx();
1533 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001534 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001535 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001536 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001537 info.mFlags = ds.flags;
1538 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001539 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001540 info.mMatrix[0][0] = ds.transform[0][0];
1541 info.mMatrix[0][1] = ds.transform[0][1];
1542 info.mMatrix[1][0] = ds.transform[1][0];
1543 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001544 {
chaviwd62d3062019-09-04 14:48:02 -07001545 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001546 if (buffer != 0) {
1547 info.mActiveBufferWidth = buffer->getWidth();
1548 info.mActiveBufferHeight = buffer->getHeight();
1549 info.mActiveBufferStride = buffer->getStride();
1550 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001551 } else {
1552 info.mActiveBufferWidth = 0;
1553 info.mActiveBufferHeight = 0;
1554 info.mActiveBufferStride = 0;
1555 info.mActiveBufferFormat = 0;
1556 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001557 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001558 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001559 info.mIsOpaque = isOpaque(ds);
1560 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001561 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001562 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001563}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001564
Yiwei Zhang5434a782018-12-05 18:06:32 -08001565void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001566 result.append(kDumpTableRowLength, '-');
1567 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001568 result.append(" Layer name\n");
1569 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001570 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001571 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001572 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001573 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001574 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001575 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1576 result.append(kDumpTableRowLength, '-');
1577 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001578}
1579
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001580void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1581 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001582 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001583 return;
1584 }
1585
Yiwei Zhang5434a782018-12-05 18:06:32 -08001586 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001587 if (mName.length() > 77) {
1588 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001589 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001590 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001591 shortened.append(mName, mName.length() - 36);
1592 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001593 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001594 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001595 }
1596
Yiwei Zhang5434a782018-12-05 18:06:32 -08001597 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001598
Alec Mourib416efd2018-09-06 21:01:59 +00001599 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001600 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001601
Chia-I Wu1e043612018-03-01 09:45:09 -08001602 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001603 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001604 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001605 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001606 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001607 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001608 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001609 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1610 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001611 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001612 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001613 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001614 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001615 const auto frameRate = getFrameRateForLayerTree();
1616 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1617 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001618 ftl::enum_string(frameRate.type).c_str(),
1619 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001620 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001621 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001622 }
Dan Stozae22aec72016-08-01 13:20:59 -07001623
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001624 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1625 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1626
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001627 result.append(kDumpTableRowLength, '-');
1628 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001629}
Dan Stozae22aec72016-08-01 13:20:59 -07001630
Yiwei Zhang5434a782018-12-05 18:06:32 -08001631void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001632 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001633}
1634
Svetoslavd85084b2014-03-20 10:28:31 -07001635void Layer::clearFrameStats() {
1636 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001637}
1638
Jamie Gennis6547ff42013-07-16 20:12:42 -07001639void Layer::logFrameStats() {
1640 mFrameTracker.logAndResetStats(mName);
1641}
1642
Svetoslavd85084b2014-03-20 10:28:31 -07001643void Layer::getFrameStats(FrameStats* outStats) const {
1644 mFrameTracker.getStats(outStats);
1645}
1646
Vishnu Nair76554eb2022-12-09 03:38:36 +00001647void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1648 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
1649 StringAppendF(&result, "Layer %s%s pid:%d uid:%d\n", getName().c_str(), hasBuffer.c_str(),
Vishnu Naircb8be502022-10-12 19:03:23 +00001650 mOwnerPid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001651}
1652
Brian Anderson5ea5e592016-12-01 16:54:33 -08001653void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001654 const int32_t layerId = getSequence();
1655 mFlinger->mTimeStats->onDestroy(layerId);
1656 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001657}
1658
Vishnu Nair787aa782023-03-17 13:46:46 -07001659size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001660 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001661 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001662 count += 1 + child->getChildrenCount();
1663 }
1664 return count;
1665}
1666
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001667void Layer::setGameModeForTree(GameMode gameMode) {
1668 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001669 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1670 gameMode =
1671 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001672 }
1673 setGameMode(gameMode);
1674 for (const sp<Layer>& child : mCurrentChildren) {
1675 child->setGameModeForTree(gameMode);
1676 }
1677}
1678
Robert Carr1f0a16a2016-10-24 16:27:39 -07001679void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001680 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001681 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001682
Robert Carr1f0a16a2016-10-24 16:27:39 -07001683 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001684 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001685 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001686 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001687}
1688
1689ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001690 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001691 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001692
Robert Carr1323c952019-01-28 18:13:27 -08001693 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001694 const auto removeResult = mCurrentChildren.remove(layer);
1695
1696 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001697 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001698 layer->updateTreeHasFrameRateVote();
1699
1700 return removeResult;
1701}
1702
Robert Carr15eae092018-03-23 13:43:53 -07001703void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001704 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001705 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001706 const float parentShadowRadius =
1707 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001708 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001709 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001710 }
1711}
1712
chaviwf1961f72017-09-18 16:41:07 -07001713bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001714 sp<Layer> newParent;
1715 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001716 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001717 if (newParent == nullptr) {
1718 ALOGE("Unable to promote Layer handle");
1719 return false;
1720 }
1721 if (newParent == this) {
1722 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1723 return false;
1724 }
1725 }
1726
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001727 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001728 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001729 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001730 }
1731
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001732 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001733 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001734 if (!newParent->isRemovedFromCurrentState()) {
1735 addToCurrentState();
1736 } else {
1737 onRemovedFromCurrentState();
1738 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001739 } else {
1740 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001741 }
1742
chaviw06178942017-07-27 10:25:59 -07001743 return true;
1744}
1745
Peiyong Lind3788632018-09-18 16:01:31 -07001746bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001747 static const mat4 identityMatrix = mat4();
1748
Robert Carr6a160312021-05-17 12:08:20 -07001749 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001750 return false;
1751 }
Robert Carr6a160312021-05-17 12:08:20 -07001752 ++mDrawingState.sequence;
1753 mDrawingState.colorTransform = matrix;
1754 mDrawingState.hasColorTransform = matrix != identityMatrix;
1755 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001756 setTransactionFlags(eTransactionNeeded);
1757 return true;
1758}
1759
chaviwf66724d2018-11-28 16:35:21 -08001760mat4 Layer::getColorTransform() const {
1761 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001762 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001763 colorTransform = parent->getColorTransform() * colorTransform;
1764 }
1765 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001766}
1767
1768bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001769 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001770 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001771 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1772 }
1773 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001774}
1775
Chia-I Wu11481472018-05-04 10:43:19 -07001776bool Layer::isLegacyDataSpace() const {
1777 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001778 return !(getDataSpace() &
1779 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1780 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001781}
1782
Robert Carr1f0a16a2016-10-24 16:27:39 -07001783void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001784 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001785}
1786
Robert Carr6a160312021-05-17 12:08:20 -07001787int32_t Layer::getZ(LayerVector::StateSet) const {
1788 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001789}
1790
Robert Carr1c5481e2019-07-01 14:42:27 -07001791bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001792 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001793 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001794 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001795}
1796
David Sodman41fdfc92017-11-06 16:09:56 -08001797__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001798 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001799 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1800 "makeTraversalList received invalid stateSet");
1801 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1802 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001803 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001804
Robert Carr29abff82017-12-04 13:51:20 -08001805 if (state.zOrderRelatives.size() == 0) {
1806 *outSkipRelativeZUsers = true;
1807 return children;
1808 }
1809
chaviwfd462612018-05-31 16:11:27 -07001810 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001811 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001812 sp<Layer> strongRelative = weakRelative.promote();
1813 if (strongRelative != nullptr) {
1814 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001815 }
1816 }
1817
Dan Stoza412903f2017-04-27 13:42:17 -07001818 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001819 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001820 continue;
1821 }
Robert Carrdb66e622017-04-10 16:55:57 -07001822 traverse.add(child);
1823 }
1824
1825 return traverse;
1826}
1827
Robert Carr1f0a16a2016-10-24 16:27:39 -07001828/**
Robert Carrdb66e622017-04-10 16:55:57 -07001829 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001830 */
Dan Stoza412903f2017-04-27 13:42:17 -07001831void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001832 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1833 // produce a new list for traversing, including our relatives, and not including our children
1834 // who are relatives of another surface. In the case that there are no relative Z,
1835 // makeTraversalList returns our children directly to avoid significant overhead.
1836 // However in this case we need to take the responsibility for filtering children which
1837 // are relatives of another surface here.
1838 bool skipRelativeZUsers = false;
1839 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001840
Robert Carr1f0a16a2016-10-24 16:27:39 -07001841 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001842 for (; i < list.size(); i++) {
1843 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001844 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1845 continue;
1846 }
1847
chaviw301b1d82019-11-06 13:15:09 -08001848 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001849 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001850 }
Dan Stoza412903f2017-04-27 13:42:17 -07001851 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001852 }
Robert Carr29abff82017-12-04 13:51:20 -08001853
Dan Stoza412903f2017-04-27 13:42:17 -07001854 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001855 for (; i < list.size(); i++) {
1856 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001857
Robert Carr29abff82017-12-04 13:51:20 -08001858 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1859 continue;
1860 }
Dan Stoza412903f2017-04-27 13:42:17 -07001861 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001862 }
1863}
1864
1865/**
Robert Carrdb66e622017-04-10 16:55:57 -07001866 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001867 */
Dan Stoza412903f2017-04-27 13:42:17 -07001868void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1869 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001870 // See traverseInZOrder for documentation.
1871 bool skipRelativeZUsers = false;
1872 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001873
Robert Carr1f0a16a2016-10-24 16:27:39 -07001874 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001875 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001876 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001877
1878 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1879 continue;
1880 }
1881
chaviw301b1d82019-11-06 13:15:09 -08001882 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001883 break;
1884 }
Dan Stoza412903f2017-04-27 13:42:17 -07001885 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001886 }
Dan Stoza412903f2017-04-27 13:42:17 -07001887 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001888 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001889 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001890
1891 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1892 continue;
1893 }
1894
Dan Stoza412903f2017-04-27 13:42:17 -07001895 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001896 }
1897}
1898
Edgar Arriaga844fa672020-01-16 14:21:42 -08001899void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1900 visitor(this);
1901 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001902 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001903 for (const sp<Layer>& child : children) {
1904 child->traverse(state, visitor);
1905 }
1906}
1907
Vishnu Nair787aa782023-03-17 13:46:46 -07001908void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
1909 for (const sp<Layer>& child : mDrawingChildren) {
1910 visitor(child.get());
1911 }
1912}
1913
chaviw4b129c22018-04-09 16:19:43 -07001914LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1915 const std::vector<Layer*>& layersInTree) {
1916 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1917 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001918 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1919 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001920 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001921
chaviwfd462612018-05-31 16:11:27 -07001922 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001923 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1924 sp<Layer> strongRelative = weakRelative.promote();
1925 // Only add relative layers that are also descendents of the top most parent of the tree.
1926 // If a relative layer is not a descendent, then it should be ignored.
1927 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1928 traverse.add(strongRelative);
1929 }
1930 }
1931
1932 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001933 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001934 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1935 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1936 // the child here since it won't be added later as a relative.
1937 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1938 childState.zOrderRelativeOf.promote().get())) {
1939 continue;
1940 }
1941 traverse.add(child);
1942 }
1943
1944 return traverse;
1945}
1946
1947void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1948 LayerVector::StateSet stateSet,
1949 const LayerVector::Visitor& visitor) {
1950 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001951
1952 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001953 for (; i < list.size(); i++) {
1954 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001955 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001956 break;
1957 }
chaviw4b129c22018-04-09 16:19:43 -07001958 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001959 }
chaviw4b129c22018-04-09 16:19:43 -07001960
chaviwa76b2712017-09-20 12:02:26 -07001961 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001962 for (; i < list.size(); i++) {
1963 const auto& relative = list[i];
1964 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001965 }
1966}
1967
chaviw4b129c22018-04-09 16:19:43 -07001968std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1969 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1970 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1971
1972 std::vector<Layer*> layersInTree = {this};
1973 for (size_t i = 0; i < children.size(); i++) {
1974 const auto& child = children[i];
1975 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1976 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1977 }
1978
1979 return layersInTree;
1980}
1981
1982void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1983 const LayerVector::Visitor& visitor) {
1984 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1985 std::sort(layersInTree.begin(), layersInTree.end());
1986 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1987}
1988
Peiyong Linefefaac2018-08-17 12:27:51 -07001989ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001990 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001991}
1992
Garfield Tan2c1782c2022-02-16 15:25:05 -08001993bool Layer::isTransformValid() const {
1994 float transformDet = getTransform().det();
1995 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1996}
1997
chaviw13fdc492017-06-27 12:40:18 -07001998half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001999 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002000
chaviw13fdc492017-06-27 12:40:18 -07002001 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2002 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002003}
Robert Carr6452f122017-03-21 10:41:29 -07002004
Vishnu Nair6213bd92020-05-08 17:42:25 -07002005ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002006 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002007 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2008 return fixedTransformHint;
2009 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002010 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002011 if (!p) return fixedTransformHint;
2012 return p->getFixedTransformHint();
2013}
2014
chaviw13fdc492017-06-27 12:40:18 -07002015half4 Layer::getColor() const {
2016 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002017 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002018}
Robert Carr6452f122017-03-21 10:41:29 -07002019
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002020int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002021 if (getDrawingState().backgroundBlurRadius == 0) {
2022 return 0;
2023 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002024
Vishnu Nair29810f72022-07-01 16:38:41 +00002025 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002026 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2027 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002028}
2029
Galia Peychevae0acf382021-04-12 21:22:34 +02002030const std::vector<BlurRegion> Layer::getBlurRegions() const {
2031 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002032 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002033 for (auto& region : regionsCopy) {
2034 region.alpha = region.alpha * layerAlpha;
2035 }
2036 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002037}
2038
Vishnu Naire14c6b32022-08-06 04:20:15 +00002039RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002040 // Get parent settings
2041 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002042 const auto& parent = mDrawingParent.promote();
2043 if (parent != nullptr) {
2044 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002045 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002046 ui::Transform t = getActiveTransform(getDrawingState());
2047 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002048 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002049 parentSettings.radius.x *= t.getScaleX();
2050 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002051 }
2052 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002053
2054 // Get layer settings
2055 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002056 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002057 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002058 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002059
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002060 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002061 // If the parent and the layer have rounded corner settings, use the parent settings if the
2062 // parent crop is entirely inside the layer crop.
2063 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2064 if (parentSettings.cropRect.left > layerCropRect.left &&
2065 parentSettings.cropRect.top > layerCropRect.top &&
2066 parentSettings.cropRect.right < layerCropRect.right &&
2067 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2068 return parentSettings;
2069 } else {
2070 return layerSettings;
2071 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002072 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002073 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002074 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002075 return parentSettings;
2076 }
2077 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002078}
2079
Robert Carr88b85e12022-03-21 15:47:35 -07002080bool Layer::findInHierarchy(const sp<Layer>& l) {
2081 if (l == this) {
2082 return true;
2083 }
2084 for (auto& child : mDrawingChildren) {
2085 if (child->findInHierarchy(l)) {
2086 return true;
2087 }
2088 }
2089 return false;
2090}
2091
Robert Carr1f0a16a2016-10-24 16:27:39 -07002092void Layer::commitChildList() {
2093 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2094 const auto& child = mCurrentChildren[i];
2095 child->commitChildList();
2096 }
2097 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002098 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002099 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2100 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2101 if (zOrderRelativeOf == nullptr) return;
2102 if (findInHierarchy(zOrderRelativeOf)) {
2103 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2104 zOrderRelativeOf->mName.c_str());
2105 ALOGE("Severing rel Z loop, potentially dangerous");
2106 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002107 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002108 }
2109 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002110}
2111
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002112
chaviw3277faf2021-05-19 16:45:23 -05002113void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002114 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002115 mDrawingState.touchableRegionCrop =
2116 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002117 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002118 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002119 setTransactionFlags(eTransactionNeeded);
2120}
2121
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002122LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002123 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002124 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002125 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2126
Vishnu Nair00b90132021-11-05 14:03:40 -07002127 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nair2f65e972023-04-04 16:36:28 +00002128 ui::LayerStack layerStack =
2129 (mSnapshot) ? mSnapshot->outputFilter.layerStack : ui::INVALID_LAYER_STACK;
2130 writeCompositionStateToProto(layerProto, layerStack);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002131 }
2132
chaviw08f3cb22020-01-13 13:17:21 -08002133 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002134 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002135 }
chaviw6d89e2d2020-01-14 14:42:01 -08002136
2137 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002138}
2139
Vishnu Nair2f65e972023-04-04 16:36:28 +00002140void Layer::writeCompositionStateToProto(LayerProto* layerProto, ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002141 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002142 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +00002143
2144 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002145 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002146 const auto compositionType = getCompositionType(*display);
2147 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +00002148 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +00002149 [&]() { return layerProto->mutable_visible_region(); });
2150 }
2151}
2152
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002153void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002154 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002155 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002156 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002157 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002158 [&]() { return layerInfo->mutable_active_buffer(); });
2159 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2160 layerInfo->mutable_buffer_transform());
2161 }
2162 layerInfo->set_invalidate(contentDirty);
2163 layerInfo->set_is_protected(isProtected());
2164 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2165 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002166 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002167 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002168 layerInfo->set_corner_radius(
2169 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002170 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2171 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2172 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2173 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2174 [&]() { return layerInfo->mutable_position(); });
2175 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002176 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2177 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002178
Vishnu Nair00b90132021-11-05 14:03:40 -07002179 if (hasColorTransform()) {
2180 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002181 }
2182
Vishnu Nair60db8c02020-04-02 11:55:16 -07002183 LayerProtoHelper::writeToProto(mSourceBounds,
2184 [&]() { return layerInfo->mutable_source_bounds(); });
2185 LayerProtoHelper::writeToProto(mScreenBounds,
2186 [&]() { return layerInfo->mutable_screen_bounds(); });
2187 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2188 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2189 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002190}
2191
2192void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002193 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002194 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2195 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002196 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002197
chaviw766c9c52021-02-10 17:36:47 -08002198 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002199
Vishnu Nair00b90132021-11-05 14:03:40 -07002200 layerInfo->set_id(sequence);
2201 layerInfo->set_name(getName().c_str());
2202 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002203
Vishnu Nair00b90132021-11-05 14:03:40 -07002204 for (const auto& child : children) {
2205 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002206 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002207
Vishnu Nair00b90132021-11-05 14:03:40 -07002208 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2209 sp<Layer> strongRelative = weakRelative.promote();
2210 if (strongRelative != nullptr) {
2211 layerInfo->add_relatives(strongRelative->sequence);
2212 }
2213 }
2214
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002215 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002216 [&]() { return layerInfo->mutable_transparent_region(); });
2217
2218 layerInfo->set_layer_stack(getLayerStack().id);
2219 layerInfo->set_z(state.z);
2220
2221 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2222 return layerInfo->mutable_requested_position();
2223 });
2224
Vishnu Nair00b90132021-11-05 14:03:40 -07002225 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2226
2227 layerInfo->set_is_opaque(isOpaque(state));
2228
2229 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2230 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2231 LayerProtoHelper::writeToProto(state.color,
2232 [&]() { return layerInfo->mutable_requested_color(); });
2233 layerInfo->set_flags(state.flags);
2234
2235 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2236 layerInfo->mutable_requested_transform());
2237
2238 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2239 if (parent != nullptr) {
2240 layerInfo->set_parent(parent->sequence);
2241 } else {
2242 layerInfo->set_parent(-1);
2243 }
2244
2245 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2246 if (zOrderRelativeOf != nullptr) {
2247 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2248 } else {
2249 layerInfo->set_z_order_relative_of(-1);
2250 }
2251
2252 layerInfo->set_is_relative_of(state.isRelativeOf);
2253
2254 layerInfo->set_owner_uid(mOwnerUid);
2255
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002256 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002257 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002258 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002259 info = fillInputInfo(
2260 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002261 } else {
2262 info = state.inputInfo;
2263 }
2264
2265 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002266 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002267 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002268
Vishnu Nair00b90132021-11-05 14:03:40 -07002269 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002270 auto protoMap = layerInfo->mutable_metadata();
2271 for (const auto& entry : state.metadata.mMap) {
2272 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2273 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002274 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002275
2276 LayerProtoHelper::writeToProto(state.destinationFrame,
2277 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002278}
2279
Robert Carr2e102c92018-10-23 12:11:15 -07002280bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002281 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002282}
2283
Prabir Pradhan33da9462022-06-14 14:55:57 +00002284// Applies the given transform to the region, while protecting against overflows caused by any
2285// offsets. If applying the offset in the transform to any of the Rects in the region would result
2286// in an overflow, they are not added to the output Region.
2287static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2288 const std::string& debugWindowName) {
2289 // Round the translation using the same rounding strategy used by ui::Transform.
2290 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2291 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2292
2293 ui::Transform transformWithoutOffset = t;
2294 transformWithoutOffset.set(0.f, 0.f);
2295
2296 const Region transformed = transformWithoutOffset.transform(r);
2297
2298 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2299 Region ret;
2300 for (const auto& rect : transformed) {
2301 Rect newRect;
2302 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2303 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2304 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2305 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2306 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2307 debugWindowName.c_str());
2308 continue;
2309 }
2310 ret.orSelf(newRect);
2311 }
2312 return ret;
2313}
2314
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002315void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002316 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2317 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002318 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002319 }
2320
Vishnu Nairfed7c122023-03-18 01:54:43 +00002321 const Rect roundedFrameInDisplay = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002322 info.frameLeft = roundedFrameInDisplay.left;
2323 info.frameTop = roundedFrameInDisplay.top;
2324 info.frameRight = roundedFrameInDisplay.right;
2325 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002326
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002327 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002328 inputToLayer.set(inputBounds.left, inputBounds.top);
2329 const ui::Transform layerToScreen = getInputTransform();
2330 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002331
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002332 // InputDispatcher expects a display-to-input transform.
2333 info.transform = inputToDisplay.inverse();
2334
2335 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002336 info.touchableRegion =
2337 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002338}
2339
chaviw3277faf2021-05-19 16:45:23 -05002340void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002341 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002342 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002343 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002344 }
2345 if (p != nullptr) {
2346 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2347 }
2348}
2349
Vishnu Naira066d902021-09-13 18:40:17 -07002350gui::DropInputMode Layer::getDropInputMode() const {
2351 gui::DropInputMode mode = mDrawingState.dropInputMode;
2352 if (mode == gui::DropInputMode::ALL) {
2353 return mode;
2354 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002355 sp<Layer> parent = mDrawingParent.promote();
2356 if (parent) {
2357 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002358 if (parentMode != gui::DropInputMode::NONE) {
2359 return parentMode;
2360 }
2361 }
2362 return mode;
2363}
2364
2365void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002366 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002367 return;
2368 }
2369
2370 // Check if we need to drop input unconditionally
2371 gui::DropInputMode dropInputMode = getDropInputMode();
2372 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002373 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002374 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2375 return;
2376 }
2377
2378 // Check if we need to check if the window is obscured by parent
2379 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2380 return;
2381 }
2382
2383 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002384 sp<Layer> parent = mDrawingParent.promote();
2385 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002386 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002387 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2388 static_cast<float>(getAlpha()));
2389 }
2390
2391 // Check if the parent has cropped the buffer
2392 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2393 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002394 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002395 return;
2396 }
2397
2398 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2399 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2400 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2401 // match then the layer has not been cropped by its parents.
2402 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2403 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2404
2405 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002406 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002407 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2408 getDebugName());
2409 } else {
2410 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2411 // input if the window is obscured. This check should be done in surfaceflinger but the
2412 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2413 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002414 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002415 }
2416}
2417
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002418WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002419 if (!hasInputInfo()) {
2420 mDrawingState.inputInfo.name = getName();
2421 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2422 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002423 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002424 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002425 }
2426
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002427 const ui::Transform& displayTransform =
2428 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2429
chaviw3277faf2021-05-19 16:45:23 -05002430 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002431 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002432 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002433
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002434 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002435
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002436 if (displayArgs.transform == nullptr) {
2437 // Do not let the window receive touches if it is not associated with a valid display
2438 // transform. We still allow the window to receive keys and prevent ANRs.
2439 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2440 }
2441
Robert Carr5dc426e2020-06-10 14:29:14 -07002442 // For compatibility reasons we let layers which can receive input
2443 // receive input before they have actually submitted a buffer. Because
2444 // of this we use canReceiveInput instead of isVisible to check the
2445 // policy-visibility, ignoring the buffer state. However for layers with
2446 // hasInputInfo()==false we can use the real visibility state.
2447 // We are just using these layers for occlusion detection in
2448 // InputDispatcher, and obviously if they aren't visible they can't occlude
2449 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002450 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2451 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2452
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002453 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002454 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002455 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002456
Vishnu Nair16a938f2021-09-24 07:14:54 -07002457 // If the window will be blacked out on a display because the display does not have the secure
2458 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002459 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002460 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002461 }
2462
Vishnu Nairfed7c122023-03-18 01:54:43 +00002463 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002464 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002465 Rect inputBoundsInDisplaySpace;
2466 if (!cropLayer) {
2467 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2468 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2469 } else {
2470 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2471 inputBoundsInDisplaySpace =
2472 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2473 }
2474 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002475 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002476 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2477 Rect inputBoundsInDisplaySpace =
2478 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2479 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002480 }
2481
Winson Chunga30f7c92021-06-29 15:42:56 -07002482 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2483 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002484 if (isTrustedOverlay()) {
2485 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2486 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002487
chaviwaf87b3e2019-10-01 16:59:28 -07002488 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2489 // touches from going outside the cloned area.
2490 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002491 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002492 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2493 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002494 info.touchableRegion = info.touchableRegion.intersect(rect);
2495 }
2496 }
2497
Robert Carr720e5062018-07-30 17:45:14 -07002498 return info;
2499}
2500
Vishnu Nairfed7c122023-03-18 01:54:43 +00002501Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2502 const ui::Transform& screenToDisplay) {
2503 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2504 // frame and transform used for the layer, which determines the bounds and the coordinate space
2505 // within which the layer will receive input.
2506
2507 // Coordinate space definitions:
2508 // - display: The display device's coordinate space. Correlates to pixels on the display.
2509 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2510 // - layer: The coordinate space of this layer.
2511 // - input: The coordinate space in which this layer will receive input events. This could be
2512 // different than layer space if a surfaceInset is used, which changes the origin
2513 // of the input space.
2514
2515 // Crop the input bounds to ensure it is within the parent's bounds.
2516 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2517 const ui::Transform layerToScreen = getInputTransform();
2518 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2519 return Rect{layerToDisplay.transform(croppedInputBounds)};
2520}
2521
chaviwaf87b3e2019-10-01 16:59:28 -07002522sp<Layer> Layer::getClonedRoot() {
2523 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002524 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002525 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002526 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002527 return nullptr;
2528 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002529 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002530}
2531
Robert Carredd13602020-04-13 17:24:34 -07002532bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002533 return mDrawingState.inputInfo.token != nullptr ||
2534 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002535}
2536
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002537compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002538 const DisplayDevice* display) const {
2539 if (!display) return nullptr;
Vishnu Naird47bcee2023-02-24 18:08:51 +00002540 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2541 return display->getCompositionDisplay()->getOutputLayerForLayer(
2542 getCompositionEngineLayerFE());
2543 }
2544 sp<LayerFE> layerFE;
2545 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2546 for (auto& [p, layer] : mLayerFEs) {
2547 if (p == path) {
2548 layerFE = layer;
2549 }
2550 }
2551
2552 if (!layerFE) return nullptr;
2553 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002554}
2555
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002556Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2557 const auto outputLayer = findOutputLayerForDisplay(display);
2558 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002559}
2560
chaviwb4c6e582019-08-16 14:35:07 -07002561void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002562 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002563 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002564 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2565 mPotentialCursor = clonedFrom->mPotentialCursor;
2566 mProtectedByApp = clonedFrom->mProtectedByApp;
2567 updateCloneBufferInfo();
2568}
2569
2570void Layer::updateCloneBufferInfo() {
2571 if (!isClone() || !isClonedFromAlive()) {
2572 return;
2573 }
2574
2575 sp<Layer> clonedFrom = getClonedFrom();
2576 mBufferInfo = clonedFrom->mBufferInfo;
2577 mSidebandStream = clonedFrom->mSidebandStream;
2578 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2579 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2580 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2581
2582 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2583 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2584 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2585 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2586 // the cloned drawingState again.
2587 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2588 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2589 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2590 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2591
2592 cloneDrawingState(clonedFrom.get());
2593
2594 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2595 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2596 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2597 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002598}
chaviw74b03172019-08-19 11:09:03 -07002599
2600void Layer::updateMirrorInfo() {
2601 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2602 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2603 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2604 // that case, we want to delete the reference to the clone since we want it to get
2605 // destroyed. The root, this layer, will still be around since the client can continue
2606 // to hold a reference, but no cloned layers will be displayed.
2607 mClonedChild = nullptr;
2608 return;
2609 }
2610
2611 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2612 // If the real layer exists and is in current state, add the clone as a child of the root.
2613 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2614 // copied to drawingState for the root layer. So the clonedChild is always removed from
2615 // drawingState and then needs to be added back each traversal.
2616 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2617 addChildToDrawing(mClonedChild);
2618 }
2619
2620 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002621 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002622 mClonedChild->updateClonedRelatives(clonedLayersMap);
2623}
2624
2625void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2626 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2627 // to the clone. If the real layer is no longer alive, continue traversing the children
2628 // since we may be able to pull out other children that are still alive.
2629 if (isClonedFromAlive()) {
2630 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002631 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002632 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002633 }
2634
2635 // The clone layer may have children in drawingState since they may have been created and
2636 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2637 // that already exist, since we can just re-use them.
2638 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2639 // not updated in the regular traversal. They are skipped since the root will lose the
2640 // reference to them when it copies its currentChildren to drawing.
2641 for (sp<Layer>& child : mDrawingChildren) {
2642 child->updateClonedDrawingState(clonedLayersMap);
2643 }
2644}
2645
2646void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2647 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2648 mDrawingChildren.clear();
2649
2650 if (!isClonedFromAlive()) {
2651 return;
2652 }
2653
2654 sp<Layer> clonedFrom = getClonedFrom();
2655 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2656 if (child == mirrorRoot) {
2657 // This is to avoid cyclical mirroring.
2658 continue;
2659 }
2660 sp<Layer> clonedChild = clonedLayersMap[child];
2661 if (clonedChild == nullptr) {
2662 clonedChild = child->createClone();
2663 clonedLayersMap[child] = clonedChild;
2664 }
2665 addChildToDrawing(clonedChild);
2666 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2667 }
2668}
2669
chaviwaf87b3e2019-10-01 16:59:28 -07002670void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2671 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2672 if (cropLayer != nullptr) {
2673 if (clonedLayersMap.count(cropLayer) == 0) {
2674 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2675 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002676 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002677 } else {
2678 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2679 mDrawingState.touchableRegionCrop = clonedCropLayer;
2680 }
2681 }
2682 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2683 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002684 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002685}
2686
2687void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002688 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002689 mDrawingState.zOrderRelatives.clear();
2690
2691 if (!isClonedFromAlive()) {
2692 return;
2693 }
2694
chaviwaf87b3e2019-10-01 16:59:28 -07002695 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002696 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002697 const sp<Layer>& relative = relativeWeak.promote();
2698 if (clonedLayersMap.count(relative) > 0) {
2699 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002700 mDrawingState.zOrderRelatives.add(clonedRelative);
2701 }
2702 }
2703
2704 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2705 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2706 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2707 // still traverse the children, but the layer with the missing relativeOf will not be shown
2708 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002709 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2710 if (clonedLayersMap.count(relativeOf) > 0) {
2711 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002712 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2713 }
2714
chaviwaf87b3e2019-10-01 16:59:28 -07002715 updateClonedInputInfo(clonedLayersMap);
2716
chaviw74b03172019-08-19 11:09:03 -07002717 for (sp<Layer>& child : mDrawingChildren) {
2718 child->updateClonedRelatives(clonedLayersMap);
2719 }
2720}
2721
2722void Layer::addChildToDrawing(const sp<Layer>& layer) {
2723 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002724 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002725}
2726
Steven Thomas62a4cf82020-01-31 12:04:03 -08002727Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2728 switch (compatibility) {
2729 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2730 return FrameRateCompatibility::Default;
2731 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2732 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002733 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2734 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002735 case ANATIVEWINDOW_FRAME_RATE_MIN:
2736 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002737 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2738 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002739 default:
2740 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2741 return FrameRateCompatibility::Default;
2742 }
2743}
2744
Marin Shalamanovc5986772021-03-16 16:09:49 +01002745scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2746 switch (strategy) {
2747 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2748 return Seamlessness::OnlySeamless;
2749 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2750 return Seamlessness::SeamedAndSeamless;
2751 default:
2752 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2753 return Seamlessness::Default;
2754 }
2755}
2756
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002757bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002758 const State& s(mDrawingState);
2759 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2760 return true;
2761 }
2762
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002763 sp<Layer> parent = mDrawingParent.promote();
2764 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002765}
2766
Robert Carr6a0382d2021-07-01 15:57:17 -07002767void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2768 mClonedChild = clonedChild;
2769 mHadClonedChild = true;
2770 mFlinger->mNumClones++;
2771}
2772
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002773bool Layer::setDropInputMode(gui::DropInputMode mode) {
2774 if (mDrawingState.dropInputMode == mode) {
2775 return false;
2776 }
2777 mDrawingState.dropInputMode = mode;
2778 return true;
2779}
2780
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002781void Layer::cloneDrawingState(const Layer* from) {
2782 mDrawingState = from->mDrawingState;
2783 // Skip callback info since they are not applicable for cloned layers.
2784 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002785 // TODO (b/238781169) currently broken for mirror layers because we do not
2786 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002787 mDrawingState.callbackHandles = {};
2788}
2789
Patrick Williamsbb25f802022-08-30 23:02:34 +00002790void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2791 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002792 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002793 if (!listener) {
2794 return;
2795 }
2796 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002797 uint32_t currentMaxAcquiredBufferCount =
2798 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002799 listener->onReleaseBuffer({buffer->getId(), framenumber},
2800 releaseFence ? releaseFence : Fence::NO_FENCE,
2801 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002802}
2803
2804void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2805 // If we are displayed on multiple displays in a single composition cycle then we would
2806 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2807 // For example we can only use it if all the displays are client comp, and we need
2808 // to merge all the client comp fences. We could do this, but for now we just
2809 // disable the optimization when a layer is composed on multiple displays.
2810 if (mClearClientCompositionFenceOnLayerDisplayed) {
2811 mLastClientCompositionFence = nullptr;
2812 } else {
2813 mClearClientCompositionFenceOnLayerDisplayed = true;
2814 }
2815
2816 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2817 // buffer that was presented on this layer. The first transaction that came in this frame that
2818 // replaced the previous buffer on this layer needs this release fence, because the fence will
2819 // let the client know when that previous buffer is removed from the screen.
2820 //
2821 // Every other transaction on this layer does not need a release fence because no other
2822 // Transactions that were set on this layer this frame are going to have their preceding buffer
2823 // removed from the display this frame.
2824 //
2825 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2826 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2827 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2828 // the previous buffer will be released this frame. The third transaction also contains a
2829 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2830 // transaction will now no longer be presented so it is released immediately and the third
2831 // transaction doesn't need a previous release fence.
2832 sp<CallbackHandle> ch;
2833 for (auto& handle : mDrawingState.callbackHandles) {
2834 if (handle->releasePreviousBuffer &&
2835 mDrawingState.releaseBufferEndpoint == handle->listener) {
2836 ch = handle;
2837 break;
2838 }
2839 }
2840
2841 // Prevent tracing the same release multiple times.
2842 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2843 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2844 }
2845
2846 if (ch != nullptr) {
2847 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2848 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2849 ch->name = mName;
2850 }
2851}
2852
2853void Layer::onSurfaceFrameCreated(
2854 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2855 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2856 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2857 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2858 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002859 if (hasBufferOrSidebandStreamInDrawing()) {
2860 // Only log for layers with a buffer, since we expect the jank data to be drained for
2861 // these, while there may be no jank listeners for bufferless layers.
2862 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2863 mName.c_str());
2864 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2865 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2866 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002867 mPendingJankClassifications.pop_front();
2868 }
2869 mPendingJankClassifications.emplace_back(surfaceFrame);
2870}
2871
2872void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2873 for (const auto& handle : mDrawingState.callbackHandles) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -07002874 if (mFlinger->mLayerLifecycleManagerEnabled) {
2875 handle->transformHint = mTransformHint;
2876 } else {
2877 handle->transformHint = mSkipReportingTransformHint
2878 ? std::nullopt
2879 : std::make_optional<uint32_t>(mTransformHintLegacy);
2880 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002881 handle->dequeueReadyTime = dequeueReadyTime;
2882 handle->currentMaxAcquiredBufferCount =
2883 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2884 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2885 handle->previousReleaseCallbackId.framenumber);
2886 }
2887
2888 for (auto& handle : mDrawingState.callbackHandles) {
2889 if (handle->releasePreviousBuffer &&
2890 mDrawingState.releaseBufferEndpoint == handle->listener) {
2891 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2892 break;
2893 }
2894 }
2895
2896 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002897 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002898 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2899 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002900 mDrawingState.callbackHandles = {};
2901}
2902
2903bool Layer::willPresentCurrentTransaction() const {
2904 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2905 return (getSidebandStreamChanged() || getAutoRefresh() ||
2906 (mDrawingState.modified &&
2907 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2908}
2909
2910bool Layer::setTransform(uint32_t transform) {
2911 if (mDrawingState.bufferTransform == transform) return false;
2912 mDrawingState.bufferTransform = transform;
2913 mDrawingState.modified = true;
2914 setTransactionFlags(eTransactionNeeded);
2915 return true;
2916}
2917
2918bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2919 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2920 mDrawingState.sequence++;
2921 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2922 mDrawingState.modified = true;
2923 setTransactionFlags(eTransactionNeeded);
2924 return true;
2925}
2926
2927bool Layer::setBufferCrop(const Rect& bufferCrop) {
2928 if (mDrawingState.bufferCrop == bufferCrop) return false;
2929
2930 mDrawingState.sequence++;
2931 mDrawingState.bufferCrop = bufferCrop;
2932
2933 mDrawingState.modified = true;
2934 setTransactionFlags(eTransactionNeeded);
2935 return true;
2936}
2937
2938bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2939 if (mDrawingState.destinationFrame == destinationFrame) return false;
2940
2941 mDrawingState.sequence++;
2942 mDrawingState.destinationFrame = destinationFrame;
2943
2944 mDrawingState.modified = true;
2945 setTransactionFlags(eTransactionNeeded);
2946 return true;
2947}
2948
2949// Translate destination frame into scale and position. If a destination frame is not set, use the
2950// provided scale and position
2951bool Layer::updateGeometry() {
2952 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2953 mDrawingState.destinationFrame.isEmpty()) {
2954 // If destination frame is not set, use the requested transform set via
2955 // Layer::setPosition and Layer::setMatrix.
2956 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2957 }
2958
2959 Rect destRect = mDrawingState.destinationFrame;
2960 int32_t destW = destRect.width();
2961 int32_t destH = destRect.height();
2962 if (destRect.left < 0) {
2963 destRect.left = 0;
2964 destRect.right = destW;
2965 }
2966 if (destRect.top < 0) {
2967 destRect.top = 0;
2968 destRect.bottom = destH;
2969 }
2970
2971 if (!mDrawingState.buffer) {
2972 ui::Transform t;
2973 t.set(destRect.left, destRect.top);
2974 return assignTransform(&mDrawingState.transform, t);
2975 }
2976
2977 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2978 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2979 // Undo any transformations on the buffer.
2980 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2981 std::swap(bufferWidth, bufferHeight);
2982 }
2983 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
2984 if (mDrawingState.transformToDisplayInverse) {
2985 if (invTransform & ui::Transform::ROT_90) {
2986 std::swap(bufferWidth, bufferHeight);
2987 }
2988 }
2989
2990 float sx = destW / static_cast<float>(bufferWidth);
2991 float sy = destH / static_cast<float>(bufferHeight);
2992 ui::Transform t;
2993 t.set(sx, 0, 0, sy);
2994 t.set(destRect.left, destRect.top);
2995 return assignTransform(&mDrawingState.transform, t);
2996}
2997
2998bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
2999 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3000 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3001 return false;
3002 }
3003
3004 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3005
3006 mDrawingState.sequence++;
3007 mDrawingState.modified = true;
3008 setTransactionFlags(eTransactionNeeded);
3009
3010 return true;
3011}
3012
3013bool Layer::setPosition(float x, float y) {
3014 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3015 return false;
3016 }
3017
3018 mRequestedTransform.set(x, y);
3019
3020 mDrawingState.sequence++;
3021 mDrawingState.modified = true;
3022 setTransactionFlags(eTransactionNeeded);
3023
3024 return true;
3025}
3026
3027bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3028 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3029 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003030 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003031 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003032 if (!buffer) {
3033 return false;
3034 }
3035
3036 const bool frameNumberChanged =
3037 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3038 const uint64_t frameNumber =
3039 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003040 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003041
3042 if (mDrawingState.buffer) {
3043 mReleasePreviousBuffer = true;
3044 if (!mBufferInfo.mBuffer ||
3045 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3046 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3047 // If mDrawingState has a buffer, and we are about to update again
3048 // before swapping to drawing state, then the first buffer will be
3049 // dropped and we should decrement the pending buffer count and
3050 // call any release buffer callbacks if set.
3051 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3052 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003053 mDrawingState.acquireFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003054 decrementPendingBufferCount();
3055 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3056 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3057 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
3058 mDrawingState.bufferSurfaceFrameTX.reset();
3059 }
3060 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3061 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3062 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003063 mLastClientCompositionFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003064 mLastClientCompositionFence = nullptr;
3065 }
Vishnu Nairc09c0232023-03-02 03:22:35 +00003066 } else {
3067 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3068 // we don't want to incorrectly classify a frame if we miss the desired present time.
3069 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003070 }
3071
liulijuneb489f62022-10-17 22:02:14 +08003072 mDrawingState.producerId = bufferData.producerId;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003073 mDrawingState.frameNumber = frameNumber;
3074 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3075 mDrawingState.buffer = std::move(buffer);
3076 mDrawingState.clientCacheId = bufferData.cachedBuffer;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003077 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3078 ? bufferData.acquireFence
3079 : Fence::NO_FENCE;
3080 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3081 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3082 // We latched this buffer unsiganled, so we need to pass the acquire fence
3083 // on the callback instead of just the acquire time, since it's unknown at
3084 // this point.
3085 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3086 } else {
3087 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3088 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003089 mDrawingState.latchedVsyncId = info.vsyncId;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003090 mDrawingState.modified = true;
3091 setTransactionFlags(eTransactionNeeded);
3092
3093 const int32_t layerId = getSequence();
3094 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3095 mOwnerUid, postTime, getGameMode());
3096 mDrawingState.desiredPresentTime = desiredPresentTime;
3097 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3098
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003099 if (mFlinger->mLegacyFrontEndEnabled) {
3100 recordLayerHistoryBufferUpdate(getLayerProps());
3101 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003102
3103 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3104
3105 if (dequeueTime && *dequeueTime != 0) {
3106 const uint64_t bufferId = mDrawingState.buffer->getId();
3107 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3108 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3109 FrameTracer::FrameEvent::DEQUEUE);
3110 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3111 FrameTracer::FrameEvent::QUEUE);
3112 }
3113
3114 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3115 return true;
3116}
3117
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003118void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3119 mDrawingState.desiredPresentTime = desiredPresentTime;
3120 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3121}
3122
3123void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps) {
3124 const nsecs_t presentTime = [&] {
3125 if (!mDrawingState.isAutoTimestamp) return mDrawingState.desiredPresentTime;
3126
3127 const auto prediction = mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3128 mDrawingState.latchedVsyncId);
3129 if (prediction.has_value()) return prediction->presentTime;
3130
3131 return static_cast<nsecs_t>(0);
3132 }();
3133 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3134 scheduler::LayerHistory::LayerUpdateType::Buffer);
3135}
3136
3137void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps) {
3138 const nsecs_t presentTime =
3139 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
3140 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3141 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3142}
3143
Patrick Williamsbb25f802022-08-30 23:02:34 +00003144bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003145 if (mDrawingState.dataspace == dataspace) return false;
3146 mDrawingState.dataspace = dataspace;
3147 mDrawingState.modified = true;
3148 setTransactionFlags(eTransactionNeeded);
3149 return true;
3150}
3151
John Reck68796592023-01-25 13:47:12 -05003152bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07003153 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3154 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05003155 return false;
Sally Qi963049b2023-03-23 14:06:21 -07003156 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3157 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05003158 mDrawingState.modified = true;
3159 setTransactionFlags(eTransactionNeeded);
3160 return true;
3161}
3162
Alec Mourif4af03e2023-02-11 00:25:24 +00003163bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3164 if (mDrawingState.cachingHint == cachingHint) return false;
3165 mDrawingState.cachingHint = cachingHint;
3166 mDrawingState.modified = true;
3167 setTransactionFlags(eTransactionNeeded);
3168 return true;
3169}
3170
Patrick Williamsbb25f802022-08-30 23:02:34 +00003171bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3172 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3173 mDrawingState.hdrMetadata = hdrMetadata;
3174 mDrawingState.modified = true;
3175 setTransactionFlags(eTransactionNeeded);
3176 return true;
3177}
3178
3179bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003180 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003181 mDrawingState.surfaceDamageRegion = surfaceDamage;
3182 mDrawingState.modified = true;
3183 setTransactionFlags(eTransactionNeeded);
3184 return true;
3185}
3186
3187bool Layer::setApi(int32_t api) {
3188 if (mDrawingState.api == api) return false;
3189 mDrawingState.api = api;
3190 mDrawingState.modified = true;
3191 setTransactionFlags(eTransactionNeeded);
3192 return true;
3193}
3194
3195bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3196 if (mDrawingState.sidebandStream == sidebandStream) return false;
3197
3198 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3199 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3200 } else if (sidebandStream != nullptr) {
3201 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3202 }
3203
3204 mDrawingState.sidebandStream = sidebandStream;
3205 mDrawingState.modified = true;
3206 setTransactionFlags(eTransactionNeeded);
3207 if (!mSidebandStreamChanged.exchange(true)) {
3208 // mSidebandStreamChanged was false
3209 mFlinger->onLayerUpdate();
3210 }
3211 return true;
3212}
3213
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003214bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3215 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003216 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3217 if (handles.empty()) {
3218 mReleasePreviousBuffer = false;
3219 return false;
3220 }
3221
Pascal Muetschard81cef292023-02-06 12:18:52 +01003222 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003223 for (const auto& handle : handles) {
3224 // If this transaction set a buffer on this layer, release its previous buffer
3225 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3226
3227 // If this layer will be presented in this frame
3228 if (willPresent) {
3229 // If this transaction set an acquire fence on this layer, set its acquire time
3230 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3231 handle->frameNumber = mDrawingState.frameNumber;
3232
3233 // Store so latched time and release fence can be set
3234 mDrawingState.callbackHandles.push_back(handle);
3235
3236 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003237 // Queue this handle to be notified below.
3238 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003239 }
3240 }
3241
Pascal Muetschard81cef292023-02-06 12:18:52 +01003242 if (!remainingHandles.empty()) {
3243 // Notify the transaction completed threads these handles are done. These are only the
3244 // handles that were not added to the mDrawingState, which will be notified later.
3245 std::vector<JankData> jankData;
3246 transferAvailableJankData(remainingHandles, jankData);
3247 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3248 }
3249
Patrick Williamsbb25f802022-08-30 23:02:34 +00003250 mReleasePreviousBuffer = false;
3251 mCallbackHandleAcquireTimeOrFence = -1;
3252
3253 return willPresent;
3254}
3255
3256Rect Layer::getBufferSize(const State& /*s*/) const {
3257 // for buffer state layers we use the display frame size as the buffer size.
3258
3259 if (mBufferInfo.mBuffer == nullptr) {
3260 return Rect::INVALID_RECT;
3261 }
3262
3263 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3264 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3265
3266 // Undo any transformations on the buffer and return the result.
3267 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3268 std::swap(bufWidth, bufHeight);
3269 }
3270
3271 if (getTransformToDisplayInverse()) {
3272 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3273 if (invTransform & ui::Transform::ROT_90) {
3274 std::swap(bufWidth, bufHeight);
3275 }
3276 }
3277
3278 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3279}
3280
3281FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3282 if (mBufferInfo.mBuffer == nullptr) {
3283 return parentBounds;
3284 }
3285
3286 return getBufferSize(getDrawingState()).toFloatRect();
3287}
3288
3289bool Layer::fenceHasSignaled() const {
3290 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3291 return true;
3292 }
3293
3294 const bool fenceSignaled =
3295 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3296 if (!fenceSignaled) {
3297 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3298 TimeStats::LatchSkipReason::LateAcquire);
3299 }
3300
3301 return fenceSignaled;
3302}
3303
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003304void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003305 for (const auto& handle : mDrawingState.callbackHandles) {
3306 handle->refreshStartTime = refreshStartTime;
3307 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003308}
3309
3310void Layer::setAutoRefresh(bool autoRefresh) {
3311 mDrawingState.autoRefresh = autoRefresh;
3312}
3313
3314bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3315 // 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 +00003316 auto* snapshot = editLayerSnapshot();
3317 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003318
3319 if (mSidebandStreamChanged.exchange(false)) {
3320 const State& s(getDrawingState());
3321 // mSidebandStreamChanged was true
3322 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003323 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003324 if (mSidebandStream != nullptr) {
3325 setTransactionFlags(eTransactionNeeded);
3326 mFlinger->setTransactionFlags(eTraversalNeeded);
3327 }
3328 recomputeVisibleRegions = true;
3329
3330 return true;
3331 }
3332 return false;
3333}
3334
3335bool Layer::hasFrameUpdate() const {
3336 const State& c(getDrawingState());
3337 return (mDrawingStateModified || mDrawingState.modified) &&
3338 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3339}
3340
Vishnu Naird47bcee2023-02-24 18:08:51 +00003341void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003342 const State& s(getDrawingState());
3343
3344 if (!s.buffer) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003345 if (bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003346 for (auto& handle : mDrawingState.callbackHandles) {
3347 handle->latchTime = latchTime;
3348 }
3349 }
3350 return;
3351 }
3352
3353 for (auto& handle : mDrawingState.callbackHandles) {
3354 if (handle->frameNumber == mDrawingState.frameNumber) {
3355 handle->latchTime = latchTime;
3356 }
3357 }
3358
3359 const int32_t layerId = getSequence();
3360 const uint64_t bufferId = mDrawingState.buffer->getId();
3361 const uint64_t frameNumber = mDrawingState.frameNumber;
3362 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3363 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3364 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3365
3366 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3367 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3368 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3369 FrameTracer::FrameEvent::LATCH);
3370
3371 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3372 if (bufferSurfaceFrame != nullptr &&
3373 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3374 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3375 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3376 // are processing the next state.
3377 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3378 mDrawingState.acquireFenceTime->getSignalTime(),
3379 latchTime);
3380 mDrawingState.bufferSurfaceFrameTX.reset();
3381 }
3382
3383 std::deque<sp<CallbackHandle>> remainingHandles;
3384 mFlinger->getTransactionCallbackInvoker()
3385 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3386 mDrawingState.callbackHandles = remainingHandles;
3387
3388 mDrawingStateModified = false;
3389}
3390
3391void Layer::gatherBufferInfo() {
3392 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3393 decrementPendingBufferCount();
3394 }
3395
3396 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3397 mBufferInfo.mBuffer = mDrawingState.buffer;
3398 mBufferInfo.mFence = mDrawingState.acquireFence;
3399 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3400 mBufferInfo.mPixelFormat =
3401 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3402 mBufferInfo.mFrameLatencyNeeded = true;
3403 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3404 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3405 mBufferInfo.mFence = mDrawingState.acquireFence;
3406 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3407 auto lastDataspace = mBufferInfo.mDataspace;
3408 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003409 if (mBufferInfo.mBuffer != nullptr) {
3410 auto& mapper = GraphicBufferMapper::get();
3411 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
3412 // and don't need to possibly remaps buffers.
3413 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
3414 status_t err = OK;
3415 {
3416 ATRACE_NAME("getDataspace");
3417 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
3418 }
3419 if (err != OK || dataspace != mBufferInfo.mDataspace) {
3420 {
3421 ATRACE_NAME("setDataspace");
3422 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
3423 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
3424 }
3425
3426 // Some GPU drivers may cache gralloc metadata which means before we composite we need
3427 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
3428 // compatible with old vendors, with a ticking clock.
3429 static const int32_t kVendorVersion =
3430 base::GetIntProperty("ro.vndk.version", __ANDROID_API_FUTURE__);
3431 if (const auto format =
3432 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
3433 mBufferInfo.mBuffer->getPixelFormat());
3434 err == OK && kVendorVersion < __ANDROID_API_U__ &&
3435 (format ==
3436 aidl::android::hardware::graphics::common::PixelFormat::
3437 IMPLEMENTATION_DEFINED ||
3438 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
3439 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
3440 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
3441 mBufferInfo.mBuffer->remapBuffer();
3442 }
3443 }
3444 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003445 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003446 mFlinger->mHdrLayerInfoChanged = true;
3447 }
Sally Qi963049b2023-03-23 14:06:21 -07003448 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3449 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05003450 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003451 }
3452 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3453 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3454 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3455 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3456 mBufferInfo.mApi = mDrawingState.api;
3457 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003458}
3459
3460Rect Layer::computeBufferCrop(const State& s) {
3461 if (s.buffer && !s.bufferCrop.isEmpty()) {
3462 Rect bufferCrop;
3463 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3464 return bufferCrop;
3465 } else if (s.buffer) {
3466 return s.buffer->getBounds();
3467 } else {
3468 return s.bufferCrop;
3469 }
3470}
3471
3472sp<Layer> Layer::createClone() {
3473 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3474 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003475 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003476 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3477 return layer;
3478}
3479
Patrick Williamsbb25f802022-08-30 23:02:34 +00003480void Layer::decrementPendingBufferCount() {
3481 int32_t pendingBuffers = --mPendingBufferTransactions;
3482 tracePendingBufferCount(pendingBuffers);
3483}
3484
3485void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3486 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3487}
3488
3489/*
3490 * We don't want to send the layer's transform to input, but rather the
3491 * parent's transform. This is because Layer's transform is
3492 * information about how the buffer is placed on screen. The parent's
3493 * transform makes more sense to send since it's information about how the
3494 * layer is placed on screen. This transform is used by input to determine
3495 * how to go from screen space back to window space.
3496 */
3497ui::Transform Layer::getInputTransform() const {
3498 if (!hasBufferOrSidebandStream()) {
3499 return getTransform();
3500 }
3501 sp<Layer> parent = mDrawingParent.promote();
3502 if (parent == nullptr) {
3503 return ui::Transform();
3504 }
3505
3506 return parent->getTransform();
3507}
3508
3509/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003510 * Returns the bounds used to fill the input frame and the touchable region.
3511 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003512 * Similar to getInputTransform, we need to update the bounds to include the transform.
3513 * This is because bounds don't include the buffer transform, where the input assumes
3514 * that's already included.
3515 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003516std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3517 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3518 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3519 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3520 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3521 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003522 }
3523
Vishnu Nairfed7c122023-03-18 01:54:43 +00003524 bool inputBoundsValid = croppedBufferSize.isValid();
3525 if (!inputBoundsValid) {
3526 /**
3527 * Input bounds are based on the layer crop or buffer size. But if we are using
3528 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3529 * we can use the parent bounds as the input bounds if the layer does not have buffer
3530 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3531 * use the parent bounds. A layer without a buffer can get input. So when a window is
3532 * initially added, its touchable region can fill its parent layer bounds and that can
3533 * have negative consequences.
3534 */
3535 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003536 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003537
3538 // Clamp surface inset to the input bounds.
3539 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3540 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3541 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3542
3543 // Apply the insets to the input bounds.
3544 inputBounds.left += xSurfaceInset;
3545 inputBounds.top += ySurfaceInset;
3546 inputBounds.right -= xSurfaceInset;
3547 inputBounds.bottom -= ySurfaceInset;
3548
3549 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003550}
3551
3552bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3553 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3554
3555 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3556 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3557 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3558 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3559 layer_state_t::eReparent;
3560
3561 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3562 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3563 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3564 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3565 layer_state_t::eInputInfoChanged;
3566
3567 if ((s.what & requiredFlags) != requiredFlags) {
3568 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3569 (s.what | requiredFlags) & ~s.what);
3570 return false;
3571 }
3572
3573 if (s.what & deniedFlags) {
3574 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3575 return false;
3576 }
3577
3578 if (s.what & allowedFlags) {
3579 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3580 }
3581
3582 if (s.what & layer_state_t::ePositionChanged) {
3583 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3584 ALOGV("%s: false [ePositionChanged changed]", __func__);
3585 return false;
3586 }
3587 }
3588
3589 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003590 if (mDrawingState.color.a != s.color.a) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003591 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3592 return false;
3593 }
3594 }
3595
3596 if (s.what & layer_state_t::eColorTransformChanged) {
3597 if (mDrawingState.colorTransform != s.colorTransform) {
3598 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3599 return false;
3600 }
3601 }
3602
3603 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003604 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003605 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3606 return false;
3607 }
3608 }
3609
3610 if (s.what & layer_state_t::eMatrixChanged) {
3611 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3612 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3613 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3614 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3615 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3616 return false;
3617 }
3618 }
3619
3620 if (s.what & layer_state_t::eCornerRadiusChanged) {
3621 if (mDrawingState.cornerRadius != s.cornerRadius) {
3622 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3623 return false;
3624 }
3625 }
3626
3627 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3628 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3629 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3630 return false;
3631 }
3632 }
3633
Vishnu Nairbbceb462022-10-10 04:52:13 +00003634 if (s.what & layer_state_t::eBufferTransformChanged) {
3635 if (mDrawingState.bufferTransform != s.bufferTransform) {
3636 ALOGV("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003637 return false;
3638 }
3639 }
3640
3641 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3642 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3643 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3644 return false;
3645 }
3646 }
3647
3648 if (s.what & layer_state_t::eCropChanged) {
3649 if (mDrawingState.crop != s.crop) {
3650 ALOGV("%s: false [eCropChanged changed]", __func__);
3651 return false;
3652 }
3653 }
3654
3655 if (s.what & layer_state_t::eDataspaceChanged) {
3656 if (mDrawingState.dataspace != s.dataspace) {
3657 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3658 return false;
3659 }
3660 }
3661
3662 if (s.what & layer_state_t::eHdrMetadataChanged) {
3663 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3664 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3665 return false;
3666 }
3667 }
3668
3669 if (s.what & layer_state_t::eSidebandStreamChanged) {
3670 if (mDrawingState.sidebandStream != s.sidebandStream) {
3671 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3672 return false;
3673 }
3674 }
3675
3676 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3677 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3678 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3679 return false;
3680 }
3681 }
3682
3683 if (s.what & layer_state_t::eShadowRadiusChanged) {
3684 if (mDrawingState.shadowRadius != s.shadowRadius) {
3685 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3686 return false;
3687 }
3688 }
3689
3690 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3691 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3692 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3693 return false;
3694 }
3695 }
3696
3697 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3698 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3699 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3700 return false;
3701 }
3702 }
3703
3704 if (s.what & layer_state_t::eStretchChanged) {
3705 StretchEffect temp = s.stretchEffect;
3706 temp.sanitize();
3707 if (mDrawingState.stretchEffect != temp) {
3708 ALOGV("%s: false [eStretchChanged changed]", __func__);
3709 return false;
3710 }
3711 }
3712
3713 if (s.what & layer_state_t::eBufferCropChanged) {
3714 if (mDrawingState.bufferCrop != s.bufferCrop) {
3715 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3716 return false;
3717 }
3718 }
3719
3720 if (s.what & layer_state_t::eDestinationFrameChanged) {
3721 if (mDrawingState.destinationFrame != s.destinationFrame) {
3722 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3723 return false;
3724 }
3725 }
3726
3727 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3728 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3729 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3730 return false;
3731 }
3732 }
3733
John Reck68796592023-01-25 13:47:12 -05003734 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07003735 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
3736 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
3737 ALOGV("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05003738 return false;
3739 }
3740 }
3741
Patrick Williamsbb25f802022-08-30 23:02:34 +00003742 ALOGV("%s: true", __func__);
3743 return true;
3744}
3745
3746bool Layer::isHdrY410() const {
3747 // pixel format is HDR Y410 masquerading as RGBA_1010102
3748 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3749 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3750 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3751}
3752
Vishnu Naire14c6b32022-08-06 04:20:15 +00003753sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003754 // 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 +00003755 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003756}
3757
Vishnu Naire14c6b32022-08-06 04:20:15 +00003758const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003759 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003760}
3761
Vishnu Naire14c6b32022-08-06 04:20:15 +00003762LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003763 return mSnapshot.get();
3764}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003765
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003766std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3767 return std::move(mSnapshot);
3768}
3769
3770void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3771 mSnapshot = std::move(snapshot);
3772}
3773
Patrick Williamsbb25f802022-08-30 23:02:34 +00003774const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003775 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003776}
3777
Patrick Williams7584c6a2022-10-29 02:10:58 +00003778sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003779 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003780 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3781 return result;
3782}
3783
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003784sp<LayerFE> Layer::getCompositionEngineLayerFE(
3785 const frontend::LayerHierarchy::TraversalPath& path) {
3786 for (auto& [p, layerFE] : mLayerFEs) {
3787 if (p == path) {
3788 return layerFE;
3789 }
3790 }
3791 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3792 mLayerFEs.emplace_back(path, layerFE);
3793 return layerFE;
3794}
3795
Patrick Williamsbb25f802022-08-30 23:02:34 +00003796void Layer::useSurfaceDamage() {
3797 if (mFlinger->mForceFullDamage) {
3798 surfaceDamageRegion = Region::INVALID_REGION;
3799 } else {
3800 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3801 }
3802}
3803
3804void Layer::useEmptyDamage() {
3805 surfaceDamageRegion.clear();
3806}
3807
3808bool Layer::isOpaque(const Layer::State& s) const {
3809 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3810 // layer's opaque flag.
3811 if (!hasSomethingToDraw()) {
3812 return false;
3813 }
3814
3815 // if the layer has the opaque flag, then we're always opaque
3816 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3817 return true;
3818 }
3819
3820 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003821 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003822 return true;
3823 }
3824
3825 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3826 return fillsColor() && getAlpha() == 1.0_hf;
3827}
3828
3829bool Layer::canReceiveInput() const {
3830 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3831}
3832
3833bool Layer::isVisible() const {
3834 if (!hasSomethingToDraw()) {
3835 return false;
3836 }
3837
3838 if (isHiddenByPolicy()) {
3839 return false;
3840 }
3841
3842 return getAlpha() > 0.0f || hasBlur();
3843}
3844
3845void Layer::onPostComposition(const DisplayDevice* display,
3846 const std::shared_ptr<FenceTime>& glDoneFence,
3847 const std::shared_ptr<FenceTime>& presentFence,
3848 const CompositorTiming& compositorTiming) {
3849 // mFrameLatencyNeeded is true when a new frame was latched for the
3850 // composition.
3851 if (!mBufferInfo.mFrameLatencyNeeded) return;
3852
3853 for (const auto& handle : mDrawingState.callbackHandles) {
3854 handle->gpuCompositionDoneFence = glDoneFence;
3855 handle->compositorTiming = compositorTiming;
3856 }
3857
3858 // Update mFrameTracker.
3859 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3860 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3861
3862 const int32_t layerId = getSequence();
3863 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3864
3865 const auto outputLayer = findOutputLayerForDisplay(display);
3866 if (outputLayer && outputLayer->requiresClientComposition()) {
3867 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3868 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3869 clientCompositionTimestamp,
3870 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3871 // Update the SurfaceFrames in the drawing state
3872 if (mDrawingState.bufferSurfaceFrameTX) {
3873 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3874 }
3875 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3876 surfaceFrame->setGpuComposition();
3877 }
3878 }
3879
3880 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3881 if (frameReadyFence->isValid()) {
3882 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3883 } else {
3884 // There was no fence for this frame, so assume that it was ready
3885 // to be presented at the desired present time.
3886 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3887 }
3888
3889 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08003890 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003891 const std::optional<Fps> renderRate =
3892 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3893
3894 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3895 const auto gameMode = getGameMode();
3896
3897 if (presentFence->isValid()) {
3898 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3899 refreshRate, renderRate, vote, gameMode);
3900 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3901 presentFence,
3902 FrameTracer::FrameEvent::PRESENT_FENCE);
3903 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3904 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3905 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003906 // The HWC doesn't support present fences, so use the present timestamp instead.
3907 const nsecs_t presentTimestamp =
3908 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3909
3910 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3911 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3912 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3913
Patrick Williamsbb25f802022-08-30 23:02:34 +00003914 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3915 refreshRate, renderRate, vote, gameMode);
3916 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3917 mCurrentFrameNumber, actualPresentTime,
3918 FrameTracer::FrameEvent::PRESENT_FENCE);
3919 mFrameTracker.setActualPresentTime(actualPresentTime);
3920 }
3921 }
3922
3923 mFrameTracker.advanceFrame();
3924 mBufferInfo.mFrameLatencyNeeded = false;
3925}
3926
3927bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003928 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
3929 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
3930}
3931
3932bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003933 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3934 getDrawingState().frameNumber);
3935
3936 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3937
3938 if (refreshRequired) {
3939 return refreshRequired;
3940 }
3941
3942 // If the head buffer's acquire fence hasn't signaled yet, return and
3943 // try again later
3944 if (!fenceHasSignaled()) {
3945 ATRACE_NAME("!fenceHasSignaled()");
3946 mFlinger->onLayerUpdate();
3947 return false;
3948 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00003949 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003950 if (mDrawingState.buffer == nullptr) {
3951 return false;
3952 }
3953
3954 // Capture the old state of the layer for comparisons later
3955 BufferInfo oldBufferInfo = mBufferInfo;
3956 const bool oldOpacity = isOpaque(mDrawingState);
3957 mPreviousFrameNumber = mCurrentFrameNumber;
3958 mCurrentFrameNumber = mDrawingState.frameNumber;
3959 gatherBufferInfo();
3960
3961 if (oldBufferInfo.mBuffer == nullptr) {
3962 // the first time we receive a buffer, we need to trigger a
3963 // geometry invalidation.
3964 recomputeVisibleRegions = true;
3965 }
3966
3967 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3968 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3969 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3970 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3971 recomputeVisibleRegions = true;
3972 }
3973
3974 if (oldBufferInfo.mBuffer != nullptr) {
3975 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3976 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3977 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3978 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3979 recomputeVisibleRegions = true;
3980 }
3981 }
3982
3983 if (oldOpacity != isOpaque(mDrawingState)) {
3984 recomputeVisibleRegions = true;
3985 }
3986
3987 return true;
3988}
3989
3990bool Layer::hasReadyFrame() const {
3991 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
3992}
3993
3994bool Layer::isProtected() const {
3995 return (mBufferInfo.mBuffer != nullptr) &&
3996 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
3997}
3998
Patrick Williamsbb25f802022-08-30 23:02:34 +00003999void Layer::latchAndReleaseBuffer() {
4000 if (hasReadyFrame()) {
4001 bool ignored = false;
4002 latchBuffer(ignored, systemTime());
4003 }
4004 releasePendingBuffer(systemTime());
4005}
4006
4007PixelFormat Layer::getPixelFormat() const {
4008 return mBufferInfo.mPixelFormat;
4009}
4010
4011bool Layer::getTransformToDisplayInverse() const {
4012 return mBufferInfo.mTransformToDisplayInverse;
4013}
4014
4015Rect Layer::getBufferCrop() const {
4016 // this is the crop rectangle that applies to the buffer
4017 // itself (as opposed to the window)
4018 if (!mBufferInfo.mCrop.isEmpty()) {
4019 // if the buffer crop is defined, we use that
4020 return mBufferInfo.mCrop;
4021 } else if (mBufferInfo.mBuffer != nullptr) {
4022 // otherwise we use the whole buffer
4023 return mBufferInfo.mBuffer->getBounds();
4024 } else {
4025 // if we don't have a buffer yet, we use an empty/invalid crop
4026 return Rect();
4027 }
4028}
4029
4030uint32_t Layer::getBufferTransform() const {
4031 return mBufferInfo.mTransform;
4032}
4033
4034ui::Dataspace Layer::getDataSpace() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004035 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4036}
4037
4038ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4039 ui::Dataspace updatedDataspace = dataspace;
4040 // translate legacy dataspaces to modern dataspaces
4041 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00004042 // Treat unknown dataspaces as V0_sRGB
4043 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00004044 case ui::Dataspace::SRGB:
4045 updatedDataspace = ui::Dataspace::V0_SRGB;
4046 break;
4047 case ui::Dataspace::SRGB_LINEAR:
4048 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4049 break;
4050 case ui::Dataspace::JFIF:
4051 updatedDataspace = ui::Dataspace::V0_JFIF;
4052 break;
4053 case ui::Dataspace::BT601_625:
4054 updatedDataspace = ui::Dataspace::V0_BT601_625;
4055 break;
4056 case ui::Dataspace::BT601_525:
4057 updatedDataspace = ui::Dataspace::V0_BT601_525;
4058 break;
4059 case ui::Dataspace::BT709:
4060 updatedDataspace = ui::Dataspace::V0_BT709;
4061 break;
4062 default:
4063 break;
4064 }
4065
4066 return updatedDataspace;
4067}
4068
4069sp<GraphicBuffer> Layer::getBuffer() const {
4070 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4071}
4072
Vishnu Nairb76d99a2023-03-19 18:22:31 -07004073void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4074 mTransformHintLegacy = getFixedTransformHint();
4075 if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4076 mTransformHintLegacy = displayTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004077 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004078 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004079}
4080
4081const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4082 return mBufferInfo.mBuffer;
4083}
4084
4085bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004086 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004087 return false;
4088 }
4089
4090 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004091 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004092 mDrawingState.modified = true;
4093 setTransactionFlags(eTransactionNeeded);
4094 return true;
4095}
4096
4097bool Layer::fillsColor() const {
4098 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4099 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4100}
4101
4102bool Layer::hasBlur() const {
4103 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4104}
4105
Vishnu Nairba354102022-08-01 00:14:18 +00004106void Layer::updateSnapshot(bool updateGeometry) {
4107 if (!getCompositionEngineLayerFE()) {
4108 return;
4109 }
4110
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004111 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004112 if (updateGeometry) {
4113 prepareBasicGeometryCompositionState();
4114 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004115 snapshot->roundedCorner = getRoundedCornerState();
4116 snapshot->stretchEffect = getStretchEffect();
4117 snapshot->transformedBounds = mScreenBounds;
4118 if (mEffectiveShadowRadius > 0.f) {
4119 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4120
4121 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4122 // it if transparent regions are present. This may not be necessary since shadows are
4123 // typically cast by layers without transparent regions.
4124 snapshot->shadowSettings.boundaries = mBounds;
4125
4126 const float casterAlpha = snapshot->alpha;
4127 const bool casterIsOpaque =
4128 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4129
4130 // If the casting layer is translucent, we need to fill in the shadow underneath the
4131 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4132 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4133 snapshot->shadowSettings.ambientColor *= casterAlpha;
4134 snapshot->shadowSettings.spotColor *= casterAlpha;
4135 }
4136 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004137 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004138 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004139 snapshot->layerOpaqueFlagSet =
4140 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004141 snapshot->isHdrY410 = isHdrY410();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004142 sp<Layer> p = mDrawingParent.promote();
4143 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004144 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004145 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004146 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004147 }
4148 snapshot->bufferSize = getBufferSize(mDrawingState);
4149 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004150 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004151 preparePerFrameCompositionState();
4152}
4153
Vishnu Naire14c6b32022-08-06 04:20:15 +00004154void Layer::updateChildrenSnapshots(bool updateGeometry) {
4155 for (const sp<Layer>& child : mDrawingChildren) {
4156 child->updateSnapshot(updateGeometry);
4157 child->updateChildrenSnapshots(updateGeometry);
4158 }
4159}
4160
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004161void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4162 mSnapshot->layerMetadata = parentMetadata;
4163 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4164 for (const sp<Layer>& child : mDrawingChildren) {
4165 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4166 }
4167}
4168
4169void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4170 std::unordered_set<Layer*>& visited) {
4171 if (visited.find(this) != visited.end()) {
4172 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4173 return;
4174 }
4175 visited.insert(this);
4176
4177 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4178
4179 if (mDrawingState.zOrderRelatives.empty()) {
4180 return;
4181 }
4182 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4183 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4184 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4185 sp<Layer> relative = weakRelative.promote();
4186 if (!relative) {
4187 continue;
4188 }
4189 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4190 }
4191}
4192
Chavi Weingarten328a8312023-01-26 21:17:52 +00004193bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004194 TrustedPresentationListener const& listener) {
4195 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4196 mTrustedPresentationListener = listener;
4197 mTrustedPresentationThresholds = thresholds;
4198 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4199 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4200 mFlinger->mNumTrustedPresentationListeners++;
4201 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4202 mFlinger->mNumTrustedPresentationListeners--;
4203 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004204
4205 // Reset trusted presentation states to ensure we start the time again.
4206 mEnteredTrustedPresentationStateTime = -1;
4207 mLastReportedTrustedPresentationState = false;
4208 mLastComputedTrustedPresentationState = false;
4209
4210 // If there's a new trusted presentation listener, the code needs to go through the composite
4211 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4212 // we're already in the requested state.
4213 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004214}
4215
Vishnu Naira156f482023-02-22 00:23:38 +00004216void Layer::updateLastLatchTime(nsecs_t latchTime) {
4217 mLastLatchTime = latchTime;
4218}
4219
Mathias Agopian13127d82013-03-05 17:47:11 -08004220// ---------------------------------------------------------------------------
4221
Marin Shalamanov46084422020-10-13 12:33:42 +02004222std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004223 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4224 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004225}
4226
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004227} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004228
4229#if defined(__gl_h_)
4230#error "don't include gl/gl.h in this file"
4231#endif
4232
4233#if defined(__gl2_h_)
4234#error "don't include gl2/gl2.h in this file"
4235#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004236
4237// TODO(b/129481165): remove the #pragma below and fix conversion issues
4238#pragma clang diagnostic pop // ignored "-Wconversion"