blob: 047d376ee4d98bb455588150df55e6903c7f0828 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Dan Stoza9e56aa02015-11-02 13:00:03 -080021//#define LOG_NDEBUG 0
22#undef LOG_TAG
23#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080024#define ATRACE_TAG ATRACE_TAG_GRAPHICS
25
Alec Mourie60041e2019-06-14 18:59:51 -070026#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080027
[1;3C2b9fc252021-02-04 16:16:50 -080028#include <android-base/properties.h>
Yiwei Zhang5434a782018-12-05 18:06:32 -080029#include <android-base/stringprintf.h>
Vishnu Nair0f085c62019-08-30 08:49:12 -070030#include <binder/IPCThreadState.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000031#include <compositionengine/CompositionEngine.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080032#include <compositionengine/Display.h>
Lloyd Piquea83776c2019-01-29 18:42:32 -080033#include <compositionengine/LayerFECompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080034#include <compositionengine/OutputLayer.h>
35#include <compositionengine/impl/OutputLayerCompositionState.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070036#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070037#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070038#include <cutils/properties.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070039#include <ftl/enum.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080040#include <ftl/fake_guard.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080041#include <gui/BufferItem.h>
42#include <gui/LayerDebugInfo.h>
43#include <gui/Surface.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000044#include <gui/TraceUtils.h>
Alec Mourie60041e2019-06-14 18:59:51 -070045#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070046#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080047#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070048#include <stdint.h>
49#include <stdlib.h>
50#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000051#include <system/graphics-base-v1.0.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080052#include <ui/DebugUtils.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000053#include <ui/FloatRect.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080054#include <ui/GraphicBuffer.h>
Sally Qif6918d42023-08-07 15:28:30 -070055#include <ui/HdrRenderTypeUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080056#include <ui/PixelFormat.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000057#include <ui/Rect.h>
58#include <ui/Transform.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059#include <utils/Errors.h>
60#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080061#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080063#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Alec Mourie60041e2019-06-14 18:59:51 -070065#include <algorithm>
66#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070067#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070068#include <sstream>
69
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070070#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080071#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070072#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070073#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +000074#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000075#include "FrontEnd/LayerHandle.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080076#include "LayerProtoHelper.h"
Josh Gao194ff392022-09-08 16:19:29 -070077#include "MutexUtils.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080079#include "TimeStats/TimeStats.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070080#include "TunnelModeEnabledReporter.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070081
David Sodman41fdfc92017-11-06 16:09:56 -080082#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000083#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085namespace android {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010086namespace {
87constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000088
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000089const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000090
Patrick Williamsbb25f802022-08-30 23:02:34 +000091bool assignTransform(ui::Transform* dst, ui::Transform& from) {
92 if (*dst == from) {
93 return false;
94 }
95 *dst = from;
96 return true;
97}
98
99TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
100 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
101 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
102 const auto frameRateCompatibility = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700103 switch (frameRate.vote.type) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000104 case Layer::FrameRateCompatibility::Default:
105 return FrameRateCompatibility::Default;
106 case Layer::FrameRateCompatibility::ExactOrMultiple:
107 return FrameRateCompatibility::ExactOrMultiple;
108 default:
109 return FrameRateCompatibility::Undefined;
110 }
111 }();
112
113 const auto seamlessness = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700114 switch (frameRate.vote.seamlessness) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000115 case scheduler::Seamlessness::OnlySeamless:
116 return Seamlessness::ShouldBeSeamless;
117 case scheduler::Seamlessness::SeamedAndSeamless:
118 return Seamlessness::NotRequired;
119 default:
120 return Seamlessness::Undefined;
121 }
122 }();
123
Rachel Leece6e0042023-06-27 11:22:54 -0700124 return TimeStats::SetFrameRateVote{.frameRate = frameRate.vote.rate.getValue(),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000125 .frameRateCompatibility = frameRateCompatibility,
126 .seamlessness = seamlessness};
127}
128
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100129} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800130
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700131using namespace ftl::flag_operators;
132
Yiwei Zhang5434a782018-12-05 18:06:32 -0800133using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000134using frontend::LayerSnapshot;
135using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800136using gui::GameMode;
137using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500138using gui::WindowInfo;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800139
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700140using PresentState = frametimeline::SurfaceFrame::PresentState;
141
Kean Mariotti4ba343c2023-04-19 13:31:02 +0000142Layer::Layer(const surfaceflinger::LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000143 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700144 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000145 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700146 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800147 mWindowType(static_cast<WindowInfo::Type>(
148 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000149 mLayerCreationFlags(args.flags),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000150 mBorderEnabled(false),
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000151 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000152 ALOGV("Creating Layer %s", getDebugName());
153
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700154 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700155 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
156 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
157 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700158 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
159 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700160 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700161 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700162 mDrawingState.z = 0;
163 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700164 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700165 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700166 mDrawingState.transform.set(0, 0);
167 mDrawingState.frameNumber = 0;
Vishnu Nair63221212023-04-06 15:17:37 -0700168 mDrawingState.barrierFrameNumber = 0;
169 mDrawingState.producerId = 0;
170 mDrawingState.barrierProducerId = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700171 mDrawingState.bufferTransform = 0;
172 mDrawingState.transformToDisplayInverse = false;
173 mDrawingState.crop.makeInvalid();
174 mDrawingState.acquireFence = sp<Fence>::make(-1);
175 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
Alec Mouri74c7ae12023-03-26 02:57:47 +0000176 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Robert Carr6a160312021-05-17 12:08:20 -0700177 mDrawingState.hdrMetadata.validTypes = 0;
178 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
179 mDrawingState.cornerRadius = 0.0f;
180 mDrawingState.backgroundBlurRadius = 0;
181 mDrawingState.api = -1;
182 mDrawingState.hasColorTransform = false;
183 mDrawingState.colorSpaceAgnostic = false;
184 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
185 mDrawingState.metadata = args.metadata;
186 mDrawingState.shadowRadius = 0.f;
187 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
188 mDrawingState.frameTimelineInfo = {};
189 mDrawingState.postTime = -1;
190 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000191 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700192 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700193 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000194 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700195
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700196 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
197 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700198 mDrawingState.color.r = -1.0_hf;
199 mDrawingState.color.g = -1.0_hf;
200 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700201 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700202
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500203 mFrameTracker.setDisplayRefreshPeriod(
204 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700205
Vishnu Naircb8be502022-10-12 19:03:23 +0000206 mOwnerUid = args.ownerUid;
207 mOwnerPid = args.ownerPid;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000208
209 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
210 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
211 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000212
213 mSnapshot->sequence = sequence;
214 mSnapshot->name = getDebugName();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000215 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 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000236 const int32_t layerId = getSequence();
237 mFlinger->mTimeStats->onDestroy(layerId);
238 mFlinger->mFrameTracer->onDestroy(layerId);
239
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000240 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700241 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700242
243 if (mDrawingState.sidebandStream != nullptr) {
244 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
245 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700246 if (mHadClonedChild) {
Vishnu Nair3be61902023-04-26 19:47:29 -0700247 auto& roots = mFlinger->mLayerMirrorRoots;
248 roots.erase(std::remove(roots.begin(), roots.end(), this), roots.end());
Robert Carr6a0382d2021-07-01 15:57:17 -0700249 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000250 if (hasTrustedPresentationListener()) {
251 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000252 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000253 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700254}
255
Mathias Agopian13127d82013-03-05 17:47:11 -0800256// ---------------------------------------------------------------------------
257// callbacks
258// ---------------------------------------------------------------------------
259
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700260void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700261 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700262 return;
263 }
Robert Carr2e102c92018-10-23 12:11:15 -0700264
Robert Carr6a160312021-05-17 12:08:20 -0700265 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700266 if (strongRelative == nullptr) {
267 setZOrderRelativeOf(nullptr);
268 return;
269 }
270
271 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700272 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700273 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800274 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700275 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700276}
277
278void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700279 if (!mRemovedFromDrawingState) {
280 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700281 mFlinger->mScheduler->deregisterLayer(this);
282 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000283 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000284
Ady Abrahamd11bade2022-08-01 16:18:03 -0700285 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700286}
Chia-I Wu38512252017-05-17 14:36:16 -0700287
chaviw68d4dab2020-06-08 15:07:32 -0700288sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000289 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700290 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700291 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700292 }
293 return parent->getRootLayer();
294}
295
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700296void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700297 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
298 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700299 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700300
Josh Gao194ff392022-09-08 16:19:29 -0700301 REQUIRE_MUTEX(mFlinger->mStateLock);
302 traverse(LayerVector::StateSet::Current,
303 [&](Layer* layer) REQUIRES(layer->mFlinger->mStateLock) {
304 layer->removeFromCurrentState();
305 layer->removeRelativeZ(layersInTree);
306 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700307}
308
chaviw61626f22018-11-15 16:26:27 -0800309void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700310 if (mRemovedFromDrawingState) {
311 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700312 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700313 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700314 }
chaviw61626f22018-11-15 16:26:27 -0800315
316 for (const auto& child : mCurrentChildren) {
317 child->addToCurrentState();
318 }
319}
320
Mathias Agopian13127d82013-03-05 17:47:11 -0800321// ---------------------------------------------------------------------------
322// set-up
323// ---------------------------------------------------------------------------
324
chaviw13fdc492017-06-27 12:40:18 -0700325bool Layer::getPremultipledAlpha() const {
326 return mPremultipliedAlpha;
327}
328
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700329sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800330 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700331 if (mGetHandleCalled) {
332 ALOGE("Get handle called twice" );
333 return nullptr;
334 }
335 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700336 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000337 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800338}
339
340// ---------------------------------------------------------------------------
341// h/w composer set-up
342// ---------------------------------------------------------------------------
343
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700344static Rect reduce(const Rect& win, const Region& exclude) {
345 if (CC_LIKELY(exclude.isEmpty())) {
346 return win;
347 }
348 if (exclude.isRect()) {
349 return win.reduce(exclude.getBounds());
350 }
351 return Region(win).subtract(exclude).getBounds();
352}
353
Dan Stoza80d61162017-12-20 15:57:52 -0800354static FloatRect reduce(const FloatRect& win, const Region& exclude) {
355 if (CC_LIKELY(exclude.isEmpty())) {
356 return win;
357 }
358 // Convert through Rect (by rounding) for lack of FloatRegion
359 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
360}
361
Vishnu Nair4351ad52019-02-11 14:13:02 -0800362Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800363 if (!reduceTransparentRegion) {
364 return Rect{mScreenBounds};
365 }
366
367 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800368 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800369 // Transform to screen space.
370 bounds = t.transform(bounds);
371 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700372}
373
Vishnu Nair4351ad52019-02-11 14:13:02 -0800374FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000375 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800376 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700377}
378
Vishnu Nairf0c28512019-02-08 12:40:28 -0800379FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
380 // Subtract the transparent region and snap to the bounds.
381 return reduce(mBounds, activeTransparentRegion);
382}
383
Chavi Weingarten076acac2023-01-19 17:20:43 +0000384// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000385void Layer::updateTrustedPresentationState(const DisplayDevice* display,
386 const frontend::LayerSnapshot* snapshot,
387 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000388 if (!hasTrustedPresentationListener()) {
389 return;
390 }
391 const bool lastState = mLastComputedTrustedPresentationState;
392 mLastComputedTrustedPresentationState = false;
393
394 if (!leaveState) {
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000395 const auto outputLayer = findOutputLayerForDisplay(display, snapshot->path);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000396 if (outputLayer != nullptr) {
397 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
398 Region coveredRegion =
399 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
400 mLastComputedTrustedPresentationState =
401 computeTrustedPresentationState(snapshot->geomLayerBounds,
402 snapshot->sourceBounds(), coveredRegion,
403 snapshot->transformedBounds,
404 snapshot->alpha,
405 snapshot->geomLayerTransform,
406 mTrustedPresentationThresholds);
407 } else {
408 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
409 "TrustedPresentationState",
410 getDebugName());
411 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000412 }
413 }
414 const bool newState = mLastComputedTrustedPresentationState;
415 if (lastState && !newState) {
416 // We were in the trusted presentation state, but now we left it,
417 // emit the callback if needed
418 if (mLastReportedTrustedPresentationState) {
419 mLastReportedTrustedPresentationState = false;
420 mTrustedPresentationListener.invoke(false);
421 }
422 // Reset the timer
423 mEnteredTrustedPresentationStateTime = -1;
424 } else if (!lastState && newState) {
425 // We were not in the trusted presentation state, but we entered it, begin the timer
426 // and make sure this gets called at least once more!
427 mEnteredTrustedPresentationStateTime = time_in_ms;
428 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
429 }
430
431 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
432 if (!mLastReportedTrustedPresentationState && newState &&
433 (time_in_ms - mEnteredTrustedPresentationStateTime >
434 mTrustedPresentationThresholds.stabilityRequirementMs)) {
435 mLastReportedTrustedPresentationState = true;
436 mTrustedPresentationListener.invoke(true);
437 }
438}
439
440/**
441 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
442 * of how the parameters and thresholds are interpreted. The general spirit is
443 * to produce an upper bound on the amount of the buffer which was presented.
444 */
445bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
446 const Region& coveredRegion,
447 const FloatRect& screenBounds, float alpha,
448 const ui::Transform& effectiveTransform,
449 const TrustedPresentationThresholds& thresholds) {
450 if (alpha < thresholds.minAlpha) {
451 return false;
452 }
453 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
454 return false;
455 }
456 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
457 return false;
458 }
459
460 const float sx = effectiveTransform.dsdx();
461 const float sy = effectiveTransform.dsdy();
462 float fractionRendered = std::min(sx * sy, 1.0f);
463
464 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
465 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
466 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
467
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000468 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
469 // Compute the size of all the rects since they may be disconnected.
470 float coveredSize = 0;
471 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
472 float size = rect->width() * rect->height();
473 coveredSize += size;
474 }
475
476 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000477
478 if (fractionRendered < thresholds.minFractionRendered) {
479 return false;
480 }
481
482 return true;
483}
484
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700485void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
486 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800487 const State& s(getDrawingState());
488
489 // Calculate effective layer transform
490 mEffectiveTransform = parentTransform * getActiveTransform(s);
491
Garfield Tan2c1782c2022-02-16 15:25:05 -0800492 if (CC_UNLIKELY(!isTransformValid())) {
493 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
494 getDebugName());
495 return;
496 }
497
Vishnu Nair4351ad52019-02-11 14:13:02 -0800498 // Transform parent bounds to layer space
499 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
500
Vishnu Nairc652ff82019-03-15 12:48:54 -0700501 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800502 mSourceBounds = computeSourceBounds(parentBounds);
503
504 // Calculate bounds by croping diplay frame with layer crop and parent bounds
505 FloatRect bounds = mSourceBounds;
506 const Rect layerCrop = getCrop(s);
507 if (!layerCrop.isEmpty()) {
508 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
509 }
510 bounds = bounds.intersect(parentBounds);
511
512 mBounds = bounds;
513 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700514
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700515 // Use the layer's own shadow radius if set. Otherwise get the radius from
516 // parent.
517 if (s.shadowRadius > 0.f) {
518 mEffectiveShadowRadius = s.shadowRadius;
519 } else {
520 mEffectiveShadowRadius = parentShadowRadius;
521 }
522
523 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
524 // don't pass it to its children.
525 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
526
Vishnu Nair4351ad52019-02-11 14:13:02 -0800527 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700528 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800529 }
Vishnu Nairba354102022-08-01 00:14:18 +0000530
531 if (mPotentialCursor) {
532 prepareCursorCompositionState();
533 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800534}
535
Vishnu Nair60356342018-11-13 13:00:45 -0800536Rect Layer::getCroppedBufferSize(const State& s) const {
537 Rect size = getBufferSize(s);
538 Rect crop = getCrop(s);
539 if (!crop.isEmpty() && size.isValid()) {
540 size.intersect(crop, &size);
541 } else if (!crop.isEmpty()) {
542 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700543 }
Vishnu Nair60356342018-11-13 13:00:45 -0800544 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800545}
546
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700547void Layer::setupRoundedCornersCropCoordinates(Rect win,
548 const FloatRect& roundedCornersCrop) const {
549 // Translate win by the rounded corners rect coordinates, to have all values in
550 // layer coordinate space.
551 win.left -= roundedCornersCrop.left;
552 win.right -= roundedCornersCrop.left;
553 win.top -= roundedCornersCrop.top;
554 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700555}
556
Lloyd Piquede196652020-01-22 17:29:58 -0800557void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800558 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800559 const auto alpha = static_cast<float>(getAlpha());
560 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700561 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800562
563 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
564 if (!opaque || alpha != 1.0f) {
565 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
566 : Hwc2::IComposerClient::BlendMode::COVERAGE;
567 }
568
Alec Mourif4af03e2023-02-11 00:25:24 +0000569 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000570 auto* snapshot = editLayerSnapshot();
571 snapshot->outputFilter = getOutputFilter();
572 snapshot->isVisible = isVisible();
573 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
574 snapshot->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800575
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000576 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800577 contentDirty = false;
578
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000579 snapshot->geomLayerBounds = mBounds;
580 snapshot->geomLayerTransform = getTransform();
581 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
582 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000583 snapshot->localTransform = getActiveTransform(drawingState);
584 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000585 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
586 snapshot->alpha = alpha;
Vishnu Nairc6384702023-07-31 12:22:20 -0700587 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
588 snapshot->blurRegions = getBlurRegions();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000589 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800590}
591
Lloyd Piquede196652020-01-22 17:29:58 -0800592void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800593 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000594 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700595
Alec Mourif4af03e2023-02-11 00:25:24 +0000596 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000597 snapshot->geomBufferSize = getBufferSize(drawingState);
598 snapshot->geomContentCrop = getBufferCrop();
599 snapshot->geomCrop = getCrop(drawingState);
600 snapshot->geomBufferTransform = getBufferTransform();
601 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
602 snapshot->geomUsesSourceCrop = usesSourceCrop();
603 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800604
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000605 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800606 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
607 for (const auto& [key, mandatory] : supportedMetadata) {
608 const auto& genericLayerMetadataCompatibilityMap =
609 mFlinger->getGenericLayerMetadataKeyMap();
610 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
611 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
612 continue;
613 }
614 const uint32_t id = compatIter->second;
615
616 auto it = drawingState.metadata.mMap.find(id);
617 if (it == std::end(drawingState.metadata.mMap)) {
618 continue;
619 }
620
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000621 snapshot->metadata.emplace(key,
622 compositionengine::GenericLayerMetadataEntry{mandatory,
623 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800624 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800625}
David Sodmanba340492018-08-05 21:51:33 -0700626
Lloyd Piquede196652020-01-22 17:29:58 -0800627void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800628 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000629 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000630 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800631
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000632 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800633
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000634 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
635 snapshot->dataspace = getDataSpace();
636 snapshot->colorTransform = getColorTransform();
637 snapshot->colorTransformIsIdentity = !hasColorTransform();
638 snapshot->surfaceDamage = surfaceDamageRegion;
639 snapshot->hasProtectedContent = isProtected();
640 snapshot->dimmingEnabled = isDimmingEnabled();
Sally Qi963049b2023-03-23 14:06:21 -0700641 snapshot->currentHdrSdrRatio = getCurrentHdrSdrRatio();
642 snapshot->desiredHdrSdrRatio = getDesiredHdrSdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000643 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800644
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700645 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700646
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000647 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800648
649 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400650 // Rounded corners no longer force client composition, since we may use a
651 // hole punch so that the layer will appear to have rounded corners.
Alec Mouri994761f2023-08-04 21:50:55 +0000652 if (drawShadows() || snapshot->stretchEffect.hasEffect()) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000653 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800654 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700655 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairc6384702023-07-31 12:22:20 -0700656 snapshot->blurRegions = getBlurRegions();
657 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400658
659 // Layer framerate is used in caching decisions.
660 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
661 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000662 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000663
664 if (hasBufferOrSidebandStream()) {
665 preparePerFrameBufferCompositionState();
666 } else {
667 preparePerFrameEffectsCompositionState();
668 }
669}
670
671void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000672 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000673 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000674 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000675 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
676 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000677 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
678 return;
679 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000680 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000681 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800682 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
683 snapshot->compositionType =
684 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000685 } else {
686 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000687 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
688 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000689 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
690 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
691 }
692
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000693 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000694 snapshot->acquireFence = mBufferInfo.mFence;
695 snapshot->frameNumber = mBufferInfo.mFrameNumber;
696 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000697}
698
699void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000700 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000701 auto* snapshot = editLayerSnapshot();
702 snapshot->color = getColor();
703 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000704 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800705}
706
Lloyd Piquede196652020-01-22 17:29:58 -0800707void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800708 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000709 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000710 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800711
712 // Apply the layer's transform, followed by the display's global transform
713 // Here we're guaranteed that the layer's transform preserves rects
714 Rect win = getCroppedBufferSize(drawingState);
715 // Subtract the transparent region and snap to the bounds
716 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
717 Rect frame(getTransform().transform(bounds));
718
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000719 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800720}
721
Lloyd Piquea83776c2019-01-29 18:42:32 -0800722const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700723 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800724}
725
Mathias Agopian13127d82013-03-05 17:47:11 -0800726// ---------------------------------------------------------------------------
727// drawing...
728// ---------------------------------------------------------------------------
729
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500730aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
731 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700732 const auto outputLayer = findOutputLayerForDisplay(&display);
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000733 return getCompositionType(outputLayer);
734}
735
736aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
737 const compositionengine::OutputLayer* outputLayer) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -0800738 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500739 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800740 }
741 if (outputLayer->getState().hwc) {
742 return (*outputLayer->getState().hwc).hwcCompositionType;
743 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500744 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800745 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800746}
747
Mathias Agopian13127d82013-03-05 17:47:11 -0800748// ----------------------------------------------------------------------------
749// local state
750// ----------------------------------------------------------------------------
751
David Sodman41fdfc92017-11-06 16:09:56 -0800752bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800753 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700754 if (s.flags & layer_state_t::eLayerSecure) {
755 return true;
756 }
757
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000758 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700759 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700760}
761
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100762void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
763 std::vector<JankData>& jankData) {
764 if (mPendingJankClassifications.empty() ||
765 !mPendingJankClassifications.front()->getJankType()) {
766 return;
767 }
768
769 bool includeJankData = false;
770 for (const auto& handle : handles) {
771 for (const auto& cb : handle->callbackIds) {
772 if (cb.includeJankData) {
773 includeJankData = true;
774 break;
775 }
776 }
777
778 if (includeJankData) {
779 jankData.reserve(mPendingJankClassifications.size());
780 break;
781 }
782 }
783
784 while (!mPendingJankClassifications.empty() &&
785 mPendingJankClassifications.front()->getJankType()) {
786 if (includeJankData) {
787 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
788 mPendingJankClassifications.front();
789 jankData.emplace_back(
790 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
791 }
792 mPendingJankClassifications.pop_front();
793 }
794}
795
Mathias Agopian13127d82013-03-05 17:47:11 -0800796// ----------------------------------------------------------------------------
797// transaction
798// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800799
Vishnu Naira156f482023-02-22 00:23:38 +0000800uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700801 ATRACE_CALL();
802
Robert Carr0758e5d2021-03-11 22:15:04 -0800803 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700804 mDrawingStateModified = mDrawingState.modified;
805 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700806
Alec Mourib416efd2018-09-06 21:01:59 +0000807 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700808
Robert Carr6a160312021-05-17 12:08:20 -0700809 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800810 // invalidate and recompute the visible regions if needed
811 flags |= Layer::eVisibleRegion;
812 }
813
Robert Carr6a160312021-05-17 12:08:20 -0700814 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800815 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000816 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800817 flags |= eVisibleRegion;
818 this->contentDirty = true;
819
820 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700821 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800822 }
823
Arthur Hung9ed43392022-05-27 06:31:57 +0000824 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
825 mFlinger->mUpdateInputInfo = true;
826 }
827
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700828 commitTransaction();
Robert Carra1257842020-01-31 13:48:28 -0800829
Mathias Agopian13127d82013-03-05 17:47:11 -0800830 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800831}
832
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700833void Layer::commitTransaction() {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000834 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
835 // bufferSurfaceFrameTX will be presented in latchBuffer.
836 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
837 if (surfaceFrame->getPresentState() != PresentState::Presented) {
838 // With applyPendingStates, we could end up having presented surfaceframes from previous
839 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800840 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000841 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
842 }
843 }
Robert Carr6a160312021-05-17 12:08:20 -0700844 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700845}
846
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700847uint32_t Layer::clearTransactionFlags(uint32_t mask) {
848 const auto flags = mTransactionFlags & mask;
849 mTransactionFlags &= ~mask;
850 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800851}
852
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700853void Layer::setTransactionFlags(uint32_t mask) {
854 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800855}
856
Robert Carr1f0a16a2016-10-24 16:27:39 -0700857bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
858 ssize_t idx = mCurrentChildren.indexOf(childLayer);
859 if (idx < 0) {
860 return false;
861 }
862 if (childLayer->setLayer(z)) {
863 mCurrentChildren.removeAt(idx);
864 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800865 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700866 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800867 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700868}
869
Robert Carr503c7042017-09-27 15:06:08 -0700870bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
871 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
872 ssize_t idx = mCurrentChildren.indexOf(childLayer);
873 if (idx < 0) {
874 return false;
875 }
876 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
877 mCurrentChildren.removeAt(idx);
878 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800879 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700880 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800881 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700882}
883
Robert Carrae060832016-11-28 10:51:00 -0800884bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700885 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
886 mDrawingState.sequence++;
887 mDrawingState.z = z;
888 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700889
Robert Carra70e91c2021-06-11 13:59:52 -0700890 mFlinger->mSomeChildrenChanged = true;
891
Robert Carrdb66e622017-04-10 16:55:57 -0700892 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700893 if (mDrawingState.zOrderRelativeOf != nullptr) {
894 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700895 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700896 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700897 }
chaviw606e5cf2019-03-01 10:12:10 -0800898 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700899 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800900 setTransactionFlags(eTransactionNeeded);
901 return true;
902}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700903
Robert Carrdb66e622017-04-10 16:55:57 -0700904void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700905 mDrawingState.zOrderRelatives.remove(relative);
906 mDrawingState.sequence++;
907 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700908 setTransactionFlags(eTransactionNeeded);
909}
910
911void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700912 mDrawingState.zOrderRelatives.add(relative);
913 mDrawingState.modified = true;
914 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700915 setTransactionFlags(eTransactionNeeded);
916}
917
chaviw606e5cf2019-03-01 10:12:10 -0800918void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700919 mDrawingState.zOrderRelativeOf = relativeOf;
920 mDrawingState.sequence++;
921 mDrawingState.modified = true;
922 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700923
chaviw606e5cf2019-03-01 10:12:10 -0800924 setTransactionFlags(eTransactionNeeded);
925}
926
Robert Carr503d2bd2017-12-04 15:49:47 -0800927bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000928 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700929 if (relative == nullptr) {
930 return false;
931 }
932
Robert Carr6a160312021-05-17 12:08:20 -0700933 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
934 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800935 return false;
936 }
937
Robert Carr88b85e12022-03-21 15:47:35 -0700938 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
939 (relative->mDrawingState.zOrderRelativeOf == this)) {
940 ALOGE("Detected relative layer loop between %s and %s",
941 mName.c_str(), relative->mName.c_str());
942 ALOGE("Ignoring new call to set relative layer");
943 return false;
944 }
945
Robert Carra70e91c2021-06-11 13:59:52 -0700946 mFlinger->mSomeChildrenChanged = true;
947
Robert Carr6a160312021-05-17 12:08:20 -0700948 mDrawingState.sequence++;
949 mDrawingState.modified = true;
950 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700951
Robert Carr6a160312021-05-17 12:08:20 -0700952 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700953 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700954 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700955 }
chaviw606e5cf2019-03-01 10:12:10 -0800956 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700957 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700958
959 setTransactionFlags(eTransactionNeeded);
960
961 return true;
962}
963
Winson Chunga30f7c92021-06-29 15:42:56 -0700964bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
965 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
966 mDrawingState.isTrustedOverlay = isTrustedOverlay;
967 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000968 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700969 setTransactionFlags(eTransactionNeeded);
970 return true;
971}
972
973bool Layer::isTrustedOverlay() const {
974 if (getDrawingState().isTrustedOverlay) {
975 return true;
976 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000977 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700978 return (p != nullptr) && p->isTrustedOverlay();
979}
980
Dan Stoza9e56aa02015-11-02 13:00:03 -0800981bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700982 if (mDrawingState.color.a == alpha) return false;
983 mDrawingState.sequence++;
984 mDrawingState.color.a = alpha;
985 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800986 setTransactionFlags(eTransactionNeeded);
987 return true;
988}
chaviw13fdc492017-06-27 12:40:18 -0700989
Valerie Haudd0b7572019-01-29 14:59:27 -0800990bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700991 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700992 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800993 }
Robert Carr6a160312021-05-17 12:08:20 -0700994 mDrawingState.sequence++;
995 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800996 setTransactionFlags(eTransactionNeeded);
997
Robert Carr6a160312021-05-17 12:08:20 -0700998 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -0800999 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001000 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001001 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001002 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Kean Mariotti4ba343c2023-04-19 13:31:02 +00001003 surfaceflinger::LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
1004 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001005
Valerie Haudd0b7572019-01-29 14:59:27 -08001006 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001007 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001008 mFlinger->mLayersAdded = true;
1009 // set up SF to handle added color layer
1010 if (isRemovedFromCurrentState()) {
Josh Gao194ff392022-09-08 16:19:29 -07001011 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001012 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001013 }
1014 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001015 } else if (mDrawingState.bgColorLayer && alpha == 0) {
Josh Gao194ff392022-09-08 16:19:29 -07001016 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001017 mDrawingState.bgColorLayer->reparent(nullptr);
1018 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001019 return true;
1020 }
1021
Robert Carr6a160312021-05-17 12:08:20 -07001022 mDrawingState.bgColorLayer->setColor(color);
1023 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1024 mDrawingState.bgColorLayer->setAlpha(alpha);
1025 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001026
chaviw13fdc492017-06-27 12:40:18 -07001027 return true;
1028}
1029
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001030bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001031 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001032
Robert Carr6a160312021-05-17 12:08:20 -07001033 mDrawingState.sequence++;
1034 mDrawingState.cornerRadius = cornerRadius;
1035 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001036 setTransactionFlags(eTransactionNeeded);
1037 return true;
1038}
1039
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001040bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001041 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001042 // If we start or stop drawing blur then the layer's visibility state may change so increment
1043 // the magic sequence number.
1044 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1045 mDrawingState.sequence++;
1046 }
Robert Carr6a160312021-05-17 12:08:20 -07001047 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1048 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001049 setTransactionFlags(eTransactionNeeded);
1050 return true;
1051}
Marissa Wall61c58622018-07-18 10:12:20 -07001052
Mathias Agopian13127d82013-03-05 17:47:11 -08001053bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001054 mDrawingState.sequence++;
1055 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001056 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001057 setTransactionFlags(eTransactionNeeded);
1058 return true;
1059}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001060
Lucas Dupinc3800b82020-10-02 16:24:48 -07001061bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001062 // If we start or stop drawing blur then the layer's visibility state may change so increment
1063 // the magic sequence number.
1064 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1065 mDrawingState.sequence++;
1066 }
Robert Carr6a160312021-05-17 12:08:20 -07001067 mDrawingState.blurRegions = blurRegions;
1068 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001069 setTransactionFlags(eTransactionNeeded);
1070 return true;
1071}
1072
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001073bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001074 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1075 if (mDrawingState.flags == newFlags) return false;
1076 mDrawingState.sequence++;
1077 mDrawingState.flags = newFlags;
1078 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001079 setTransactionFlags(eTransactionNeeded);
1080 return true;
1081}
Robert Carr99e27f02016-06-16 15:18:02 -07001082
chaviw25714502021-02-11 10:01:08 -08001083bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001084 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001085 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001086 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001087
Robert Carr6a160312021-05-17 12:08:20 -07001088 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001089 setTransactionFlags(eTransactionNeeded);
1090 return true;
1091}
Robert Carr8d5227b2017-03-16 15:41:03 -07001092
Evan Roskyef876c92019-01-25 17:46:06 -08001093bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001094 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1095 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001096 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001097 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001098}
1099
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001100bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001101 if (mDrawingState.layerStack == layerStack) return false;
1102 mDrawingState.sequence++;
1103 mDrawingState.layerStack = layerStack;
1104 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001105 setTransactionFlags(eTransactionNeeded);
1106 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001107}
1108
Peiyong Linc502cb72019-03-01 15:00:23 -08001109bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001110 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001111 return false;
1112 }
Robert Carr6a160312021-05-17 12:08:20 -07001113 mDrawingState.sequence++;
1114 mDrawingState.colorSpaceAgnostic = agnostic;
1115 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001116 setTransactionFlags(eTransactionNeeded);
1117 return true;
1118}
1119
Sally Qi81d95e62022-03-21 19:41:33 -07001120bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1121 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1122
1123 mDrawingState.sequence++;
1124 mDrawingState.dimmingEnabled = dimmingEnabled;
1125 mDrawingState.modified = true;
1126 setTransactionFlags(eTransactionNeeded);
1127 return true;
1128}
1129
Ana Krulecc84d09b2019-11-02 23:10:29 +01001130bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001131 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1132 mDrawingState.frameRateSelectionPriority = priority;
1133 mDrawingState.sequence++;
1134 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001135 setTransactionFlags(eTransactionNeeded);
1136 return true;
1137}
1138
1139int32_t Layer::getFrameRateSelectionPriority() const {
1140 // Check if layer has priority set.
1141 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1142 return mDrawingState.frameRateSelectionPriority;
1143 }
1144 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001145 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001146 if (parent != nullptr) {
1147 return parent->getFrameRateSelectionPriority();
1148 }
1149
1150 return Layer::PRIORITY_UNSET;
1151}
1152
Andy Labrada096227e2022-06-15 16:58:11 +00001153bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1154 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1155 mDrawingState.defaultFrameRateCompatibility = compatibility;
1156 mDrawingState.modified = true;
1157 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1158 setTransactionFlags(eTransactionNeeded);
1159 return true;
1160}
1161
1162scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1163 return mDrawingState.defaultFrameRateCompatibility;
1164}
1165
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001166bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1167 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1168};
1169
Vishnu Nair73908d12022-10-24 21:46:42 -07001170ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1171 bool useDrawing = state == LayerVector::StateSet::Drawing;
1172 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1173 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001174 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001175 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001176 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001177}
1178
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001179bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001180 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001181 return false;
1182 }
1183
Robert Carr6a160312021-05-17 12:08:20 -07001184 mDrawingState.sequence++;
1185 mDrawingState.shadowRadius = shadowRadius;
1186 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001187 setTransactionFlags(eTransactionNeeded);
1188 return true;
1189}
1190
Vishnu Nair6213bd92020-05-08 17:42:25 -07001191bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001192 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001193 return false;
1194 }
1195
Robert Carr6a160312021-05-17 12:08:20 -07001196 mDrawingState.sequence++;
1197 mDrawingState.fixedTransformHint = fixedTransformHint;
1198 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001199 setTransactionFlags(eTransactionNeeded);
1200 return true;
1201}
1202
John Reckcdb4ed72021-02-04 13:39:33 -05001203bool Layer::setStretchEffect(const StretchEffect& effect) {
1204 StretchEffect temp = effect;
1205 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001206 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001207 return false;
1208 }
Robert Carr6a160312021-05-17 12:08:20 -07001209 mDrawingState.sequence++;
1210 mDrawingState.stretchEffect = temp;
1211 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001212 setTransactionFlags(eTransactionNeeded);
1213 return true;
1214}
1215
John Reckc00c6692021-02-16 11:37:33 -05001216StretchEffect Layer::getStretchEffect() const {
1217 if (mDrawingState.stretchEffect.hasEffect()) {
1218 return mDrawingState.stretchEffect;
1219 }
1220
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001221 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001222 if (parent != nullptr) {
1223 auto effect = parent->getStretchEffect();
1224 if (effect.hasEffect()) {
1225 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1226 return effect;
1227 }
1228 }
1229 return StretchEffect{};
1230}
1231
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001232bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1233 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001234 return false;
1235 }
1236 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001237 mBorderWidth = width;
1238 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001239 return true;
1240}
1241
1242bool Layer::isBorderEnabled() {
1243 return mBorderEnabled;
1244}
1245
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001246float Layer::getBorderWidth() {
1247 return mBorderWidth;
1248}
1249
1250const half4& Layer::getBorderColor() {
1251 return mBorderColor;
1252}
1253
Ady Abrahama850c182021-08-04 13:04:37 -07001254bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1255 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1256 const auto frameRate = [&] {
Rachel Leece6e0042023-06-27 11:22:54 -07001257 if (mDrawingState.frameRate.isValid()) {
Ady Abrahama850c182021-08-04 13:04:37 -07001258 return mDrawingState.frameRate;
1259 }
1260
1261 return parentFrameRate;
1262 }();
1263
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001264 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001265
1266 // The frame rate is propagated to the children
1267 bool childrenHaveFrameRate = false;
1268 for (const sp<Layer>& child : mCurrentChildren) {
1269 childrenHaveFrameRate |=
1270 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1271 }
1272
Rachel Leece6e0042023-06-27 11:22:54 -07001273 // If we don't have a valid frame rate specification, but the children do, we set this
Ady Abrahama850c182021-08-04 13:04:37 -07001274 // layer as NoVote to allow the children to control the refresh rate
Rachel Leece6e0042023-06-27 11:22:54 -07001275 if (!frameRate.isValid() && childrenHaveFrameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001276 *transactionNeeded |=
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001277 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001278 }
1279
Rachel Leece6e0042023-06-27 11:22:54 -07001280 // We return whether this layer or its children has a vote. We ignore ExactOrMultiple votes for
Ady Abrahama850c182021-08-04 13:04:37 -07001281 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001282 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001283 const auto layerVotedWithDefaultCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001284 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Default;
1285 const auto layerVotedWithNoVote = frameRate.vote.type == FrameRateCompatibility::NoVote;
1286 const auto layerVotedWithCategory = frameRate.category != FrameRateCategory::Default;
Ady Abrahama850c182021-08-04 13:04:37 -07001287 const auto layerVotedWithExactCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001288 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Exact;
1289 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote || layerVotedWithCategory ||
Ady Abrahama850c182021-08-04 13:04:37 -07001290 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1291}
1292
Ady Abraham60e42ea2020-03-09 19:17:31 -07001293void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001294 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001295 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001296 while (auto parent = layer->getParent()) {
1297 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001298 }
Ady Abrahama850c182021-08-04 13:04:37 -07001299 return layer;
1300 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001301
Ady Abraham60e42ea2020-03-09 19:17:31 -07001302 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001303 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001304
Ady Abrahama850c182021-08-04 13:04:37 -07001305 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001306 if (transactionNeeded) {
1307 mFlinger->setTransactionFlags(eTraversalNeeded);
1308 }
1309}
1310
Rachel Leece6e0042023-06-27 11:22:54 -07001311bool Layer::setFrameRate(FrameRate::FrameRateVote frameRateVote) {
1312 if (mDrawingState.frameRate.vote == frameRateVote) {
Steven Thomas3172e202020-01-06 19:25:30 -08001313 return false;
1314 }
1315
Robert Carr6a160312021-05-17 12:08:20 -07001316 mDrawingState.sequence++;
Rachel Leece6e0042023-06-27 11:22:54 -07001317 mDrawingState.frameRate.vote = frameRateVote;
1318 mDrawingState.modified = true;
1319
1320 updateTreeHasFrameRateVote();
1321
1322 setTransactionFlags(eTransactionNeeded);
1323 return true;
1324}
1325
1326bool Layer::setFrameRateCategory(FrameRateCategory category) {
1327 if (mDrawingState.frameRate.category == category) {
1328 return false;
1329 }
1330
1331 mDrawingState.sequence++;
1332 mDrawingState.frameRate.category = category;
Robert Carr6a160312021-05-17 12:08:20 -07001333 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001334
1335 updateTreeHasFrameRateVote();
1336
Steven Thomas3172e202020-01-06 19:25:30 -08001337 setTransactionFlags(eTransactionNeeded);
1338 return true;
1339}
1340
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001341void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1342 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001343 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001344
1345 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1346 // there are two transactions with the same token, the first one without a buffer and the
1347 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1348 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001349 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1350 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001351 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001352 mDrawingState.bufferSurfaceFrameTX = it->second;
1353 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1354 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1355 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001356 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001357 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001358 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1359 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001360
1361 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001362}
1363
1364void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1365 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001366 mDrawingState.frameTimelineInfo = info;
1367 mDrawingState.postTime = postTime;
1368 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001369 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001370
Robert Carr6a160312021-05-17 12:08:20 -07001371 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001372 bufferSurfaceFrameTX != nullptr) {
1373 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1374 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1375 // being used for BufferSurfaceFrame, don't create a new one.
1376 return;
1377 }
1378 }
1379 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1380 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1381 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001382 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1383 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001384 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001385 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001386 } else {
1387 if (it->second->getPresentState() == PresentState::Presented) {
1388 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1389 // have been from previous vsync.
1390 it->second = createSurfaceFrameForTransaction(info, postTime);
1391 }
1392 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001393
1394 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001395}
1396
1397void Layer::addSurfaceFrameDroppedForBuffer(
Ady Abraham5a3e3562023-06-07 10:32:08 -07001398 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t dropTime) {
1399 surfaceFrame->setDropTime(dropTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001400 surfaceFrame->setPresentState(PresentState::Dropped);
1401 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1402}
1403
1404void Layer::addSurfaceFramePresentedForBuffer(
1405 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1406 nsecs_t currentLatchTime) {
1407 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1408 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1409 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001410 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001411}
1412
1413std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1414 const FrameTimelineInfo& info, nsecs_t postTime) {
1415 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001416 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1417 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001418 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001419 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001420 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001421 // For Transactions, the post time is considered to be both queue and acquire fence time.
1422 surfaceFrame->setActualQueueTime(postTime);
1423 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001424 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1425 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001426 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001427 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001428 onSurfaceFrameCreated(surfaceFrame);
1429 return surfaceFrame;
1430}
1431
1432std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1433 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1434 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001435 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001436 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001437 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001438 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001439 // For buffers, acquire fence time will set during latch.
1440 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001441 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1442 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001443 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001444 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001445 onSurfaceFrameCreated(surfaceFrame);
1446 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001447}
1448
Ady Abraham5a3e3562023-06-07 10:32:08 -07001449void Layer::setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
1450 std::string debugName) {
1451 if (info.skippedFrameVsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
1452 return;
1453 }
1454
1455 FrameTimelineInfo skippedFrameTimelineInfo = info;
1456 skippedFrameTimelineInfo.vsyncId = info.skippedFrameVsyncId;
1457
1458 auto surfaceFrame =
1459 mFlinger->mFrameTimeline->createSurfaceFrameForToken(skippedFrameTimelineInfo,
1460 mOwnerPid, mOwnerUid,
1461 getSequence(), mName, debugName,
1462 /*isBuffer*/ false, getGameMode());
1463 surfaceFrame->setActualStartTime(skippedFrameTimelineInfo.skippedFrameStartTimeNanos);
1464 // For Transactions, the post time is considered to be both queue and acquire fence time.
1465 surfaceFrame->setActualQueueTime(postTime);
1466 surfaceFrame->setAcquireFenceTime(postTime);
1467 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1468 if (fps) {
1469 surfaceFrame->setRenderRate(*fps);
1470 }
1471 onSurfaceFrameCreated(surfaceFrame);
1472 addSurfaceFrameDroppedForBuffer(surfaceFrame, postTime);
1473}
1474
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001475bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001476 if (mDrawingState.frameRateForLayerTree == frameRate) {
1477 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001478 }
1479
Ady Abrahama850c182021-08-04 13:04:37 -07001480 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001481
Ady Abrahama850c182021-08-04 13:04:37 -07001482 // TODO(b/195668952): we probably don't need to dirty visible regions here
1483 // or even store frameRateForLayerTree in mDrawingState
1484 mDrawingState.sequence++;
1485 mDrawingState.modified = true;
1486 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001487
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001488 mFlinger->mScheduler
1489 ->recordLayerHistory(sequence, getLayerProps(), systemTime(),
1490 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1491 return true;
1492}
Ady Abrahama850c182021-08-04 13:04:37 -07001493
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001494bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps) {
1495 if (mDrawingState.frameRateForLayerTree == frameRate) {
1496 return false;
1497 }
1498
1499 mDrawingState.frameRateForLayerTree = frameRate;
1500 mFlinger->mScheduler
1501 ->recordLayerHistory(sequence, layerProps, systemTime(),
1502 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001503 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001504}
1505
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001506Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1507 return getDrawingState().frameRateForLayerTree;
1508}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001509
Robert Carr1f0a16a2016-10-24 16:27:39 -07001510bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001511 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001512 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001513 if (parent != nullptr && parent->isHiddenByPolicy()) {
1514 return true;
1515 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001516 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1517 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1518 if (zOrderRelativeOf != nullptr) {
1519 if (zOrderRelativeOf->isHiddenByPolicy()) {
1520 return true;
1521 }
1522 }
1523 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001524 if (CC_UNLIKELY(!isTransformValid())) {
1525 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1526 return true;
1527 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001528 return s.flags & layer_state_t::eLayerHidden;
1529}
1530
David Sodman41fdfc92017-11-06 16:09:56 -08001531uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001532 // TODO: should we do something special if mSecure is set?
1533 if (mProtectedByApp) {
1534 // need a hardware-protected path to external video sink
1535 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001536 }
Riley Andrews03414a12014-07-01 14:22:59 -07001537 if (mPotentialCursor) {
1538 usage |= GraphicBuffer::USAGE_CURSOR;
1539 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001540 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001541 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001542}
1543
Vishnu Nair71fcf912022-10-18 09:14:20 -07001544void Layer::skipReportingTransformHint() {
1545 mSkipReportingTransformHint = true;
1546}
1547
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001548void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1549 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1550 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001551 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001552
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001553 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001554}
1555
Mathias Agopian13127d82013-03-05 17:47:11 -08001556// ----------------------------------------------------------------------------
1557// debugging
1558// ----------------------------------------------------------------------------
1559
Marissa Wall61c58622018-07-18 10:12:20 -07001560// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001561gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001562 using namespace std::string_literals;
1563
Huihong Luo05539a12022-02-23 10:29:40 -08001564 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001565 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001566 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001567 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001568 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001569 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001570
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001571 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001572 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001573 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001574 info.mX = ds.transform.tx();
1575 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001576 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001577 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001578 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001579 info.mFlags = ds.flags;
1580 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001581 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001582 info.mMatrix[0][0] = ds.transform[0][0];
1583 info.mMatrix[0][1] = ds.transform[0][1];
1584 info.mMatrix[1][0] = ds.transform[1][0];
1585 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001586 {
chaviwd62d3062019-09-04 14:48:02 -07001587 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001588 if (buffer != 0) {
1589 info.mActiveBufferWidth = buffer->getWidth();
1590 info.mActiveBufferHeight = buffer->getHeight();
1591 info.mActiveBufferStride = buffer->getStride();
1592 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001593 } else {
1594 info.mActiveBufferWidth = 0;
1595 info.mActiveBufferHeight = 0;
1596 info.mActiveBufferStride = 0;
1597 info.mActiveBufferFormat = 0;
1598 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001599 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001600 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001601 info.mIsOpaque = isOpaque(ds);
1602 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001603 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001604 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001605}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001606
Yiwei Zhang5434a782018-12-05 18:06:32 -08001607void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001608 result.append(kDumpTableRowLength, '-');
1609 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001610 result.append(" Layer name\n");
1611 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001612 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001613 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001614 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001615 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001616 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001617 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1618 result.append(kDumpTableRowLength, '-');
1619 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001620}
1621
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001622void Layer::miniDumpLegacy(std::string& result, const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001623 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001624 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001625 return;
1626 }
1627
Yiwei Zhang5434a782018-12-05 18:06:32 -08001628 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001629 if (mName.length() > 77) {
1630 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001631 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001632 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001633 shortened.append(mName, mName.length() - 36);
1634 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001635 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001636 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001637 }
1638
Yiwei Zhang5434a782018-12-05 18:06:32 -08001639 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001640
Alec Mourib416efd2018-09-06 21:01:59 +00001641 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001642 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001643
Chia-I Wu1e043612018-03-01 09:45:09 -08001644 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001645 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001646 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001647 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001648 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001649 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001650 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001651 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1652 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001653 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001654 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001655 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001656 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001657 const auto frameRate = getFrameRateForLayerTree();
Rachel Leece6e0042023-06-27 11:22:54 -07001658 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
1659 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.vote.rate).c_str(),
1660 ftl::enum_string(frameRate.vote.type).c_str(),
1661 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001662 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001663 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001664 }
Dan Stozae22aec72016-08-01 13:20:59 -07001665
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001666 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1667 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1668
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001669 result.append(kDumpTableRowLength, '-');
1670 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001671}
Dan Stozae22aec72016-08-01 13:20:59 -07001672
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001673void Layer::miniDump(std::string& result, const frontend::LayerSnapshot& snapshot,
1674 const DisplayDevice& display) const {
1675 const auto outputLayer = findOutputLayerForDisplay(&display, snapshot.path);
1676 if (!outputLayer) {
1677 return;
1678 }
1679
1680 StringAppendF(&result, " %s\n", snapshot.debugName.c_str());
1681 StringAppendF(&result, " %10zu | ", snapshot.globalZ);
1682 StringAppendF(&result, " %10d | ",
1683 snapshot.layerMetadata.getInt32(gui::METADATA_WINDOW_TYPE, 0));
1684 StringAppendF(&result, "%10s | ", toString(getCompositionType(outputLayer)).c_str());
1685 const auto& outputLayerState = outputLayer->getState();
1686 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1687 const Rect& frame = outputLayerState.displayFrame;
1688 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1689 const FloatRect& crop = outputLayerState.sourceCrop;
1690 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
1691 crop.bottom);
1692 const auto frameRate = snapshot.frameRate;
Rachel Leece6e0042023-06-27 11:22:54 -07001693 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
1694 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.vote.rate).c_str(),
1695 ftl::enum_string(frameRate.vote.type).c_str(),
1696 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001697 } else {
1698 result.append(41, ' ');
1699 }
1700
1701 const auto focused = isLayerFocusedBasedOnPriority(snapshot.frameRateSelectionPriority);
1702 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1703
1704 result.append(kDumpTableRowLength, '-');
1705 result.append("\n");
1706}
1707
Yiwei Zhang5434a782018-12-05 18:06:32 -08001708void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001709 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001710}
1711
Svetoslavd85084b2014-03-20 10:28:31 -07001712void Layer::clearFrameStats() {
1713 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001714}
1715
Jamie Gennis6547ff42013-07-16 20:12:42 -07001716void Layer::logFrameStats() {
1717 mFrameTracker.logAndResetStats(mName);
1718}
1719
Svetoslavd85084b2014-03-20 10:28:31 -07001720void Layer::getFrameStats(FrameStats* outStats) const {
1721 mFrameTracker.getStats(outStats);
1722}
1723
Vishnu Nair76554eb2022-12-09 03:38:36 +00001724void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1725 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
Vishnu Nair3be61902023-04-26 19:47:29 -07001726 StringAppendF(&result, "Layer %s%s pid:%d uid:%d%s\n", getName().c_str(), hasBuffer.c_str(),
1727 mOwnerPid, mOwnerUid, isHandleAlive() ? " handleAlive" : "");
Vishnu Nair0f085c62019-08-30 08:49:12 -07001728}
1729
Brian Anderson5ea5e592016-12-01 16:54:33 -08001730void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001731 const int32_t layerId = getSequence();
1732 mFlinger->mTimeStats->onDestroy(layerId);
1733 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001734}
1735
Vishnu Nair787aa782023-03-17 13:46:46 -07001736size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001737 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001738 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001739 count += 1 + child->getChildrenCount();
1740 }
1741 return count;
1742}
1743
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001744void Layer::setGameModeForTree(GameMode gameMode) {
1745 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001746 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1747 gameMode =
1748 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001749 }
1750 setGameMode(gameMode);
1751 for (const sp<Layer>& child : mCurrentChildren) {
1752 child->setGameModeForTree(gameMode);
1753 }
1754}
1755
Robert Carr1f0a16a2016-10-24 16:27:39 -07001756void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001757 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001758 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001759
Robert Carr1f0a16a2016-10-24 16:27:39 -07001760 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001761 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001762 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001763 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001764}
1765
1766ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001767 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001768 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001769
Robert Carr1323c952019-01-28 18:13:27 -08001770 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001771 const auto removeResult = mCurrentChildren.remove(layer);
1772
1773 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001774 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001775 layer->updateTreeHasFrameRateVote();
1776
1777 return removeResult;
1778}
1779
Robert Carr15eae092018-03-23 13:43:53 -07001780void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001781 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001782 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001783 const float parentShadowRadius =
1784 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001785 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001786 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001787 }
1788}
1789
chaviwf1961f72017-09-18 16:41:07 -07001790bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001791 sp<Layer> newParent;
1792 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001793 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001794 if (newParent == nullptr) {
1795 ALOGE("Unable to promote Layer handle");
1796 return false;
1797 }
1798 if (newParent == this) {
1799 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1800 return false;
1801 }
1802 }
1803
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001804 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001805 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001806 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001807 }
1808
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001809 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001810 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001811 if (!newParent->isRemovedFromCurrentState()) {
1812 addToCurrentState();
1813 } else {
1814 onRemovedFromCurrentState();
1815 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001816 } else {
1817 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001818 }
1819
chaviw06178942017-07-27 10:25:59 -07001820 return true;
1821}
1822
Peiyong Lind3788632018-09-18 16:01:31 -07001823bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001824 static const mat4 identityMatrix = mat4();
1825
Robert Carr6a160312021-05-17 12:08:20 -07001826 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001827 return false;
1828 }
Robert Carr6a160312021-05-17 12:08:20 -07001829 ++mDrawingState.sequence;
1830 mDrawingState.colorTransform = matrix;
1831 mDrawingState.hasColorTransform = matrix != identityMatrix;
1832 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001833 setTransactionFlags(eTransactionNeeded);
1834 return true;
1835}
1836
chaviwf66724d2018-11-28 16:35:21 -08001837mat4 Layer::getColorTransform() const {
1838 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001839 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001840 colorTransform = parent->getColorTransform() * colorTransform;
1841 }
1842 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001843}
1844
1845bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001846 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001847 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001848 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1849 }
1850 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001851}
1852
Chia-I Wu11481472018-05-04 10:43:19 -07001853bool Layer::isLegacyDataSpace() const {
1854 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001855 return !(getDataSpace() &
1856 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1857 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001858}
1859
Robert Carr1f0a16a2016-10-24 16:27:39 -07001860void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001861 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001862}
1863
Robert Carr6a160312021-05-17 12:08:20 -07001864int32_t Layer::getZ(LayerVector::StateSet) const {
1865 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001866}
1867
Robert Carr1c5481e2019-07-01 14:42:27 -07001868bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001869 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001870 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001871 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001872}
1873
David Sodman41fdfc92017-11-06 16:09:56 -08001874__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001875 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001876 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1877 "makeTraversalList received invalid stateSet");
1878 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1879 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001880 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001881
Robert Carr29abff82017-12-04 13:51:20 -08001882 if (state.zOrderRelatives.size() == 0) {
1883 *outSkipRelativeZUsers = true;
1884 return children;
1885 }
1886
chaviwfd462612018-05-31 16:11:27 -07001887 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001888 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001889 sp<Layer> strongRelative = weakRelative.promote();
1890 if (strongRelative != nullptr) {
1891 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001892 }
1893 }
1894
Dan Stoza412903f2017-04-27 13:42:17 -07001895 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001896 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001897 continue;
1898 }
Robert Carrdb66e622017-04-10 16:55:57 -07001899 traverse.add(child);
1900 }
1901
1902 return traverse;
1903}
1904
Robert Carr1f0a16a2016-10-24 16:27:39 -07001905/**
Robert Carrdb66e622017-04-10 16:55:57 -07001906 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001907 */
Dan Stoza412903f2017-04-27 13:42:17 -07001908void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001909 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1910 // produce a new list for traversing, including our relatives, and not including our children
1911 // who are relatives of another surface. In the case that there are no relative Z,
1912 // makeTraversalList returns our children directly to avoid significant overhead.
1913 // However in this case we need to take the responsibility for filtering children which
1914 // are relatives of another surface here.
1915 bool skipRelativeZUsers = false;
1916 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001917
Robert Carr1f0a16a2016-10-24 16:27:39 -07001918 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001919 for (; i < list.size(); i++) {
1920 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001921 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1922 continue;
1923 }
1924
chaviw301b1d82019-11-06 13:15:09 -08001925 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001926 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001927 }
Dan Stoza412903f2017-04-27 13:42:17 -07001928 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001929 }
Robert Carr29abff82017-12-04 13:51:20 -08001930
Dan Stoza412903f2017-04-27 13:42:17 -07001931 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001932 for (; i < list.size(); i++) {
1933 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001934
Robert Carr29abff82017-12-04 13:51:20 -08001935 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1936 continue;
1937 }
Dan Stoza412903f2017-04-27 13:42:17 -07001938 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001939 }
1940}
1941
1942/**
Robert Carrdb66e622017-04-10 16:55:57 -07001943 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001944 */
Dan Stoza412903f2017-04-27 13:42:17 -07001945void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1946 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001947 // See traverseInZOrder for documentation.
1948 bool skipRelativeZUsers = false;
1949 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001950
Robert Carr1f0a16a2016-10-24 16:27:39 -07001951 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001952 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001953 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001954
1955 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1956 continue;
1957 }
1958
chaviw301b1d82019-11-06 13:15:09 -08001959 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001960 break;
1961 }
Dan Stoza412903f2017-04-27 13:42:17 -07001962 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001963 }
Dan Stoza412903f2017-04-27 13:42:17 -07001964 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001965 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001966 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001967
1968 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1969 continue;
1970 }
1971
Dan Stoza412903f2017-04-27 13:42:17 -07001972 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001973 }
1974}
1975
Edgar Arriaga844fa672020-01-16 14:21:42 -08001976void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1977 visitor(this);
1978 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001979 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001980 for (const sp<Layer>& child : children) {
1981 child->traverse(state, visitor);
1982 }
1983}
1984
Vishnu Nair787aa782023-03-17 13:46:46 -07001985void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
1986 for (const sp<Layer>& child : mDrawingChildren) {
1987 visitor(child.get());
1988 }
1989}
1990
chaviw4b129c22018-04-09 16:19:43 -07001991LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1992 const std::vector<Layer*>& layersInTree) {
1993 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1994 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001995 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1996 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001997 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001998
chaviwfd462612018-05-31 16:11:27 -07001999 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07002000 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2001 sp<Layer> strongRelative = weakRelative.promote();
2002 // Only add relative layers that are also descendents of the top most parent of the tree.
2003 // If a relative layer is not a descendent, then it should be ignored.
2004 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
2005 traverse.add(strongRelative);
2006 }
2007 }
2008
2009 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07002010 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002011 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
2012 // descendent of the top most parent of the tree. If it's not a descendent, then just add
2013 // the child here since it won't be added later as a relative.
2014 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
2015 childState.zOrderRelativeOf.promote().get())) {
2016 continue;
2017 }
2018 traverse.add(child);
2019 }
2020
2021 return traverse;
2022}
2023
2024void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
2025 LayerVector::StateSet stateSet,
2026 const LayerVector::Visitor& visitor) {
2027 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07002028
2029 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07002030 for (; i < list.size(); i++) {
2031 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08002032 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07002033 break;
2034 }
chaviw4b129c22018-04-09 16:19:43 -07002035 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002036 }
chaviw4b129c22018-04-09 16:19:43 -07002037
chaviwa76b2712017-09-20 12:02:26 -07002038 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07002039 for (; i < list.size(); i++) {
2040 const auto& relative = list[i];
2041 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002042 }
2043}
2044
chaviw4b129c22018-04-09 16:19:43 -07002045std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2046 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2047 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2048
2049 std::vector<Layer*> layersInTree = {this};
2050 for (size_t i = 0; i < children.size(); i++) {
2051 const auto& child = children[i];
2052 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2053 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2054 }
2055
2056 return layersInTree;
2057}
2058
2059void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2060 const LayerVector::Visitor& visitor) {
2061 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2062 std::sort(layersInTree.begin(), layersInTree.end());
2063 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2064}
2065
Peiyong Linefefaac2018-08-17 12:27:51 -07002066ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08002067 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002068}
2069
Garfield Tan2c1782c2022-02-16 15:25:05 -08002070bool Layer::isTransformValid() const {
2071 float transformDet = getTransform().det();
2072 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2073}
2074
chaviw13fdc492017-06-27 12:40:18 -07002075half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002076 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002077
chaviw13fdc492017-06-27 12:40:18 -07002078 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2079 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002080}
Robert Carr6452f122017-03-21 10:41:29 -07002081
Vishnu Nair6213bd92020-05-08 17:42:25 -07002082ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002083 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002084 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2085 return fixedTransformHint;
2086 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002087 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002088 if (!p) return fixedTransformHint;
2089 return p->getFixedTransformHint();
2090}
2091
chaviw13fdc492017-06-27 12:40:18 -07002092half4 Layer::getColor() const {
2093 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002094 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002095}
Robert Carr6452f122017-03-21 10:41:29 -07002096
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002097int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002098 if (getDrawingState().backgroundBlurRadius == 0) {
2099 return 0;
2100 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002101
Vishnu Nair29810f72022-07-01 16:38:41 +00002102 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002103 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2104 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002105}
2106
Galia Peychevae0acf382021-04-12 21:22:34 +02002107const std::vector<BlurRegion> Layer::getBlurRegions() const {
2108 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002109 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002110 for (auto& region : regionsCopy) {
2111 region.alpha = region.alpha * layerAlpha;
2112 }
2113 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002114}
2115
Vishnu Naire14c6b32022-08-06 04:20:15 +00002116RoundedCornerState Layer::getRoundedCornerState() const {
Leon Scroggins IIIc1dbfcb2022-03-21 16:48:10 -04002117 // Today's DPUs cannot do rounded corners. If RenderEngine cannot render
2118 // protected content, remove rounded corners from protected content so it
2119 // can be rendered by the DPU.
2120 if (isProtected() && !mFlinger->getRenderEngine().supportsProtectedContent()) {
2121 return {};
2122 }
2123
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002124 // Get parent settings
2125 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002126 const auto& parent = mDrawingParent.promote();
2127 if (parent != nullptr) {
2128 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002129 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002130 ui::Transform t = getActiveTransform(getDrawingState());
2131 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002132 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002133 parentSettings.radius.x *= t.getScaleX();
2134 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002135 }
2136 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002137
2138 // Get layer settings
2139 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002140 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002141 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002142 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002143
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002144 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002145 // If the parent and the layer have rounded corner settings, use the parent settings if the
2146 // parent crop is entirely inside the layer crop.
2147 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2148 if (parentSettings.cropRect.left > layerCropRect.left &&
2149 parentSettings.cropRect.top > layerCropRect.top &&
2150 parentSettings.cropRect.right < layerCropRect.right &&
2151 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2152 return parentSettings;
2153 } else {
2154 return layerSettings;
2155 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002156 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002157 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002158 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002159 return parentSettings;
2160 }
2161 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002162}
2163
Robert Carr88b85e12022-03-21 15:47:35 -07002164bool Layer::findInHierarchy(const sp<Layer>& l) {
2165 if (l == this) {
2166 return true;
2167 }
2168 for (auto& child : mDrawingChildren) {
2169 if (child->findInHierarchy(l)) {
2170 return true;
2171 }
2172 }
2173 return false;
2174}
2175
Robert Carr1f0a16a2016-10-24 16:27:39 -07002176void Layer::commitChildList() {
2177 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2178 const auto& child = mCurrentChildren[i];
2179 child->commitChildList();
2180 }
2181 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002182 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002183 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2184 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2185 if (zOrderRelativeOf == nullptr) return;
2186 if (findInHierarchy(zOrderRelativeOf)) {
2187 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2188 zOrderRelativeOf->mName.c_str());
2189 ALOGE("Severing rel Z loop, potentially dangerous");
2190 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002191 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002192 }
2193 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002194}
2195
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002196
chaviw3277faf2021-05-19 16:45:23 -05002197void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002198 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002199 mDrawingState.touchableRegionCrop =
2200 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002201 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002202 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002203 setTransactionFlags(eTransactionNeeded);
2204}
2205
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002206perfetto::protos::LayerProto* Layer::writeToProto(perfetto::protos::LayersProto& layersProto,
2207 uint32_t traceFlags) {
2208 perfetto::protos::LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002209 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002210 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2211
Vishnu Nair00b90132021-11-05 14:03:40 -07002212 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nair2f65e972023-04-04 16:36:28 +00002213 ui::LayerStack layerStack =
2214 (mSnapshot) ? mSnapshot->outputFilter.layerStack : ui::INVALID_LAYER_STACK;
2215 writeCompositionStateToProto(layerProto, layerStack);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002216 }
2217
chaviw08f3cb22020-01-13 13:17:21 -08002218 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002219 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002220 }
chaviw6d89e2d2020-01-14 14:42:01 -08002221
2222 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002223}
2224
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002225void Layer::writeCompositionStateToProto(perfetto::protos::LayerProto* layerProto,
2226 ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002227 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002228 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +00002229
2230 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002231 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002232 const auto compositionType = getCompositionType(*display);
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002233 layerProto->set_hwc_composition_type(
2234 static_cast<perfetto::protos::HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +00002235 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +00002236 [&]() { return layerProto->mutable_visible_region(); });
2237 }
2238}
2239
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002240void Layer::writeToProtoDrawingState(perfetto::protos::LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002241 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002242 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002243 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002244 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002245 [&]() { return layerInfo->mutable_active_buffer(); });
2246 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2247 layerInfo->mutable_buffer_transform());
2248 }
2249 layerInfo->set_invalidate(contentDirty);
2250 layerInfo->set_is_protected(isProtected());
2251 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2252 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002253 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002254 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002255 layerInfo->set_corner_radius(
2256 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002257 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2258 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2259 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2260 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2261 [&]() { return layerInfo->mutable_position(); });
2262 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002263 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2264 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002265
Vishnu Nair00b90132021-11-05 14:03:40 -07002266 if (hasColorTransform()) {
2267 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002268 }
2269
Vishnu Nair60db8c02020-04-02 11:55:16 -07002270 LayerProtoHelper::writeToProto(mSourceBounds,
2271 [&]() { return layerInfo->mutable_source_bounds(); });
2272 LayerProtoHelper::writeToProto(mScreenBounds,
2273 [&]() { return layerInfo->mutable_screen_bounds(); });
2274 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2275 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2276 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002277}
2278
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002279void Layer::writeToProtoCommonState(perfetto::protos::LayerProto* layerInfo,
2280 LayerVector::StateSet stateSet, uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002281 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2282 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002283 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002284
chaviw766c9c52021-02-10 17:36:47 -08002285 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002286
Vishnu Nair00b90132021-11-05 14:03:40 -07002287 layerInfo->set_id(sequence);
2288 layerInfo->set_name(getName().c_str());
2289 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002290
Vishnu Nair00b90132021-11-05 14:03:40 -07002291 for (const auto& child : children) {
2292 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002293 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002294
Vishnu Nair00b90132021-11-05 14:03:40 -07002295 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2296 sp<Layer> strongRelative = weakRelative.promote();
2297 if (strongRelative != nullptr) {
2298 layerInfo->add_relatives(strongRelative->sequence);
2299 }
2300 }
2301
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002302 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002303 [&]() { return layerInfo->mutable_transparent_region(); });
2304
2305 layerInfo->set_layer_stack(getLayerStack().id);
2306 layerInfo->set_z(state.z);
2307
2308 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2309 return layerInfo->mutable_requested_position();
2310 });
2311
Vishnu Nair00b90132021-11-05 14:03:40 -07002312 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2313
2314 layerInfo->set_is_opaque(isOpaque(state));
2315
2316 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2317 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2318 LayerProtoHelper::writeToProto(state.color,
2319 [&]() { return layerInfo->mutable_requested_color(); });
2320 layerInfo->set_flags(state.flags);
2321
2322 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2323 layerInfo->mutable_requested_transform());
2324
2325 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2326 if (parent != nullptr) {
2327 layerInfo->set_parent(parent->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002328 }
2329
2330 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2331 if (zOrderRelativeOf != nullptr) {
2332 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002333 }
2334
2335 layerInfo->set_is_relative_of(state.isRelativeOf);
2336
2337 layerInfo->set_owner_uid(mOwnerUid);
2338
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002339 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002340 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002341 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002342 info = fillInputInfo(
2343 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002344 } else {
2345 info = state.inputInfo;
2346 }
2347
2348 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002349 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002350 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002351
Vishnu Nair00b90132021-11-05 14:03:40 -07002352 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002353 auto protoMap = layerInfo->mutable_metadata();
2354 for (const auto& entry : state.metadata.mMap) {
2355 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2356 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002357 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002358
2359 LayerProtoHelper::writeToProto(state.destinationFrame,
2360 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002361}
2362
Robert Carr2e102c92018-10-23 12:11:15 -07002363bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002364 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002365}
2366
Prabir Pradhan33da9462022-06-14 14:55:57 +00002367// Applies the given transform to the region, while protecting against overflows caused by any
2368// offsets. If applying the offset in the transform to any of the Rects in the region would result
2369// in an overflow, they are not added to the output Region.
2370static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2371 const std::string& debugWindowName) {
2372 // Round the translation using the same rounding strategy used by ui::Transform.
2373 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2374 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2375
2376 ui::Transform transformWithoutOffset = t;
2377 transformWithoutOffset.set(0.f, 0.f);
2378
2379 const Region transformed = transformWithoutOffset.transform(r);
2380
2381 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2382 Region ret;
2383 for (const auto& rect : transformed) {
2384 Rect newRect;
2385 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2386 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2387 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2388 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2389 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2390 debugWindowName.c_str());
2391 continue;
2392 }
2393 ret.orSelf(newRect);
2394 }
2395 return ret;
2396}
2397
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002398void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002399 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2400 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002401 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002402 }
2403
Chavi Weingarten7f019192023-08-08 20:39:01 +00002404 info.frame = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
chaviw1ff3d1e2020-07-01 15:53:47 -07002405
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002406 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002407 inputToLayer.set(inputBounds.left, inputBounds.top);
2408 const ui::Transform layerToScreen = getInputTransform();
2409 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002410
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002411 // InputDispatcher expects a display-to-input transform.
2412 info.transform = inputToDisplay.inverse();
2413
2414 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002415 info.touchableRegion =
2416 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002417}
2418
chaviw3277faf2021-05-19 16:45:23 -05002419void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002420 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002421 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002422 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002423 }
2424 if (p != nullptr) {
2425 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2426 }
2427}
2428
Vishnu Naira066d902021-09-13 18:40:17 -07002429gui::DropInputMode Layer::getDropInputMode() const {
2430 gui::DropInputMode mode = mDrawingState.dropInputMode;
2431 if (mode == gui::DropInputMode::ALL) {
2432 return mode;
2433 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002434 sp<Layer> parent = mDrawingParent.promote();
2435 if (parent) {
2436 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002437 if (parentMode != gui::DropInputMode::NONE) {
2438 return parentMode;
2439 }
2440 }
2441 return mode;
2442}
2443
2444void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002445 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002446 return;
2447 }
2448
2449 // Check if we need to drop input unconditionally
2450 gui::DropInputMode dropInputMode = getDropInputMode();
2451 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002452 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002453 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2454 return;
2455 }
2456
2457 // Check if we need to check if the window is obscured by parent
2458 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2459 return;
2460 }
2461
2462 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002463 sp<Layer> parent = mDrawingParent.promote();
2464 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002465 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002466 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2467 static_cast<float>(getAlpha()));
2468 }
2469
2470 // Check if the parent has cropped the buffer
2471 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2472 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002473 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002474 return;
2475 }
2476
2477 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2478 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2479 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2480 // match then the layer has not been cropped by its parents.
2481 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2482 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2483
2484 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002485 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002486 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2487 getDebugName());
2488 } else {
2489 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2490 // input if the window is obscured. This check should be done in surfaceflinger but the
2491 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2492 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002493 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002494 }
2495}
2496
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002497WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002498 if (!hasInputInfo()) {
2499 mDrawingState.inputInfo.name = getName();
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002500 mDrawingState.inputInfo.ownerUid = gui::Uid{mOwnerUid};
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00002501 mDrawingState.inputInfo.ownerPid = gui::Pid{mOwnerPid};
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002502 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002503 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002504 }
2505
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002506 const ui::Transform& displayTransform =
2507 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2508
chaviw3277faf2021-05-19 16:45:23 -05002509 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002510 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002511 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002512
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002513 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002514
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002515 if (displayArgs.transform == nullptr) {
2516 // Do not let the window receive touches if it is not associated with a valid display
2517 // transform. We still allow the window to receive keys and prevent ANRs.
2518 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2519 }
2520
Patrick Williams1caf3b72023-03-31 10:59:10 -05002521 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !isVisibleForInput());
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002522
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002523 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002524 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002525 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002526
Vishnu Nair16a938f2021-09-24 07:14:54 -07002527 // If the window will be blacked out on a display because the display does not have the secure
2528 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002529 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002530 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002531 }
2532
Vishnu Nairfed7c122023-03-18 01:54:43 +00002533 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002534 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002535 Rect inputBoundsInDisplaySpace;
2536 if (!cropLayer) {
2537 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2538 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2539 } else {
2540 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2541 inputBoundsInDisplaySpace =
2542 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2543 }
2544 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002545 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002546 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2547 Rect inputBoundsInDisplaySpace =
2548 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2549 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002550 }
2551
Winson Chunga30f7c92021-06-29 15:42:56 -07002552 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2553 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002554 if (isTrustedOverlay()) {
2555 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2556 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002557
chaviwaf87b3e2019-10-01 16:59:28 -07002558 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2559 // touches from going outside the cloned area.
2560 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002561 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002562 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2563 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002564 info.touchableRegion = info.touchableRegion.intersect(rect);
2565 }
2566 }
2567
Robert Carr720e5062018-07-30 17:45:14 -07002568 return info;
2569}
2570
Vishnu Nairfed7c122023-03-18 01:54:43 +00002571Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2572 const ui::Transform& screenToDisplay) {
2573 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2574 // frame and transform used for the layer, which determines the bounds and the coordinate space
2575 // within which the layer will receive input.
2576
2577 // Coordinate space definitions:
2578 // - display: The display device's coordinate space. Correlates to pixels on the display.
2579 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2580 // - layer: The coordinate space of this layer.
2581 // - input: The coordinate space in which this layer will receive input events. This could be
2582 // different than layer space if a surfaceInset is used, which changes the origin
2583 // of the input space.
2584
2585 // Crop the input bounds to ensure it is within the parent's bounds.
2586 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2587 const ui::Transform layerToScreen = getInputTransform();
2588 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2589 return Rect{layerToDisplay.transform(croppedInputBounds)};
2590}
2591
chaviwaf87b3e2019-10-01 16:59:28 -07002592sp<Layer> Layer::getClonedRoot() {
2593 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002594 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002595 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002596 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002597 return nullptr;
2598 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002599 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002600}
2601
Robert Carredd13602020-04-13 17:24:34 -07002602bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002603 return mDrawingState.inputInfo.token != nullptr ||
2604 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002605}
2606
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002607compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002608 const DisplayDevice* display) const {
2609 if (!display) return nullptr;
Lloyd Pique30db6402023-06-26 18:56:51 +00002610 if (!mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00002611 return display->getCompositionDisplay()->getOutputLayerForLayer(
2612 getCompositionEngineLayerFE());
2613 }
2614 sp<LayerFE> layerFE;
2615 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2616 for (auto& [p, layer] : mLayerFEs) {
2617 if (p == path) {
2618 layerFE = layer;
2619 }
2620 }
2621
2622 if (!layerFE) return nullptr;
2623 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002624}
2625
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002626compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
2627 const DisplayDevice* display, const frontend::LayerHierarchy::TraversalPath& path) const {
2628 if (!display) return nullptr;
Vishnu Naire9ee0002023-07-01 03:14:51 +00002629 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2630 return display->getCompositionDisplay()->getOutputLayerForLayer(
2631 getCompositionEngineLayerFE());
2632 }
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002633 sp<LayerFE> layerFE;
2634 for (auto& [p, layer] : mLayerFEs) {
2635 if (p == path) {
2636 layerFE = layer;
2637 }
2638 }
2639
2640 if (!layerFE) return nullptr;
2641 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
2642}
2643
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002644Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2645 const auto outputLayer = findOutputLayerForDisplay(display);
2646 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002647}
2648
Vishnu Nairde177252023-04-21 12:44:10 -07002649void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom, uint32_t mirrorRootId) {
2650 mSnapshot->path.id = clonedFrom->getSequence();
2651 mSnapshot->path.mirrorRootId = mirrorRootId;
2652
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002653 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002654 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002655 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2656 mPotentialCursor = clonedFrom->mPotentialCursor;
2657 mProtectedByApp = clonedFrom->mProtectedByApp;
2658 updateCloneBufferInfo();
2659}
2660
2661void Layer::updateCloneBufferInfo() {
2662 if (!isClone() || !isClonedFromAlive()) {
2663 return;
2664 }
2665
2666 sp<Layer> clonedFrom = getClonedFrom();
2667 mBufferInfo = clonedFrom->mBufferInfo;
2668 mSidebandStream = clonedFrom->mSidebandStream;
2669 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2670 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2671 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2672
2673 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2674 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2675 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2676 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2677 // the cloned drawingState again.
2678 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2679 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2680 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2681 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2682
2683 cloneDrawingState(clonedFrom.get());
2684
2685 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2686 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2687 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2688 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002689}
chaviw74b03172019-08-19 11:09:03 -07002690
Vishnu Nair3be61902023-04-26 19:47:29 -07002691bool Layer::updateMirrorInfo(const std::deque<Layer*>& cloneRootsPendingUpdates) {
chaviw74b03172019-08-19 11:09:03 -07002692 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2693 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2694 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2695 // that case, we want to delete the reference to the clone since we want it to get
2696 // destroyed. The root, this layer, will still be around since the client can continue
2697 // to hold a reference, but no cloned layers will be displayed.
2698 mClonedChild = nullptr;
Vishnu Nair3be61902023-04-26 19:47:29 -07002699 return true;
chaviw74b03172019-08-19 11:09:03 -07002700 }
2701
2702 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2703 // If the real layer exists and is in current state, add the clone as a child of the root.
2704 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2705 // copied to drawingState for the root layer. So the clonedChild is always removed from
2706 // drawingState and then needs to be added back each traversal.
2707 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2708 addChildToDrawing(mClonedChild);
2709 }
2710
2711 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002712 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002713 mClonedChild->updateClonedRelatives(clonedLayersMap);
Vishnu Nair3be61902023-04-26 19:47:29 -07002714
2715 for (Layer* root : cloneRootsPendingUpdates) {
2716 if (clonedLayersMap.find(sp<Layer>::fromExisting(root)) != clonedLayersMap.end()) {
2717 return false;
2718 }
2719 }
2720 return true;
chaviw74b03172019-08-19 11:09:03 -07002721}
2722
2723void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2724 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2725 // to the clone. If the real layer is no longer alive, continue traversing the children
2726 // since we may be able to pull out other children that are still alive.
2727 if (isClonedFromAlive()) {
2728 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002729 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002730 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002731 }
2732
2733 // The clone layer may have children in drawingState since they may have been created and
2734 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2735 // that already exist, since we can just re-use them.
2736 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2737 // not updated in the regular traversal. They are skipped since the root will lose the
2738 // reference to them when it copies its currentChildren to drawing.
2739 for (sp<Layer>& child : mDrawingChildren) {
2740 child->updateClonedDrawingState(clonedLayersMap);
2741 }
2742}
2743
2744void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2745 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2746 mDrawingChildren.clear();
2747
2748 if (!isClonedFromAlive()) {
2749 return;
2750 }
2751
2752 sp<Layer> clonedFrom = getClonedFrom();
2753 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2754 if (child == mirrorRoot) {
2755 // This is to avoid cyclical mirroring.
2756 continue;
2757 }
2758 sp<Layer> clonedChild = clonedLayersMap[child];
2759 if (clonedChild == nullptr) {
Vishnu Nairde177252023-04-21 12:44:10 -07002760 clonedChild = child->createClone(mirrorRoot->getSequence());
chaviw74b03172019-08-19 11:09:03 -07002761 clonedLayersMap[child] = clonedChild;
2762 }
2763 addChildToDrawing(clonedChild);
2764 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2765 }
2766}
2767
chaviwaf87b3e2019-10-01 16:59:28 -07002768void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2769 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2770 if (cropLayer != nullptr) {
2771 if (clonedLayersMap.count(cropLayer) == 0) {
2772 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2773 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002774 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002775 } else {
2776 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2777 mDrawingState.touchableRegionCrop = clonedCropLayer;
2778 }
2779 }
2780 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2781 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002782 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002783}
2784
2785void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002786 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002787 mDrawingState.zOrderRelatives.clear();
2788
2789 if (!isClonedFromAlive()) {
2790 return;
2791 }
2792
chaviwaf87b3e2019-10-01 16:59:28 -07002793 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002794 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002795 const sp<Layer>& relative = relativeWeak.promote();
2796 if (clonedLayersMap.count(relative) > 0) {
2797 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002798 mDrawingState.zOrderRelatives.add(clonedRelative);
2799 }
2800 }
2801
2802 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2803 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2804 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2805 // still traverse the children, but the layer with the missing relativeOf will not be shown
2806 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002807 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2808 if (clonedLayersMap.count(relativeOf) > 0) {
2809 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002810 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2811 }
2812
chaviwaf87b3e2019-10-01 16:59:28 -07002813 updateClonedInputInfo(clonedLayersMap);
2814
chaviw74b03172019-08-19 11:09:03 -07002815 for (sp<Layer>& child : mDrawingChildren) {
2816 child->updateClonedRelatives(clonedLayersMap);
2817 }
2818}
2819
2820void Layer::addChildToDrawing(const sp<Layer>& layer) {
2821 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002822 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002823}
2824
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002825bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002826 const State& s(mDrawingState);
2827 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2828 return true;
2829 }
2830
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002831 sp<Layer> parent = mDrawingParent.promote();
2832 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002833}
2834
Robert Carr6a0382d2021-07-01 15:57:17 -07002835void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2836 mClonedChild = clonedChild;
2837 mHadClonedChild = true;
Vishnu Nair3be61902023-04-26 19:47:29 -07002838 mFlinger->mLayerMirrorRoots.push_back(this);
Robert Carr6a0382d2021-07-01 15:57:17 -07002839}
2840
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002841bool Layer::setDropInputMode(gui::DropInputMode mode) {
2842 if (mDrawingState.dropInputMode == mode) {
2843 return false;
2844 }
2845 mDrawingState.dropInputMode = mode;
2846 return true;
2847}
2848
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002849void Layer::cloneDrawingState(const Layer* from) {
2850 mDrawingState = from->mDrawingState;
2851 // Skip callback info since they are not applicable for cloned layers.
2852 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002853 // TODO (b/238781169) currently broken for mirror layers because we do not
2854 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002855 mDrawingState.callbackHandles = {};
2856}
2857
Patrick Williamsbb25f802022-08-30 23:02:34 +00002858void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2859 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002860 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002861 if (!listener) {
2862 return;
2863 }
2864 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002865 uint32_t currentMaxAcquiredBufferCount =
2866 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002867 listener->onReleaseBuffer({buffer->getId(), framenumber},
2868 releaseFence ? releaseFence : Fence::NO_FENCE,
2869 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002870}
2871
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002872void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
2873 ui::LayerStack layerStack) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002874 // If we are displayed on multiple displays in a single composition cycle then we would
2875 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2876 // For example we can only use it if all the displays are client comp, and we need
2877 // to merge all the client comp fences. We could do this, but for now we just
2878 // disable the optimization when a layer is composed on multiple displays.
2879 if (mClearClientCompositionFenceOnLayerDisplayed) {
2880 mLastClientCompositionFence = nullptr;
2881 } else {
2882 mClearClientCompositionFenceOnLayerDisplayed = true;
2883 }
2884
2885 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2886 // buffer that was presented on this layer. The first transaction that came in this frame that
2887 // replaced the previous buffer on this layer needs this release fence, because the fence will
2888 // let the client know when that previous buffer is removed from the screen.
2889 //
2890 // Every other transaction on this layer does not need a release fence because no other
2891 // Transactions that were set on this layer this frame are going to have their preceding buffer
2892 // removed from the display this frame.
2893 //
2894 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2895 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2896 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2897 // the previous buffer will be released this frame. The third transaction also contains a
2898 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2899 // transaction will now no longer be presented so it is released immediately and the third
2900 // transaction doesn't need a previous release fence.
2901 sp<CallbackHandle> ch;
2902 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002903 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002904 ch = handle;
2905 break;
2906 }
2907 }
2908
2909 // Prevent tracing the same release multiple times.
2910 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2911 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2912 }
2913
2914 if (ch != nullptr) {
2915 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2916 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2917 ch->name = mName;
2918 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002919 mPreviouslyPresentedLayerStacks.push_back(layerStack);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002920}
2921
2922void Layer::onSurfaceFrameCreated(
2923 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2924 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2925 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2926 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2927 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002928 if (hasBufferOrSidebandStreamInDrawing()) {
2929 // Only log for layers with a buffer, since we expect the jank data to be drained for
2930 // these, while there may be no jank listeners for bufferless layers.
2931 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2932 mName.c_str());
2933 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2934 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2935 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002936 mPendingJankClassifications.pop_front();
2937 }
2938 mPendingJankClassifications.emplace_back(surfaceFrame);
2939}
2940
2941void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2942 for (const auto& handle : mDrawingState.callbackHandles) {
Lloyd Pique30db6402023-06-26 18:56:51 +00002943 if (mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -07002944 handle->transformHint = mTransformHint;
2945 } else {
2946 handle->transformHint = mSkipReportingTransformHint
2947 ? std::nullopt
2948 : std::make_optional<uint32_t>(mTransformHintLegacy);
2949 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002950 handle->dequeueReadyTime = dequeueReadyTime;
2951 handle->currentMaxAcquiredBufferCount =
2952 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2953 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2954 handle->previousReleaseCallbackId.framenumber);
2955 }
2956
2957 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002958 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002959 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2960 break;
2961 }
2962 }
2963
2964 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002965 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002966 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2967 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002968 mDrawingState.callbackHandles = {};
2969}
2970
2971bool Layer::willPresentCurrentTransaction() const {
2972 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2973 return (getSidebandStreamChanged() || getAutoRefresh() ||
2974 (mDrawingState.modified &&
2975 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2976}
2977
2978bool Layer::setTransform(uint32_t transform) {
2979 if (mDrawingState.bufferTransform == transform) return false;
2980 mDrawingState.bufferTransform = transform;
2981 mDrawingState.modified = true;
2982 setTransactionFlags(eTransactionNeeded);
2983 return true;
2984}
2985
2986bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2987 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2988 mDrawingState.sequence++;
2989 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2990 mDrawingState.modified = true;
2991 setTransactionFlags(eTransactionNeeded);
2992 return true;
2993}
2994
2995bool Layer::setBufferCrop(const Rect& bufferCrop) {
2996 if (mDrawingState.bufferCrop == bufferCrop) return false;
2997
2998 mDrawingState.sequence++;
2999 mDrawingState.bufferCrop = bufferCrop;
3000
3001 mDrawingState.modified = true;
3002 setTransactionFlags(eTransactionNeeded);
3003 return true;
3004}
3005
3006bool Layer::setDestinationFrame(const Rect& destinationFrame) {
3007 if (mDrawingState.destinationFrame == destinationFrame) return false;
3008
3009 mDrawingState.sequence++;
3010 mDrawingState.destinationFrame = destinationFrame;
3011
3012 mDrawingState.modified = true;
3013 setTransactionFlags(eTransactionNeeded);
3014 return true;
3015}
3016
3017// Translate destination frame into scale and position. If a destination frame is not set, use the
3018// provided scale and position
3019bool Layer::updateGeometry() {
3020 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
3021 mDrawingState.destinationFrame.isEmpty()) {
3022 // If destination frame is not set, use the requested transform set via
3023 // Layer::setPosition and Layer::setMatrix.
3024 return assignTransform(&mDrawingState.transform, mRequestedTransform);
3025 }
3026
3027 Rect destRect = mDrawingState.destinationFrame;
3028 int32_t destW = destRect.width();
3029 int32_t destH = destRect.height();
3030 if (destRect.left < 0) {
3031 destRect.left = 0;
3032 destRect.right = destW;
3033 }
3034 if (destRect.top < 0) {
3035 destRect.top = 0;
3036 destRect.bottom = destH;
3037 }
3038
3039 if (!mDrawingState.buffer) {
3040 ui::Transform t;
3041 t.set(destRect.left, destRect.top);
3042 return assignTransform(&mDrawingState.transform, t);
3043 }
3044
3045 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3046 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3047 // Undo any transformations on the buffer.
3048 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3049 std::swap(bufferWidth, bufferHeight);
3050 }
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003051 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003052 if (mDrawingState.transformToDisplayInverse) {
3053 if (invTransform & ui::Transform::ROT_90) {
3054 std::swap(bufferWidth, bufferHeight);
3055 }
3056 }
3057
3058 float sx = destW / static_cast<float>(bufferWidth);
3059 float sy = destH / static_cast<float>(bufferHeight);
3060 ui::Transform t;
3061 t.set(sx, 0, 0, sy);
3062 t.set(destRect.left, destRect.top);
3063 return assignTransform(&mDrawingState.transform, t);
3064}
3065
3066bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3067 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3068 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3069 return false;
3070 }
3071
3072 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3073
3074 mDrawingState.sequence++;
3075 mDrawingState.modified = true;
3076 setTransactionFlags(eTransactionNeeded);
3077
3078 return true;
3079}
3080
3081bool Layer::setPosition(float x, float y) {
3082 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3083 return false;
3084 }
3085
3086 mRequestedTransform.set(x, y);
3087
3088 mDrawingState.sequence++;
3089 mDrawingState.modified = true;
3090 setTransactionFlags(eTransactionNeeded);
3091
3092 return true;
3093}
3094
Dorin Drimuse5374e52023-08-02 17:52:43 +00003095void Layer::releasePreviousBuffer() {
3096 mReleasePreviousBuffer = true;
3097 if (!mBufferInfo.mBuffer ||
3098 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3099 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3100 // If mDrawingState has a buffer, and we are about to update again
3101 // before swapping to drawing state, then the first buffer will be
3102 // dropped and we should decrement the pending buffer count and
3103 // call any release buffer callbacks if set.
3104 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3105 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3106 mDrawingState.acquireFence);
3107 decrementPendingBufferCount();
3108 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3109 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3110 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX, systemTime());
3111 mDrawingState.bufferSurfaceFrameTX.reset();
3112 }
3113 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3114 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3115 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3116 mLastClientCompositionFence);
3117 mLastClientCompositionFence = nullptr;
3118 }
3119}
3120
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003121void Layer::resetDrawingStateBufferInfo() {
3122 mDrawingState.producerId = 0;
3123 mDrawingState.frameNumber = 0;
3124 mDrawingState.releaseBufferListener = nullptr;
3125 mDrawingState.buffer = nullptr;
3126 mDrawingState.acquireFence = sp<Fence>::make(-1);
3127 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3128 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3129 mDrawingState.releaseBufferEndpoint = nullptr;
3130}
3131
Patrick Williamsbb25f802022-08-30 23:02:34 +00003132bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3133 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3134 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003135 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003136 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003137
3138 const bool frameNumberChanged =
3139 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3140 const uint64_t frameNumber =
3141 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003142 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003143
3144 if (mDrawingState.buffer) {
Dorin Drimuse5374e52023-08-02 17:52:43 +00003145 releasePreviousBuffer();
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003146 } else if (buffer) {
Vishnu Nairc09c0232023-03-02 03:22:35 +00003147 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3148 // we don't want to incorrectly classify a frame if we miss the desired present time.
3149 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003150 }
3151
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003152 mDrawingState.desiredPresentTime = desiredPresentTime;
3153 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3154 mDrawingState.latchedVsyncId = info.vsyncId;
Ady Abraham55269162023-05-09 11:26:06 -07003155 mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003156 mDrawingState.modified = true;
3157 if (!buffer) {
3158 resetDrawingStateBufferInfo();
3159 setTransactionFlags(eTransactionNeeded);
3160 mDrawingState.bufferSurfaceFrameTX = nullptr;
3161 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3162 return true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003163 } else {
3164 // release sideband stream if it exists and a non null buffer is being set
3165 if (mDrawingState.sidebandStream != nullptr) {
3166 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3167 mDrawingState.sidebandStream = nullptr;
3168 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003169 }
3170
Vishnu Naird1f74982023-06-15 20:16:51 -07003171 if ((mDrawingState.producerId > bufferData.producerId) ||
3172 ((mDrawingState.producerId == bufferData.producerId) &&
3173 (mDrawingState.frameNumber > frameNumber))) {
3174 ALOGE("Out of order buffers detected for %s producedId=%d frameNumber=%" PRIu64
3175 " -> producedId=%d frameNumber=%" PRIu64,
3176 getDebugName(), mDrawingState.producerId, mDrawingState.frameNumber,
3177 bufferData.producerId, frameNumber);
3178 TransactionTraceWriter::getInstance().invoke("out_of_order_buffers_", /*overwrite=*/false);
3179 }
3180
liulijuneb489f62022-10-17 22:02:14 +08003181 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -07003182 mDrawingState.barrierProducerId =
3183 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003184 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -07003185 mDrawingState.barrierFrameNumber =
3186 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
3187
Patrick Williamsbb25f802022-08-30 23:02:34 +00003188 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3189 mDrawingState.buffer = std::move(buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003190 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3191 ? bufferData.acquireFence
3192 : Fence::NO_FENCE;
3193 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3194 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3195 // We latched this buffer unsiganled, so we need to pass the acquire fence
3196 // on the callback instead of just the acquire time, since it's unknown at
3197 // this point.
3198 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3199 } else {
3200 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3201 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003202 setTransactionFlags(eTransactionNeeded);
3203
3204 const int32_t layerId = getSequence();
3205 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3206 mOwnerUid, postTime, getGameMode());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003207
Lloyd Pique30db6402023-06-26 18:56:51 +00003208 if (mFlinger->mLegacyFrontEndEnabled) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003209 recordLayerHistoryBufferUpdate(getLayerProps());
3210 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003211
3212 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3213
3214 if (dequeueTime && *dequeueTime != 0) {
3215 const uint64_t bufferId = mDrawingState.buffer->getId();
3216 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3217 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3218 FrameTracer::FrameEvent::DEQUEUE);
3219 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3220 FrameTracer::FrameEvent::QUEUE);
3221 }
3222
3223 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
Arthur Hungc70bee22023-06-02 01:35:52 +00003224
3225 // If the layer had been updated a TextureView, this would make sure the present time could be
3226 // same to TextureView update when it's a small dirty, and get the correct heuristic rate.
3227 if (mFlinger->mScheduler->supportSmallDirtyDetection()) {
3228 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3229 mUsedVsyncIdForRefreshRateSelection = true;
3230 }
3231 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003232 return true;
3233}
3234
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003235void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3236 mDrawingState.desiredPresentTime = desiredPresentTime;
3237 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3238}
3239
3240void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps) {
Ady Abraham55269162023-05-09 11:26:06 -07003241 ATRACE_CALL();
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003242 const nsecs_t presentTime = [&] {
Ady Abraham55269162023-05-09 11:26:06 -07003243 if (!mDrawingState.isAutoTimestamp) {
3244 ATRACE_FORMAT_INSTANT("desiredPresentTime");
3245 return mDrawingState.desiredPresentTime;
3246 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003247
Ady Abraham55269162023-05-09 11:26:06 -07003248 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3249 const auto prediction =
3250 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3251 mDrawingState.latchedVsyncId);
3252 if (prediction.has_value()) {
3253 ATRACE_FORMAT_INSTANT("predictedPresentTime");
Arthur Hungc70bee22023-06-02 01:35:52 +00003254 mMaxTimeForUseVsyncId = prediction->presentTime +
3255 scheduler::LayerHistory::kMaxPeriodForHistory.count();
Ady Abraham55269162023-05-09 11:26:06 -07003256 return prediction->presentTime;
3257 }
3258 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003259
Arthur Hungc70bee22023-06-02 01:35:52 +00003260 if (!mFlinger->mScheduler->supportSmallDirtyDetection()) {
3261 return static_cast<nsecs_t>(0);
3262 }
3263
3264 // If the layer is not an application and didn't set an explicit rate or desiredPresentTime,
3265 // return "0" to tell the layer history that it will use the max refresh rate without
3266 // calculating the adaptive rate.
3267 if (mWindowType != WindowInfo::Type::APPLICATION &&
3268 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
3269 return static_cast<nsecs_t>(0);
3270 }
3271
3272 // Return the valid present time only when the layer potentially updated a TextureView so
3273 // LayerHistory could heuristically calculate the rate if the UI is continually updating.
3274 if (mUsedVsyncIdForRefreshRateSelection) {
3275 const auto prediction =
3276 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3277 mDrawingState.latchedVsyncId);
3278 if (prediction.has_value()) {
3279 if (mMaxTimeForUseVsyncId >= prediction->presentTime) {
3280 return prediction->presentTime;
3281 }
3282 mUsedVsyncIdForRefreshRateSelection = false;
3283 }
3284 }
3285
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003286 return static_cast<nsecs_t>(0);
3287 }();
Ady Abraham55269162023-05-09 11:26:06 -07003288
3289 if (ATRACE_ENABLED() && presentTime > 0) {
3290 const auto presentIn = TimePoint::fromNs(presentTime) - TimePoint::now();
3291 ATRACE_FORMAT_INSTANT("presentIn %s", to_string(presentIn).c_str());
3292 }
3293
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003294 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3295 scheduler::LayerHistory::LayerUpdateType::Buffer);
3296}
3297
3298void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps) {
3299 const nsecs_t presentTime =
3300 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
3301 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3302 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3303}
3304
Patrick Williamsbb25f802022-08-30 23:02:34 +00003305bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003306 if (mDrawingState.dataspace == dataspace) return false;
3307 mDrawingState.dataspace = dataspace;
3308 mDrawingState.modified = true;
3309 setTransactionFlags(eTransactionNeeded);
3310 return true;
3311}
3312
John Reck68796592023-01-25 13:47:12 -05003313bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07003314 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3315 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05003316 return false;
Sally Qi963049b2023-03-23 14:06:21 -07003317 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3318 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05003319 mDrawingState.modified = true;
3320 setTransactionFlags(eTransactionNeeded);
3321 return true;
3322}
3323
Alec Mourif4af03e2023-02-11 00:25:24 +00003324bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3325 if (mDrawingState.cachingHint == cachingHint) return false;
3326 mDrawingState.cachingHint = cachingHint;
3327 mDrawingState.modified = true;
3328 setTransactionFlags(eTransactionNeeded);
3329 return true;
3330}
3331
Patrick Williamsbb25f802022-08-30 23:02:34 +00003332bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3333 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3334 mDrawingState.hdrMetadata = hdrMetadata;
3335 mDrawingState.modified = true;
3336 setTransactionFlags(eTransactionNeeded);
3337 return true;
3338}
3339
3340bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003341 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003342 mDrawingState.surfaceDamageRegion = surfaceDamage;
3343 mDrawingState.modified = true;
3344 setTransactionFlags(eTransactionNeeded);
Arthur Hungc70bee22023-06-02 01:35:52 +00003345 setIsSmallDirty();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003346 return true;
3347}
3348
3349bool Layer::setApi(int32_t api) {
3350 if (mDrawingState.api == api) return false;
3351 mDrawingState.api = api;
3352 mDrawingState.modified = true;
3353 setTransactionFlags(eTransactionNeeded);
3354 return true;
3355}
3356
Dorin Drimuse5374e52023-08-02 17:52:43 +00003357bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream, const FrameTimelineInfo& info,
3358 nsecs_t postTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003359 if (mDrawingState.sidebandStream == sidebandStream) return false;
3360
3361 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3362 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3363 } else if (sidebandStream != nullptr) {
3364 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3365 }
3366
3367 mDrawingState.sidebandStream = sidebandStream;
3368 mDrawingState.modified = true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003369 if (sidebandStream != nullptr && mDrawingState.buffer != nullptr) {
3370 releasePreviousBuffer();
3371 resetDrawingStateBufferInfo();
3372 mDrawingState.bufferSurfaceFrameTX = nullptr;
3373 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3374 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003375 setTransactionFlags(eTransactionNeeded);
3376 if (!mSidebandStreamChanged.exchange(true)) {
3377 // mSidebandStreamChanged was false
3378 mFlinger->onLayerUpdate();
3379 }
3380 return true;
3381}
3382
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003383bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3384 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003385 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3386 if (handles.empty()) {
3387 mReleasePreviousBuffer = false;
3388 return false;
3389 }
3390
Pascal Muetschard81cef292023-02-06 12:18:52 +01003391 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003392 for (const auto& handle : handles) {
3393 // If this transaction set a buffer on this layer, release its previous buffer
3394 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3395
3396 // If this layer will be presented in this frame
3397 if (willPresent) {
3398 // If this transaction set an acquire fence on this layer, set its acquire time
3399 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3400 handle->frameNumber = mDrawingState.frameNumber;
3401
3402 // Store so latched time and release fence can be set
3403 mDrawingState.callbackHandles.push_back(handle);
3404
3405 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003406 // Queue this handle to be notified below.
3407 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003408 }
3409 }
3410
Pascal Muetschard81cef292023-02-06 12:18:52 +01003411 if (!remainingHandles.empty()) {
3412 // Notify the transaction completed threads these handles are done. These are only the
3413 // handles that were not added to the mDrawingState, which will be notified later.
3414 std::vector<JankData> jankData;
3415 transferAvailableJankData(remainingHandles, jankData);
3416 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3417 }
3418
Patrick Williamsbb25f802022-08-30 23:02:34 +00003419 mReleasePreviousBuffer = false;
3420 mCallbackHandleAcquireTimeOrFence = -1;
3421
3422 return willPresent;
3423}
3424
3425Rect Layer::getBufferSize(const State& /*s*/) const {
3426 // for buffer state layers we use the display frame size as the buffer size.
3427
3428 if (mBufferInfo.mBuffer == nullptr) {
3429 return Rect::INVALID_RECT;
3430 }
3431
3432 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3433 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3434
3435 // Undo any transformations on the buffer and return the result.
3436 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3437 std::swap(bufWidth, bufHeight);
3438 }
3439
3440 if (getTransformToDisplayInverse()) {
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003441 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003442 if (invTransform & ui::Transform::ROT_90) {
3443 std::swap(bufWidth, bufHeight);
3444 }
3445 }
3446
3447 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3448}
3449
3450FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3451 if (mBufferInfo.mBuffer == nullptr) {
3452 return parentBounds;
3453 }
3454
3455 return getBufferSize(getDrawingState()).toFloatRect();
3456}
3457
3458bool Layer::fenceHasSignaled() const {
3459 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3460 return true;
3461 }
3462
3463 const bool fenceSignaled =
3464 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3465 if (!fenceSignaled) {
3466 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3467 TimeStats::LatchSkipReason::LateAcquire);
3468 }
3469
3470 return fenceSignaled;
3471}
3472
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003473void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003474 for (const auto& handle : mDrawingState.callbackHandles) {
3475 handle->refreshStartTime = refreshStartTime;
3476 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003477}
3478
3479void Layer::setAutoRefresh(bool autoRefresh) {
3480 mDrawingState.autoRefresh = autoRefresh;
3481}
3482
3483bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3484 // 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 +00003485 auto* snapshot = editLayerSnapshot();
3486 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003487
3488 if (mSidebandStreamChanged.exchange(false)) {
3489 const State& s(getDrawingState());
3490 // mSidebandStreamChanged was true
3491 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003492 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003493 if (mSidebandStream != nullptr) {
3494 setTransactionFlags(eTransactionNeeded);
3495 mFlinger->setTransactionFlags(eTraversalNeeded);
3496 }
3497 recomputeVisibleRegions = true;
3498
3499 return true;
3500 }
3501 return false;
3502}
3503
3504bool Layer::hasFrameUpdate() const {
3505 const State& c(getDrawingState());
3506 return (mDrawingStateModified || mDrawingState.modified) &&
3507 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3508}
3509
Vishnu Naird47bcee2023-02-24 18:08:51 +00003510void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003511 const State& s(getDrawingState());
3512
3513 if (!s.buffer) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003514 if (bgColorOnly || mBufferInfo.mBuffer) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003515 for (auto& handle : mDrawingState.callbackHandles) {
3516 handle->latchTime = latchTime;
3517 }
3518 }
3519 return;
3520 }
3521
3522 for (auto& handle : mDrawingState.callbackHandles) {
3523 if (handle->frameNumber == mDrawingState.frameNumber) {
3524 handle->latchTime = latchTime;
3525 }
3526 }
3527
3528 const int32_t layerId = getSequence();
3529 const uint64_t bufferId = mDrawingState.buffer->getId();
3530 const uint64_t frameNumber = mDrawingState.frameNumber;
3531 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3532 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3533 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3534
3535 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3536 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3537 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3538 FrameTracer::FrameEvent::LATCH);
3539
3540 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3541 if (bufferSurfaceFrame != nullptr &&
3542 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3543 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3544 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3545 // are processing the next state.
3546 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3547 mDrawingState.acquireFenceTime->getSignalTime(),
3548 latchTime);
3549 mDrawingState.bufferSurfaceFrameTX.reset();
3550 }
3551
3552 std::deque<sp<CallbackHandle>> remainingHandles;
3553 mFlinger->getTransactionCallbackInvoker()
3554 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3555 mDrawingState.callbackHandles = remainingHandles;
3556
3557 mDrawingStateModified = false;
3558}
3559
3560void Layer::gatherBufferInfo() {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003561 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3562 mPreviousReleaseBufferEndpoint = mBufferInfo.mReleaseBufferEndpoint;
3563 if (!mDrawingState.buffer) {
3564 mBufferInfo = {};
3565 return;
3566 }
3567
3568 if ((!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer))) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003569 decrementPendingBufferCount();
3570 }
3571
Patrick Williamsbb25f802022-08-30 23:02:34 +00003572 mBufferInfo.mBuffer = mDrawingState.buffer;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003573 mBufferInfo.mReleaseBufferEndpoint = mDrawingState.releaseBufferEndpoint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003574 mBufferInfo.mFence = mDrawingState.acquireFence;
3575 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3576 mBufferInfo.mPixelFormat =
3577 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3578 mBufferInfo.mFrameLatencyNeeded = true;
3579 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3580 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3581 mBufferInfo.mFence = mDrawingState.acquireFence;
3582 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3583 auto lastDataspace = mBufferInfo.mDataspace;
3584 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003585 if (mBufferInfo.mBuffer != nullptr) {
3586 auto& mapper = GraphicBufferMapper::get();
3587 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
3588 // and don't need to possibly remaps buffers.
3589 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
3590 status_t err = OK;
3591 {
3592 ATRACE_NAME("getDataspace");
3593 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
3594 }
3595 if (err != OK || dataspace != mBufferInfo.mDataspace) {
3596 {
3597 ATRACE_NAME("setDataspace");
3598 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
3599 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
3600 }
3601
3602 // Some GPU drivers may cache gralloc metadata which means before we composite we need
3603 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
3604 // compatible with old vendors, with a ticking clock.
3605 static const int32_t kVendorVersion =
3606 base::GetIntProperty("ro.vndk.version", __ANDROID_API_FUTURE__);
3607 if (const auto format =
3608 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
3609 mBufferInfo.mBuffer->getPixelFormat());
3610 err == OK && kVendorVersion < __ANDROID_API_U__ &&
3611 (format ==
3612 aidl::android::hardware::graphics::common::PixelFormat::
3613 IMPLEMENTATION_DEFINED ||
3614 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
3615 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
3616 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
3617 mBufferInfo.mBuffer->remapBuffer();
3618 }
3619 }
3620 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003621 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003622 mFlinger->mHdrLayerInfoChanged = true;
3623 }
Sally Qi963049b2023-03-23 14:06:21 -07003624 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3625 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05003626 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003627 }
3628 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3629 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3630 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3631 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3632 mBufferInfo.mApi = mDrawingState.api;
3633 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003634}
3635
3636Rect Layer::computeBufferCrop(const State& s) {
3637 if (s.buffer && !s.bufferCrop.isEmpty()) {
3638 Rect bufferCrop;
3639 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3640 return bufferCrop;
3641 } else if (s.buffer) {
3642 return s.buffer->getBounds();
3643 } else {
3644 return s.bufferCrop;
3645 }
3646}
3647
Vishnu Nairde177252023-04-21 12:44:10 -07003648sp<Layer> Layer::createClone(uint32_t mirrorRootId) {
Kean Mariotti4ba343c2023-04-19 13:31:02 +00003649 surfaceflinger::LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0,
3650 LayerMetadata());
Patrick Williams83f36b22022-09-14 17:57:35 +00003651 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Vishnu Nairde177252023-04-21 12:44:10 -07003652 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this), mirrorRootId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003653 return layer;
3654}
3655
Patrick Williamsbb25f802022-08-30 23:02:34 +00003656void Layer::decrementPendingBufferCount() {
3657 int32_t pendingBuffers = --mPendingBufferTransactions;
3658 tracePendingBufferCount(pendingBuffers);
3659}
3660
3661void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3662 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3663}
3664
3665/*
3666 * We don't want to send the layer's transform to input, but rather the
3667 * parent's transform. This is because Layer's transform is
3668 * information about how the buffer is placed on screen. The parent's
3669 * transform makes more sense to send since it's information about how the
3670 * layer is placed on screen. This transform is used by input to determine
3671 * how to go from screen space back to window space.
3672 */
3673ui::Transform Layer::getInputTransform() const {
3674 if (!hasBufferOrSidebandStream()) {
3675 return getTransform();
3676 }
3677 sp<Layer> parent = mDrawingParent.promote();
3678 if (parent == nullptr) {
3679 return ui::Transform();
3680 }
3681
3682 return parent->getTransform();
3683}
3684
3685/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003686 * Returns the bounds used to fill the input frame and the touchable region.
3687 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003688 * Similar to getInputTransform, we need to update the bounds to include the transform.
3689 * This is because bounds don't include the buffer transform, where the input assumes
3690 * that's already included.
3691 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003692std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3693 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3694 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3695 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3696 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3697 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003698 }
3699
Vishnu Nairfed7c122023-03-18 01:54:43 +00003700 bool inputBoundsValid = croppedBufferSize.isValid();
3701 if (!inputBoundsValid) {
3702 /**
3703 * Input bounds are based on the layer crop or buffer size. But if we are using
3704 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3705 * we can use the parent bounds as the input bounds if the layer does not have buffer
3706 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3707 * use the parent bounds. A layer without a buffer can get input. So when a window is
3708 * initially added, its touchable region can fill its parent layer bounds and that can
3709 * have negative consequences.
3710 */
3711 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003712 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003713
3714 // Clamp surface inset to the input bounds.
3715 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3716 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3717 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3718
3719 // Apply the insets to the input bounds.
3720 inputBounds.left += xSurfaceInset;
3721 inputBounds.top += ySurfaceInset;
3722 inputBounds.right -= xSurfaceInset;
3723 inputBounds.bottom -= ySurfaceInset;
3724
3725 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003726}
3727
Ady Abraham005398b2023-06-05 13:59:41 -07003728bool Layer::isSimpleBufferUpdate(const layer_state_t& s) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003729 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3730
3731 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3732 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3733 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3734 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3735 layer_state_t::eReparent;
3736
Patrick Williamsbb25f802022-08-30 23:02:34 +00003737 if ((s.what & requiredFlags) != requiredFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003738 ATRACE_FORMAT_INSTANT("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3739 (s.what | requiredFlags) & ~s.what);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003740 return false;
3741 }
3742
3743 if (s.what & deniedFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003744 ATRACE_FORMAT_INSTANT("%s: false [has denied flags 0x%" PRIx64 "]", __func__,
3745 s.what & deniedFlags);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003746 return false;
3747 }
3748
Patrick Williamsbb25f802022-08-30 23:02:34 +00003749 if (s.what & layer_state_t::ePositionChanged) {
3750 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
Ady Abraham005398b2023-06-05 13:59:41 -07003751 ATRACE_FORMAT_INSTANT("%s: false [ePositionChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003752 return false;
3753 }
3754 }
3755
3756 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003757 if (mDrawingState.color.a != s.color.a) {
Ady Abraham005398b2023-06-05 13:59:41 -07003758 ATRACE_FORMAT_INSTANT("%s: false [eAlphaChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003759 return false;
3760 }
3761 }
3762
3763 if (s.what & layer_state_t::eColorTransformChanged) {
3764 if (mDrawingState.colorTransform != s.colorTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003765 ATRACE_FORMAT_INSTANT("%s: false [eColorTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003766 return false;
3767 }
3768 }
3769
3770 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003771 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Ady Abraham005398b2023-06-05 13:59:41 -07003772 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundColorChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003773 return false;
3774 }
3775 }
3776
3777 if (s.what & layer_state_t::eMatrixChanged) {
3778 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3779 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3780 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3781 mRequestedTransform.dsdy() != s.matrix.dsdy) {
Ady Abraham005398b2023-06-05 13:59:41 -07003782 ATRACE_FORMAT_INSTANT("%s: false [eMatrixChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003783 return false;
3784 }
3785 }
3786
3787 if (s.what & layer_state_t::eCornerRadiusChanged) {
3788 if (mDrawingState.cornerRadius != s.cornerRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003789 ATRACE_FORMAT_INSTANT("%s: false [eCornerRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003790 return false;
3791 }
3792 }
3793
3794 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3795 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
Ady Abraham005398b2023-06-05 13:59:41 -07003796 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003797 return false;
3798 }
3799 }
3800
Vishnu Nairbbceb462022-10-10 04:52:13 +00003801 if (s.what & layer_state_t::eBufferTransformChanged) {
3802 if (mDrawingState.bufferTransform != s.bufferTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003803 ATRACE_FORMAT_INSTANT("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003804 return false;
3805 }
3806 }
3807
3808 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3809 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
Ady Abraham005398b2023-06-05 13:59:41 -07003810 ATRACE_FORMAT_INSTANT("%s: false [eTransformToDisplayInverseChanged changed]",
3811 __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003812 return false;
3813 }
3814 }
3815
3816 if (s.what & layer_state_t::eCropChanged) {
3817 if (mDrawingState.crop != s.crop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003818 ATRACE_FORMAT_INSTANT("%s: false [eCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003819 return false;
3820 }
3821 }
3822
3823 if (s.what & layer_state_t::eDataspaceChanged) {
3824 if (mDrawingState.dataspace != s.dataspace) {
Ady Abraham005398b2023-06-05 13:59:41 -07003825 ATRACE_FORMAT_INSTANT("%s: false [eDataspaceChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003826 return false;
3827 }
3828 }
3829
3830 if (s.what & layer_state_t::eHdrMetadataChanged) {
3831 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
Ady Abraham005398b2023-06-05 13:59:41 -07003832 ATRACE_FORMAT_INSTANT("%s: false [eHdrMetadataChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003833 return false;
3834 }
3835 }
3836
3837 if (s.what & layer_state_t::eSidebandStreamChanged) {
3838 if (mDrawingState.sidebandStream != s.sidebandStream) {
Ady Abraham005398b2023-06-05 13:59:41 -07003839 ATRACE_FORMAT_INSTANT("%s: false [eSidebandStreamChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003840 return false;
3841 }
3842 }
3843
3844 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3845 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
Ady Abraham005398b2023-06-05 13:59:41 -07003846 ATRACE_FORMAT_INSTANT("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003847 return false;
3848 }
3849 }
3850
3851 if (s.what & layer_state_t::eShadowRadiusChanged) {
3852 if (mDrawingState.shadowRadius != s.shadowRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003853 ATRACE_FORMAT_INSTANT("%s: false [eShadowRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003854 return false;
3855 }
3856 }
3857
3858 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3859 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
Ady Abraham005398b2023-06-05 13:59:41 -07003860 ATRACE_FORMAT_INSTANT("%s: false [eFixedTransformHintChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003861 return false;
3862 }
3863 }
3864
3865 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3866 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
Ady Abraham005398b2023-06-05 13:59:41 -07003867 ATRACE_FORMAT_INSTANT("%s: false [eTrustedOverlayChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003868 return false;
3869 }
3870 }
3871
3872 if (s.what & layer_state_t::eStretchChanged) {
3873 StretchEffect temp = s.stretchEffect;
3874 temp.sanitize();
3875 if (mDrawingState.stretchEffect != temp) {
Ady Abraham005398b2023-06-05 13:59:41 -07003876 ATRACE_FORMAT_INSTANT("%s: false [eStretchChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003877 return false;
3878 }
3879 }
3880
3881 if (s.what & layer_state_t::eBufferCropChanged) {
3882 if (mDrawingState.bufferCrop != s.bufferCrop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003883 ATRACE_FORMAT_INSTANT("%s: false [eBufferCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003884 return false;
3885 }
3886 }
3887
3888 if (s.what & layer_state_t::eDestinationFrameChanged) {
3889 if (mDrawingState.destinationFrame != s.destinationFrame) {
Ady Abraham005398b2023-06-05 13:59:41 -07003890 ATRACE_FORMAT_INSTANT("%s: false [eDestinationFrameChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003891 return false;
3892 }
3893 }
3894
3895 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3896 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
Ady Abraham005398b2023-06-05 13:59:41 -07003897 ATRACE_FORMAT_INSTANT("%s: false [eDimmingEnabledChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003898 return false;
3899 }
3900 }
3901
John Reck68796592023-01-25 13:47:12 -05003902 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07003903 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
3904 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
Ady Abraham005398b2023-06-05 13:59:41 -07003905 ATRACE_FORMAT_INSTANT("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05003906 return false;
3907 }
3908 }
3909
Patrick Williamsbb25f802022-08-30 23:02:34 +00003910 return true;
3911}
3912
Vishnu Naire14c6b32022-08-06 04:20:15 +00003913sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003914 // 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 +00003915 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003916}
3917
Vishnu Naire14c6b32022-08-06 04:20:15 +00003918const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003919 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003920}
3921
Vishnu Naire14c6b32022-08-06 04:20:15 +00003922LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003923 return mSnapshot.get();
3924}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003925
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003926std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3927 return std::move(mSnapshot);
3928}
3929
3930void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3931 mSnapshot = std::move(snapshot);
3932}
3933
Patrick Williamsbb25f802022-08-30 23:02:34 +00003934const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003935 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003936}
3937
Patrick Williams7584c6a2022-10-29 02:10:58 +00003938sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003939 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003940 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3941 return result;
3942}
3943
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003944sp<LayerFE> Layer::getCompositionEngineLayerFE(
3945 const frontend::LayerHierarchy::TraversalPath& path) {
3946 for (auto& [p, layerFE] : mLayerFEs) {
3947 if (p == path) {
3948 return layerFE;
3949 }
3950 }
3951 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3952 mLayerFEs.emplace_back(path, layerFE);
3953 return layerFE;
3954}
3955
Patrick Williamsbb25f802022-08-30 23:02:34 +00003956void Layer::useSurfaceDamage() {
3957 if (mFlinger->mForceFullDamage) {
3958 surfaceDamageRegion = Region::INVALID_REGION;
3959 } else {
3960 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3961 }
3962}
3963
3964void Layer::useEmptyDamage() {
3965 surfaceDamageRegion.clear();
3966}
3967
3968bool Layer::isOpaque(const Layer::State& s) const {
3969 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3970 // layer's opaque flag.
3971 if (!hasSomethingToDraw()) {
3972 return false;
3973 }
3974
3975 // if the layer has the opaque flag, then we're always opaque
3976 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3977 return true;
3978 }
3979
3980 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003981 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003982 return true;
3983 }
3984
3985 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3986 return fillsColor() && getAlpha() == 1.0_hf;
3987}
3988
3989bool Layer::canReceiveInput() const {
3990 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3991}
3992
3993bool Layer::isVisible() const {
3994 if (!hasSomethingToDraw()) {
3995 return false;
3996 }
3997
3998 if (isHiddenByPolicy()) {
3999 return false;
4000 }
4001
4002 return getAlpha() > 0.0f || hasBlur();
4003}
4004
4005void Layer::onPostComposition(const DisplayDevice* display,
4006 const std::shared_ptr<FenceTime>& glDoneFence,
4007 const std::shared_ptr<FenceTime>& presentFence,
4008 const CompositorTiming& compositorTiming) {
4009 // mFrameLatencyNeeded is true when a new frame was latched for the
4010 // composition.
4011 if (!mBufferInfo.mFrameLatencyNeeded) return;
4012
4013 for (const auto& handle : mDrawingState.callbackHandles) {
4014 handle->gpuCompositionDoneFence = glDoneFence;
4015 handle->compositorTiming = compositorTiming;
4016 }
4017
4018 // Update mFrameTracker.
4019 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
4020 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
4021
4022 const int32_t layerId = getSequence();
4023 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
4024
4025 const auto outputLayer = findOutputLayerForDisplay(display);
4026 if (outputLayer && outputLayer->requiresClientComposition()) {
4027 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
4028 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4029 clientCompositionTimestamp,
4030 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
4031 // Update the SurfaceFrames in the drawing state
4032 if (mDrawingState.bufferSurfaceFrameTX) {
4033 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
4034 }
4035 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
4036 surfaceFrame->setGpuComposition();
4037 }
4038 }
4039
4040 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
4041 if (frameReadyFence->isValid()) {
4042 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
4043 } else {
4044 // There was no fence for this frame, so assume that it was ready
4045 // to be presented at the desired present time.
4046 mFrameTracker.setFrameReadyTime(desiredPresentTime);
4047 }
4048
4049 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08004050 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004051 const std::optional<Fps> renderRate =
4052 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
4053
Alec Mouri7c1d8b52023-08-29 20:14:46 +00004054 const auto vote = frameRateToSetFrameRateVotePayload(getFrameRateForLayerTree());
Patrick Williamsbb25f802022-08-30 23:02:34 +00004055 const auto gameMode = getGameMode();
4056
4057 if (presentFence->isValid()) {
4058 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
4059 refreshRate, renderRate, vote, gameMode);
4060 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4061 presentFence,
4062 FrameTracer::FrameEvent::PRESENT_FENCE);
4063 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
4064 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
4065 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04004066 // The HWC doesn't support present fences, so use the present timestamp instead.
4067 const nsecs_t presentTimestamp =
4068 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
4069
4070 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
4071 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
4072 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
4073
Patrick Williamsbb25f802022-08-30 23:02:34 +00004074 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
4075 refreshRate, renderRate, vote, gameMode);
4076 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
4077 mCurrentFrameNumber, actualPresentTime,
4078 FrameTracer::FrameEvent::PRESENT_FENCE);
4079 mFrameTracker.setActualPresentTime(actualPresentTime);
4080 }
4081 }
4082
4083 mFrameTracker.advanceFrame();
4084 mBufferInfo.mFrameLatencyNeeded = false;
4085}
4086
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004087bool Layer::willReleaseBufferOnLatch() const {
4088 return !mDrawingState.buffer && mBufferInfo.mBuffer;
4089}
4090
Patrick Williamsbb25f802022-08-30 23:02:34 +00004091bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00004092 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
4093 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
4094}
4095
4096bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004097 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
4098 getDrawingState().frameNumber);
4099
4100 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
4101
4102 if (refreshRequired) {
4103 return refreshRequired;
4104 }
4105
4106 // If the head buffer's acquire fence hasn't signaled yet, return and
4107 // try again later
4108 if (!fenceHasSignaled()) {
4109 ATRACE_NAME("!fenceHasSignaled()");
4110 mFlinger->onLayerUpdate();
4111 return false;
4112 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00004113 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004114
4115 // Capture the old state of the layer for comparisons later
4116 BufferInfo oldBufferInfo = mBufferInfo;
4117 const bool oldOpacity = isOpaque(mDrawingState);
4118 mPreviousFrameNumber = mCurrentFrameNumber;
4119 mCurrentFrameNumber = mDrawingState.frameNumber;
4120 gatherBufferInfo();
4121
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004122 if (mBufferInfo.mBuffer) {
4123 // We latched a buffer that will be presented soon. Clear the previously presented layer
4124 // stack list.
4125 mPreviouslyPresentedLayerStacks.clear();
4126 }
4127
4128 if (mDrawingState.buffer == nullptr) {
4129 const bool bufferReleased = oldBufferInfo.mBuffer != nullptr;
4130 recomputeVisibleRegions = bufferReleased;
4131 return bufferReleased;
4132 }
4133
Patrick Williamsbb25f802022-08-30 23:02:34 +00004134 if (oldBufferInfo.mBuffer == nullptr) {
4135 // the first time we receive a buffer, we need to trigger a
4136 // geometry invalidation.
4137 recomputeVisibleRegions = true;
4138 }
4139
4140 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
4141 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
4142 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
4143 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
4144 recomputeVisibleRegions = true;
4145 }
4146
4147 if (oldBufferInfo.mBuffer != nullptr) {
4148 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
4149 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
4150 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
4151 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
4152 recomputeVisibleRegions = true;
4153 }
4154 }
4155
4156 if (oldOpacity != isOpaque(mDrawingState)) {
4157 recomputeVisibleRegions = true;
4158 }
4159
4160 return true;
4161}
4162
4163bool Layer::hasReadyFrame() const {
4164 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4165}
4166
4167bool Layer::isProtected() const {
4168 return (mBufferInfo.mBuffer != nullptr) &&
4169 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4170}
4171
Patrick Williamsbb25f802022-08-30 23:02:34 +00004172void Layer::latchAndReleaseBuffer() {
4173 if (hasReadyFrame()) {
4174 bool ignored = false;
4175 latchBuffer(ignored, systemTime());
4176 }
4177 releasePendingBuffer(systemTime());
4178}
4179
4180PixelFormat Layer::getPixelFormat() const {
4181 return mBufferInfo.mPixelFormat;
4182}
4183
4184bool Layer::getTransformToDisplayInverse() const {
4185 return mBufferInfo.mTransformToDisplayInverse;
4186}
4187
4188Rect Layer::getBufferCrop() const {
4189 // this is the crop rectangle that applies to the buffer
4190 // itself (as opposed to the window)
4191 if (!mBufferInfo.mCrop.isEmpty()) {
4192 // if the buffer crop is defined, we use that
4193 return mBufferInfo.mCrop;
4194 } else if (mBufferInfo.mBuffer != nullptr) {
4195 // otherwise we use the whole buffer
4196 return mBufferInfo.mBuffer->getBounds();
4197 } else {
4198 // if we don't have a buffer yet, we use an empty/invalid crop
4199 return Rect();
4200 }
4201}
4202
4203uint32_t Layer::getBufferTransform() const {
4204 return mBufferInfo.mTransform;
4205}
4206
4207ui::Dataspace Layer::getDataSpace() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004208 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4209}
4210
4211ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4212 ui::Dataspace updatedDataspace = dataspace;
4213 // translate legacy dataspaces to modern dataspaces
4214 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00004215 // Treat unknown dataspaces as V0_sRGB
4216 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00004217 case ui::Dataspace::SRGB:
4218 updatedDataspace = ui::Dataspace::V0_SRGB;
4219 break;
4220 case ui::Dataspace::SRGB_LINEAR:
4221 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4222 break;
4223 case ui::Dataspace::JFIF:
4224 updatedDataspace = ui::Dataspace::V0_JFIF;
4225 break;
4226 case ui::Dataspace::BT601_625:
4227 updatedDataspace = ui::Dataspace::V0_BT601_625;
4228 break;
4229 case ui::Dataspace::BT601_525:
4230 updatedDataspace = ui::Dataspace::V0_BT601_525;
4231 break;
4232 case ui::Dataspace::BT709:
4233 updatedDataspace = ui::Dataspace::V0_BT709;
4234 break;
4235 default:
4236 break;
4237 }
4238
4239 return updatedDataspace;
4240}
4241
4242sp<GraphicBuffer> Layer::getBuffer() const {
4243 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4244}
4245
Vishnu Nairb76d99a2023-03-19 18:22:31 -07004246void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4247 mTransformHintLegacy = getFixedTransformHint();
4248 if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4249 mTransformHintLegacy = displayTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004250 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004251 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004252}
4253
4254const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4255 return mBufferInfo.mBuffer;
4256}
4257
4258bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004259 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004260 return false;
4261 }
4262
4263 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004264 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004265 mDrawingState.modified = true;
4266 setTransactionFlags(eTransactionNeeded);
4267 return true;
4268}
4269
4270bool Layer::fillsColor() const {
4271 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4272 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4273}
4274
4275bool Layer::hasBlur() const {
4276 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4277}
4278
Vishnu Nairba354102022-08-01 00:14:18 +00004279void Layer::updateSnapshot(bool updateGeometry) {
4280 if (!getCompositionEngineLayerFE()) {
4281 return;
4282 }
4283
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004284 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004285 if (updateGeometry) {
4286 prepareBasicGeometryCompositionState();
4287 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004288 snapshot->roundedCorner = getRoundedCornerState();
4289 snapshot->stretchEffect = getStretchEffect();
4290 snapshot->transformedBounds = mScreenBounds;
4291 if (mEffectiveShadowRadius > 0.f) {
4292 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4293
4294 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4295 // it if transparent regions are present. This may not be necessary since shadows are
4296 // typically cast by layers without transparent regions.
4297 snapshot->shadowSettings.boundaries = mBounds;
4298
4299 const float casterAlpha = snapshot->alpha;
4300 const bool casterIsOpaque =
4301 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4302
4303 // If the casting layer is translucent, we need to fill in the shadow underneath the
4304 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4305 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4306 snapshot->shadowSettings.ambientColor *= casterAlpha;
4307 snapshot->shadowSettings.spotColor *= casterAlpha;
4308 }
4309 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004310 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004311 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004312 snapshot->layerOpaqueFlagSet =
4313 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004314 sp<Layer> p = mDrawingParent.promote();
4315 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004316 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004317 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004318 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004319 }
4320 snapshot->bufferSize = getBufferSize(mDrawingState);
4321 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004322 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004323 preparePerFrameCompositionState();
4324}
4325
Vishnu Naire14c6b32022-08-06 04:20:15 +00004326void Layer::updateChildrenSnapshots(bool updateGeometry) {
4327 for (const sp<Layer>& child : mDrawingChildren) {
4328 child->updateSnapshot(updateGeometry);
4329 child->updateChildrenSnapshots(updateGeometry);
4330 }
4331}
4332
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004333void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4334 mSnapshot->layerMetadata = parentMetadata;
4335 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4336 for (const sp<Layer>& child : mDrawingChildren) {
4337 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4338 }
4339}
4340
4341void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4342 std::unordered_set<Layer*>& visited) {
4343 if (visited.find(this) != visited.end()) {
4344 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4345 return;
4346 }
4347 visited.insert(this);
4348
4349 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4350
4351 if (mDrawingState.zOrderRelatives.empty()) {
4352 return;
4353 }
4354 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4355 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4356 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4357 sp<Layer> relative = weakRelative.promote();
4358 if (!relative) {
4359 continue;
4360 }
4361 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4362 }
4363}
4364
Chavi Weingarten328a8312023-01-26 21:17:52 +00004365bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004366 TrustedPresentationListener const& listener) {
4367 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4368 mTrustedPresentationListener = listener;
4369 mTrustedPresentationThresholds = thresholds;
4370 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4371 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4372 mFlinger->mNumTrustedPresentationListeners++;
4373 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4374 mFlinger->mNumTrustedPresentationListeners--;
4375 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004376
4377 // Reset trusted presentation states to ensure we start the time again.
4378 mEnteredTrustedPresentationStateTime = -1;
4379 mLastReportedTrustedPresentationState = false;
4380 mLastComputedTrustedPresentationState = false;
4381
4382 // If there's a new trusted presentation listener, the code needs to go through the composite
4383 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4384 // we're already in the requested state.
4385 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004386}
4387
Vishnu Naira156f482023-02-22 00:23:38 +00004388void Layer::updateLastLatchTime(nsecs_t latchTime) {
4389 mLastLatchTime = latchTime;
4390}
4391
Arthur Hungc70bee22023-06-02 01:35:52 +00004392void Layer::setIsSmallDirty() {
4393 if (!mFlinger->mScheduler->supportSmallDirtyDetection()) {
4394 return;
4395 }
4396
4397 if (mWindowType != WindowInfo::Type::APPLICATION &&
4398 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
4399 return;
4400 }
4401 Rect bounds = mDrawingState.surfaceDamageRegion.getBounds();
4402 if (!bounds.isValid()) {
4403 return;
4404 }
4405
4406 // If the damage region is a small dirty, this could give the hint for the layer history that
4407 // it could suppress the heuristic rate when calculating.
Tony Huang9ac5e6e2023-08-24 09:01:44 +00004408 mSmallDirty = mFlinger->mScheduler->isSmallDirtyArea(mOwnerUid,
4409 bounds.getWidth() * bounds.getHeight());
Arthur Hungc70bee22023-06-02 01:35:52 +00004410}
4411
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004412} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004413
4414#if defined(__gl_h_)
4415#error "don't include gl/gl.h in this file"
4416#endif
4417
4418#if defined(__gl2_h_)
4419#error "don't include gl2/gl2.h in this file"
4420#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004421
4422// TODO(b/129481165): remove the #pragma below and fix conversion issues
4423#pragma clang diagnostic pop // ignored "-Wconversion"