blob: cf1b0184e70426f50782e6221de2cd20404e23e5 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Dan Stoza9e56aa02015-11-02 13:00:03 -080021//#define LOG_NDEBUG 0
22#undef LOG_TAG
23#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080024#define ATRACE_TAG ATRACE_TAG_GRAPHICS
25
Alec Mourie60041e2019-06-14 18:59:51 -070026#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080027
[1;3C2b9fc252021-02-04 16:16:50 -080028#include <android-base/properties.h>
Yiwei Zhang5434a782018-12-05 18:06:32 -080029#include <android-base/stringprintf.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080030#include <android/native_window.h>
Vishnu Nair0f085c62019-08-30 08:49:12 -070031#include <binder/IPCThreadState.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000032#include <compositionengine/CompositionEngine.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080033#include <compositionengine/Display.h>
Lloyd Piquea83776c2019-01-29 18:42:32 -080034#include <compositionengine/LayerFECompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080035#include <compositionengine/OutputLayer.h>
36#include <compositionengine/impl/OutputLayerCompositionState.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070037#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070038#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070039#include <cutils/properties.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070040#include <ftl/enum.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080041#include <ftl/fake_guard.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080042#include <gui/BufferItem.h>
43#include <gui/LayerDebugInfo.h>
44#include <gui/Surface.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000045#include <gui/TraceUtils.h>
Alec Mourie60041e2019-06-14 18:59:51 -070046#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070047#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070049#include <stdint.h>
50#include <stdlib.h>
51#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000052#include <system/graphics-base-v1.0.h>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070053#include <ui/DataspaceUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080054#include <ui/DebugUtils.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000055#include <ui/FloatRect.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080056#include <ui/GraphicBuffer.h>
57#include <ui/PixelFormat.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000058#include <ui/Rect.h>
59#include <ui/Transform.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060#include <utils/Errors.h>
61#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080062#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080064#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065
Alec Mourie60041e2019-06-14 18:59:51 -070066#include <algorithm>
67#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070068#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070069#include <sstream>
70
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070071#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080072#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070073#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070074#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +000075#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000076#include "FrontEnd/LayerHandle.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080077#include "LayerProtoHelper.h"
Josh Gao194ff392022-09-08 16:19:29 -070078#include "MutexUtils.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080080#include "TimeStats/TimeStats.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070081#include "TunnelModeEnabledReporter.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070082
David Sodman41fdfc92017-11-06 16:09:56 -080083#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000084#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086namespace android {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010087namespace {
88constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000089
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000090const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000091
Patrick Williamsbb25f802022-08-30 23:02:34 +000092bool assignTransform(ui::Transform* dst, ui::Transform& from) {
93 if (*dst == from) {
94 return false;
95 }
96 *dst = from;
97 return true;
98}
99
100TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
101 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
102 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
103 const auto frameRateCompatibility = [frameRate] {
104 switch (frameRate.type) {
105 case Layer::FrameRateCompatibility::Default:
106 return FrameRateCompatibility::Default;
107 case Layer::FrameRateCompatibility::ExactOrMultiple:
108 return FrameRateCompatibility::ExactOrMultiple;
109 default:
110 return FrameRateCompatibility::Undefined;
111 }
112 }();
113
114 const auto seamlessness = [frameRate] {
115 switch (frameRate.seamlessness) {
116 case scheduler::Seamlessness::OnlySeamless:
117 return Seamlessness::ShouldBeSeamless;
118 case scheduler::Seamlessness::SeamedAndSeamless:
119 return Seamlessness::NotRequired;
120 default:
121 return Seamlessness::Undefined;
122 }
123 }();
124
125 return TimeStats::SetFrameRateVote{.frameRate = frameRate.rate.getValue(),
126 .frameRateCompatibility = frameRateCompatibility,
127 .seamlessness = seamlessness};
128}
129
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100130} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800131
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700132using namespace ftl::flag_operators;
133
Yiwei Zhang5434a782018-12-05 18:06:32 -0800134using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000135using frontend::LayerSnapshot;
136using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800137using gui::GameMode;
138using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500139using gui::WindowInfo;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800140
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700141using PresentState = frametimeline::SurfaceFrame::PresentState;
142
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700143Layer::Layer(const LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000144 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700145 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000146 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700147 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800148 mWindowType(static_cast<WindowInfo::Type>(
149 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000150 mLayerCreationFlags(args.flags),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000151 mBorderEnabled(false),
152 mTextureName(args.textureName),
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000153 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000154 ALOGV("Creating Layer %s", getDebugName());
155
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700156 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700157 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
158 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
159 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700160 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
161 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700162 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700163 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700164 mDrawingState.z = 0;
165 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700166 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700167 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700168 mDrawingState.transform.set(0, 0);
169 mDrawingState.frameNumber = 0;
Vishnu Nair63221212023-04-06 15:17:37 -0700170 mDrawingState.barrierFrameNumber = 0;
171 mDrawingState.producerId = 0;
172 mDrawingState.barrierProducerId = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700173 mDrawingState.bufferTransform = 0;
174 mDrawingState.transformToDisplayInverse = false;
175 mDrawingState.crop.makeInvalid();
176 mDrawingState.acquireFence = sp<Fence>::make(-1);
177 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
Alec Mouri74c7ae12023-03-26 02:57:47 +0000178 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Robert Carr6a160312021-05-17 12:08:20 -0700179 mDrawingState.hdrMetadata.validTypes = 0;
180 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
181 mDrawingState.cornerRadius = 0.0f;
182 mDrawingState.backgroundBlurRadius = 0;
183 mDrawingState.api = -1;
184 mDrawingState.hasColorTransform = false;
185 mDrawingState.colorSpaceAgnostic = false;
186 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
187 mDrawingState.metadata = args.metadata;
188 mDrawingState.shadowRadius = 0.f;
189 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
190 mDrawingState.frameTimelineInfo = {};
191 mDrawingState.postTime = -1;
192 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000193 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700194 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700195 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000196 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700197
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700198 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
199 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700200 mDrawingState.color.r = -1.0_hf;
201 mDrawingState.color.g = -1.0_hf;
202 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700203 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700204
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500205 mFrameTracker.setDisplayRefreshPeriod(
206 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700207
Vishnu Naircb8be502022-10-12 19:03:23 +0000208 mOwnerUid = args.ownerUid;
209 mOwnerPid = args.ownerPid;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000210
211 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
212 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
213 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000214
215 mSnapshot->sequence = sequence;
216 mSnapshot->name = getDebugName();
217 mSnapshot->textureName = mTextureName;
218 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000219 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800220}
221
222void Layer::onFirstRef() {
223 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700224}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700225
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700226Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000227 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
228 "Layer destructor called off the main thread.");
229
Patrick Williamsbb25f802022-08-30 23:02:34 +0000230 // The original layer and the clone layer share the same texture and buffer. Therefore, only
231 // one of the layers, in this case the original layer, needs to handle the deletion. The
232 // original layer and the clone should be removed at the same time so there shouldn't be any
233 // issue with the clone layer trying to use the texture.
234 if (mBufferInfo.mBuffer != nullptr) {
235 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
236 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800237 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000238 }
239 if (!isClone()) {
240 // The original layer and the clone layer share the same texture. Therefore, only one of
241 // the layers, in this case the original layer, needs to handle the deletion. The original
242 // layer and the clone should be removed at the same time so there shouldn't be any issue
243 // with the clone layer trying to use the deleted texture.
244 mFlinger->deleteTextureAsync(mTextureName);
245 }
246 const int32_t layerId = getSequence();
247 mFlinger->mTimeStats->onDestroy(layerId);
248 mFlinger->mFrameTracer->onDestroy(layerId);
249
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000250 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700251 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700252
253 if (mDrawingState.sidebandStream != nullptr) {
254 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
255 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700256 if (mHadClonedChild) {
Vishnu Nair3be61902023-04-26 19:47:29 -0700257 auto& roots = mFlinger->mLayerMirrorRoots;
258 roots.erase(std::remove(roots.begin(), roots.end(), this), roots.end());
Robert Carr6a0382d2021-07-01 15:57:17 -0700259 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000260 if (hasTrustedPresentationListener()) {
261 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000262 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000263 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700264}
265
Mathias Agopian13127d82013-03-05 17:47:11 -0800266// ---------------------------------------------------------------------------
267// callbacks
268// ---------------------------------------------------------------------------
269
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700270void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700271 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700272 return;
273 }
Robert Carr2e102c92018-10-23 12:11:15 -0700274
Robert Carr6a160312021-05-17 12:08:20 -0700275 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700276 if (strongRelative == nullptr) {
277 setZOrderRelativeOf(nullptr);
278 return;
279 }
280
281 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700282 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700283 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800284 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700285 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700286}
287
288void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700289 if (!mRemovedFromDrawingState) {
290 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700291 mFlinger->mScheduler->deregisterLayer(this);
292 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000293 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000294
Ady Abrahamd11bade2022-08-01 16:18:03 -0700295 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700296}
Chia-I Wu38512252017-05-17 14:36:16 -0700297
chaviw68d4dab2020-06-08 15:07:32 -0700298sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000299 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700300 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700301 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700302 }
303 return parent->getRootLayer();
304}
305
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700306void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700307 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
308 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700309 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700310
Josh Gao194ff392022-09-08 16:19:29 -0700311 REQUIRE_MUTEX(mFlinger->mStateLock);
312 traverse(LayerVector::StateSet::Current,
313 [&](Layer* layer) REQUIRES(layer->mFlinger->mStateLock) {
314 layer->removeFromCurrentState();
315 layer->removeRelativeZ(layersInTree);
316 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700317}
318
chaviw61626f22018-11-15 16:26:27 -0800319void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700320 if (mRemovedFromDrawingState) {
321 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700322 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700323 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700324 }
chaviw61626f22018-11-15 16:26:27 -0800325
326 for (const auto& child : mCurrentChildren) {
327 child->addToCurrentState();
328 }
329}
330
Mathias Agopian13127d82013-03-05 17:47:11 -0800331// ---------------------------------------------------------------------------
332// set-up
333// ---------------------------------------------------------------------------
334
chaviw13fdc492017-06-27 12:40:18 -0700335bool Layer::getPremultipledAlpha() const {
336 return mPremultipliedAlpha;
337}
338
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700339sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800340 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700341 if (mGetHandleCalled) {
342 ALOGE("Get handle called twice" );
343 return nullptr;
344 }
345 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700346 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000347 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800348}
349
350// ---------------------------------------------------------------------------
351// h/w composer set-up
352// ---------------------------------------------------------------------------
353
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700354static Rect reduce(const Rect& win, const Region& exclude) {
355 if (CC_LIKELY(exclude.isEmpty())) {
356 return win;
357 }
358 if (exclude.isRect()) {
359 return win.reduce(exclude.getBounds());
360 }
361 return Region(win).subtract(exclude).getBounds();
362}
363
Dan Stoza80d61162017-12-20 15:57:52 -0800364static FloatRect reduce(const FloatRect& win, const Region& exclude) {
365 if (CC_LIKELY(exclude.isEmpty())) {
366 return win;
367 }
368 // Convert through Rect (by rounding) for lack of FloatRegion
369 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
370}
371
Vishnu Nair4351ad52019-02-11 14:13:02 -0800372Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800373 if (!reduceTransparentRegion) {
374 return Rect{mScreenBounds};
375 }
376
377 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800378 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800379 // Transform to screen space.
380 bounds = t.transform(bounds);
381 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700382}
383
Vishnu Nair4351ad52019-02-11 14:13:02 -0800384FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000385 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800386 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700387}
388
Vishnu Nairf0c28512019-02-08 12:40:28 -0800389FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
390 // Subtract the transparent region and snap to the bounds.
391 return reduce(mBounds, activeTransparentRegion);
392}
393
Chavi Weingarten076acac2023-01-19 17:20:43 +0000394// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000395void Layer::updateTrustedPresentationState(const DisplayDevice* display,
396 const frontend::LayerSnapshot* snapshot,
397 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000398 if (!hasTrustedPresentationListener()) {
399 return;
400 }
401 const bool lastState = mLastComputedTrustedPresentationState;
402 mLastComputedTrustedPresentationState = false;
403
404 if (!leaveState) {
405 const auto outputLayer = findOutputLayerForDisplay(display);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000406 if (outputLayer != nullptr) {
407 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
408 Region coveredRegion =
409 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
410 mLastComputedTrustedPresentationState =
411 computeTrustedPresentationState(snapshot->geomLayerBounds,
412 snapshot->sourceBounds(), coveredRegion,
413 snapshot->transformedBounds,
414 snapshot->alpha,
415 snapshot->geomLayerTransform,
416 mTrustedPresentationThresholds);
417 } else {
418 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
419 "TrustedPresentationState",
420 getDebugName());
421 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000422 }
423 }
424 const bool newState = mLastComputedTrustedPresentationState;
425 if (lastState && !newState) {
426 // We were in the trusted presentation state, but now we left it,
427 // emit the callback if needed
428 if (mLastReportedTrustedPresentationState) {
429 mLastReportedTrustedPresentationState = false;
430 mTrustedPresentationListener.invoke(false);
431 }
432 // Reset the timer
433 mEnteredTrustedPresentationStateTime = -1;
434 } else if (!lastState && newState) {
435 // We were not in the trusted presentation state, but we entered it, begin the timer
436 // and make sure this gets called at least once more!
437 mEnteredTrustedPresentationStateTime = time_in_ms;
438 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
439 }
440
441 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
442 if (!mLastReportedTrustedPresentationState && newState &&
443 (time_in_ms - mEnteredTrustedPresentationStateTime >
444 mTrustedPresentationThresholds.stabilityRequirementMs)) {
445 mLastReportedTrustedPresentationState = true;
446 mTrustedPresentationListener.invoke(true);
447 }
448}
449
450/**
451 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
452 * of how the parameters and thresholds are interpreted. The general spirit is
453 * to produce an upper bound on the amount of the buffer which was presented.
454 */
455bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
456 const Region& coveredRegion,
457 const FloatRect& screenBounds, float alpha,
458 const ui::Transform& effectiveTransform,
459 const TrustedPresentationThresholds& thresholds) {
460 if (alpha < thresholds.minAlpha) {
461 return false;
462 }
463 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
464 return false;
465 }
466 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
467 return false;
468 }
469
470 const float sx = effectiveTransform.dsdx();
471 const float sy = effectiveTransform.dsdy();
472 float fractionRendered = std::min(sx * sy, 1.0f);
473
474 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
475 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
476 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
477
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000478 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
479 // Compute the size of all the rects since they may be disconnected.
480 float coveredSize = 0;
481 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
482 float size = rect->width() * rect->height();
483 coveredSize += size;
484 }
485
486 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000487
488 if (fractionRendered < thresholds.minFractionRendered) {
489 return false;
490 }
491
492 return true;
493}
494
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700495void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
496 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800497 const State& s(getDrawingState());
498
499 // Calculate effective layer transform
500 mEffectiveTransform = parentTransform * getActiveTransform(s);
501
Garfield Tan2c1782c2022-02-16 15:25:05 -0800502 if (CC_UNLIKELY(!isTransformValid())) {
503 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
504 getDebugName());
505 return;
506 }
507
Vishnu Nair4351ad52019-02-11 14:13:02 -0800508 // Transform parent bounds to layer space
509 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
510
Vishnu Nairc652ff82019-03-15 12:48:54 -0700511 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800512 mSourceBounds = computeSourceBounds(parentBounds);
513
514 // Calculate bounds by croping diplay frame with layer crop and parent bounds
515 FloatRect bounds = mSourceBounds;
516 const Rect layerCrop = getCrop(s);
517 if (!layerCrop.isEmpty()) {
518 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
519 }
520 bounds = bounds.intersect(parentBounds);
521
522 mBounds = bounds;
523 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700524
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700525 // Use the layer's own shadow radius if set. Otherwise get the radius from
526 // parent.
527 if (s.shadowRadius > 0.f) {
528 mEffectiveShadowRadius = s.shadowRadius;
529 } else {
530 mEffectiveShadowRadius = parentShadowRadius;
531 }
532
533 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
534 // don't pass it to its children.
535 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
536
Vishnu Nair4351ad52019-02-11 14:13:02 -0800537 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700538 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800539 }
Vishnu Nairba354102022-08-01 00:14:18 +0000540
541 if (mPotentialCursor) {
542 prepareCursorCompositionState();
543 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800544}
545
Vishnu Nair60356342018-11-13 13:00:45 -0800546Rect Layer::getCroppedBufferSize(const State& s) const {
547 Rect size = getBufferSize(s);
548 Rect crop = getCrop(s);
549 if (!crop.isEmpty() && size.isValid()) {
550 size.intersect(crop, &size);
551 } else if (!crop.isEmpty()) {
552 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700553 }
Vishnu Nair60356342018-11-13 13:00:45 -0800554 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800555}
556
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700557void Layer::setupRoundedCornersCropCoordinates(Rect win,
558 const FloatRect& roundedCornersCrop) const {
559 // Translate win by the rounded corners rect coordinates, to have all values in
560 // layer coordinate space.
561 win.left -= roundedCornersCrop.left;
562 win.right -= roundedCornersCrop.left;
563 win.top -= roundedCornersCrop.top;
564 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700565}
566
Lloyd Piquede196652020-01-22 17:29:58 -0800567void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800568 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800569 const auto alpha = static_cast<float>(getAlpha());
570 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700571 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800572
573 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
574 if (!opaque || alpha != 1.0f) {
575 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
576 : Hwc2::IComposerClient::BlendMode::COVERAGE;
577 }
578
Alec Mourif4af03e2023-02-11 00:25:24 +0000579 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000580 auto* snapshot = editLayerSnapshot();
581 snapshot->outputFilter = getOutputFilter();
582 snapshot->isVisible = isVisible();
583 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
584 snapshot->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800585
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000586 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800587 contentDirty = false;
588
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000589 snapshot->geomLayerBounds = mBounds;
590 snapshot->geomLayerTransform = getTransform();
591 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
592 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000593 snapshot->localTransform = getActiveTransform(drawingState);
594 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000595 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
596 snapshot->alpha = alpha;
597 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
598 snapshot->blurRegions = drawingState.blurRegions;
599 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800600}
601
Lloyd Piquede196652020-01-22 17:29:58 -0800602void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800603 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000604 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700605
Alec Mourif4af03e2023-02-11 00:25:24 +0000606 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000607 snapshot->geomBufferSize = getBufferSize(drawingState);
608 snapshot->geomContentCrop = getBufferCrop();
609 snapshot->geomCrop = getCrop(drawingState);
610 snapshot->geomBufferTransform = getBufferTransform();
611 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
612 snapshot->geomUsesSourceCrop = usesSourceCrop();
613 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800614
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000615 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800616 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
617 for (const auto& [key, mandatory] : supportedMetadata) {
618 const auto& genericLayerMetadataCompatibilityMap =
619 mFlinger->getGenericLayerMetadataKeyMap();
620 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
621 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
622 continue;
623 }
624 const uint32_t id = compatIter->second;
625
626 auto it = drawingState.metadata.mMap.find(id);
627 if (it == std::end(drawingState.metadata.mMap)) {
628 continue;
629 }
630
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000631 snapshot->metadata.emplace(key,
632 compositionengine::GenericLayerMetadataEntry{mandatory,
633 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800634 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800635}
David Sodmanba340492018-08-05 21:51:33 -0700636
Lloyd Piquede196652020-01-22 17:29:58 -0800637void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800638 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000639 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000640 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800641
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000642 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800643
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000644 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
645 snapshot->dataspace = getDataSpace();
646 snapshot->colorTransform = getColorTransform();
647 snapshot->colorTransformIsIdentity = !hasColorTransform();
648 snapshot->surfaceDamage = surfaceDamageRegion;
649 snapshot->hasProtectedContent = isProtected();
650 snapshot->dimmingEnabled = isDimmingEnabled();
Sally Qi963049b2023-03-23 14:06:21 -0700651 snapshot->currentHdrSdrRatio = getCurrentHdrSdrRatio();
652 snapshot->desiredHdrSdrRatio = getDesiredHdrSdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000653 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800654
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700655 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700656
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000657 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800658
659 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400660 // Rounded corners no longer force client composition, since we may use a
661 // hole punch so that the layer will appear to have rounded corners.
662 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000663 snapshot->stretchEffect.hasEffect()) {
664 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800665 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700666 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000667 snapshot->blurRegions = drawingState.blurRegions;
668 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400669
670 // Layer framerate is used in caching decisions.
671 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
672 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000673 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000674
675 if (hasBufferOrSidebandStream()) {
676 preparePerFrameBufferCompositionState();
677 } else {
678 preparePerFrameEffectsCompositionState();
679 }
680}
681
682void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000683 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000684 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000685 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000686 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
687 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000688 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
689 return;
690 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000691 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000692 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800693 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
694 snapshot->compositionType =
695 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000696 } else {
697 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000698 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
699 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000700 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
701 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
702 }
703
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000704 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000705 snapshot->acquireFence = mBufferInfo.mFence;
706 snapshot->frameNumber = mBufferInfo.mFrameNumber;
707 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000708}
709
710void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000711 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000712 auto* snapshot = editLayerSnapshot();
713 snapshot->color = getColor();
714 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000715 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800716}
717
Lloyd Piquede196652020-01-22 17:29:58 -0800718void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800719 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000720 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000721 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800722
723 // Apply the layer's transform, followed by the display's global transform
724 // Here we're guaranteed that the layer's transform preserves rects
725 Rect win = getCroppedBufferSize(drawingState);
726 // Subtract the transparent region and snap to the bounds
727 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
728 Rect frame(getTransform().transform(bounds));
729
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000730 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800731}
732
Lloyd Piquea83776c2019-01-29 18:42:32 -0800733const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700734 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800735}
736
Mathias Agopian13127d82013-03-05 17:47:11 -0800737// ---------------------------------------------------------------------------
738// drawing...
739// ---------------------------------------------------------------------------
740
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500741aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
742 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700743 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800744 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500745 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800746 }
747 if (outputLayer->getState().hwc) {
748 return (*outputLayer->getState().hwc).hwcCompositionType;
749 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500750 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800751 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800752}
753
Mathias Agopian13127d82013-03-05 17:47:11 -0800754// ----------------------------------------------------------------------------
755// local state
756// ----------------------------------------------------------------------------
757
David Sodman41fdfc92017-11-06 16:09:56 -0800758bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800759 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700760 if (s.flags & layer_state_t::eLayerSecure) {
761 return true;
762 }
763
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000764 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700765 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700766}
767
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100768void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
769 std::vector<JankData>& jankData) {
770 if (mPendingJankClassifications.empty() ||
771 !mPendingJankClassifications.front()->getJankType()) {
772 return;
773 }
774
775 bool includeJankData = false;
776 for (const auto& handle : handles) {
777 for (const auto& cb : handle->callbackIds) {
778 if (cb.includeJankData) {
779 includeJankData = true;
780 break;
781 }
782 }
783
784 if (includeJankData) {
785 jankData.reserve(mPendingJankClassifications.size());
786 break;
787 }
788 }
789
790 while (!mPendingJankClassifications.empty() &&
791 mPendingJankClassifications.front()->getJankType()) {
792 if (includeJankData) {
793 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
794 mPendingJankClassifications.front();
795 jankData.emplace_back(
796 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
797 }
798 mPendingJankClassifications.pop_front();
799 }
800}
801
Mathias Agopian13127d82013-03-05 17:47:11 -0800802// ----------------------------------------------------------------------------
803// transaction
804// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800805
Vishnu Naira156f482023-02-22 00:23:38 +0000806uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700807 ATRACE_CALL();
808
Robert Carr0758e5d2021-03-11 22:15:04 -0800809 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700810 mDrawingStateModified = mDrawingState.modified;
811 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700812
Alec Mourib416efd2018-09-06 21:01:59 +0000813 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700814
Robert Carr6a160312021-05-17 12:08:20 -0700815 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800816 // invalidate and recompute the visible regions if needed
817 flags |= Layer::eVisibleRegion;
818 }
819
Robert Carr6a160312021-05-17 12:08:20 -0700820 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800821 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000822 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800823 flags |= eVisibleRegion;
824 this->contentDirty = true;
825
826 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700827 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800828 }
829
Arthur Hung9ed43392022-05-27 06:31:57 +0000830 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
831 mFlinger->mUpdateInputInfo = true;
832 }
833
Vishnu Naira156f482023-02-22 00:23:38 +0000834 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800835
Mathias Agopian13127d82013-03-05 17:47:11 -0800836 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800837}
838
Vishnu Naira156f482023-02-22 00:23:38 +0000839void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000840 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
841 // bufferSurfaceFrameTX will be presented in latchBuffer.
842 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
843 if (surfaceFrame->getPresentState() != PresentState::Presented) {
844 // With applyPendingStates, we could end up having presented surfaceframes from previous
845 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800846 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000847 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
848 }
849 }
Robert Carr6a160312021-05-17 12:08:20 -0700850 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700851}
852
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700853uint32_t Layer::clearTransactionFlags(uint32_t mask) {
854 const auto flags = mTransactionFlags & mask;
855 mTransactionFlags &= ~mask;
856 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800857}
858
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700859void Layer::setTransactionFlags(uint32_t mask) {
860 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800861}
862
Robert Carr1f0a16a2016-10-24 16:27:39 -0700863bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
864 ssize_t idx = mCurrentChildren.indexOf(childLayer);
865 if (idx < 0) {
866 return false;
867 }
868 if (childLayer->setLayer(z)) {
869 mCurrentChildren.removeAt(idx);
870 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800871 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700872 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800873 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700874}
875
Robert Carr503c7042017-09-27 15:06:08 -0700876bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
877 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
878 ssize_t idx = mCurrentChildren.indexOf(childLayer);
879 if (idx < 0) {
880 return false;
881 }
882 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
883 mCurrentChildren.removeAt(idx);
884 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800885 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700886 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800887 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700888}
889
Robert Carrae060832016-11-28 10:51:00 -0800890bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700891 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
892 mDrawingState.sequence++;
893 mDrawingState.z = z;
894 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700895
Robert Carra70e91c2021-06-11 13:59:52 -0700896 mFlinger->mSomeChildrenChanged = true;
897
Robert Carrdb66e622017-04-10 16:55:57 -0700898 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700899 if (mDrawingState.zOrderRelativeOf != nullptr) {
900 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700901 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700902 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700903 }
chaviw606e5cf2019-03-01 10:12:10 -0800904 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700905 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800906 setTransactionFlags(eTransactionNeeded);
907 return true;
908}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700909
Robert Carrdb66e622017-04-10 16:55:57 -0700910void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700911 mDrawingState.zOrderRelatives.remove(relative);
912 mDrawingState.sequence++;
913 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700914 setTransactionFlags(eTransactionNeeded);
915}
916
917void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700918 mDrawingState.zOrderRelatives.add(relative);
919 mDrawingState.modified = true;
920 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700921 setTransactionFlags(eTransactionNeeded);
922}
923
chaviw606e5cf2019-03-01 10:12:10 -0800924void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700925 mDrawingState.zOrderRelativeOf = relativeOf;
926 mDrawingState.sequence++;
927 mDrawingState.modified = true;
928 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700929
chaviw606e5cf2019-03-01 10:12:10 -0800930 setTransactionFlags(eTransactionNeeded);
931}
932
Robert Carr503d2bd2017-12-04 15:49:47 -0800933bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000934 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700935 if (relative == nullptr) {
936 return false;
937 }
938
Robert Carr6a160312021-05-17 12:08:20 -0700939 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
940 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800941 return false;
942 }
943
Robert Carr88b85e12022-03-21 15:47:35 -0700944 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
945 (relative->mDrawingState.zOrderRelativeOf == this)) {
946 ALOGE("Detected relative layer loop between %s and %s",
947 mName.c_str(), relative->mName.c_str());
948 ALOGE("Ignoring new call to set relative layer");
949 return false;
950 }
951
Robert Carra70e91c2021-06-11 13:59:52 -0700952 mFlinger->mSomeChildrenChanged = true;
953
Robert Carr6a160312021-05-17 12:08:20 -0700954 mDrawingState.sequence++;
955 mDrawingState.modified = true;
956 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700957
Robert Carr6a160312021-05-17 12:08:20 -0700958 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700959 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700960 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700961 }
chaviw606e5cf2019-03-01 10:12:10 -0800962 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700963 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700964
965 setTransactionFlags(eTransactionNeeded);
966
967 return true;
968}
969
Winson Chunga30f7c92021-06-29 15:42:56 -0700970bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
971 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
972 mDrawingState.isTrustedOverlay = isTrustedOverlay;
973 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000974 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700975 setTransactionFlags(eTransactionNeeded);
976 return true;
977}
978
979bool Layer::isTrustedOverlay() const {
980 if (getDrawingState().isTrustedOverlay) {
981 return true;
982 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000983 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700984 return (p != nullptr) && p->isTrustedOverlay();
985}
986
Dan Stoza9e56aa02015-11-02 13:00:03 -0800987bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700988 if (mDrawingState.color.a == alpha) return false;
989 mDrawingState.sequence++;
990 mDrawingState.color.a = alpha;
991 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800992 setTransactionFlags(eTransactionNeeded);
993 return true;
994}
chaviw13fdc492017-06-27 12:40:18 -0700995
Valerie Haudd0b7572019-01-29 14:59:27 -0800996bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700997 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700998 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800999 }
Robert Carr6a160312021-05-17 12:08:20 -07001000 mDrawingState.sequence++;
1001 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -08001002 setTransactionFlags(eTransactionNeeded);
1003
Robert Carr6a160312021-05-17 12:08:20 -07001004 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001005 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001006 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001007 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001008 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08001009 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001010 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001011
Valerie Haudd0b7572019-01-29 14:59:27 -08001012 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001013 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001014 mFlinger->mLayersAdded = true;
1015 // set up SF to handle added color layer
1016 if (isRemovedFromCurrentState()) {
Josh Gao194ff392022-09-08 16:19:29 -07001017 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001018 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001019 }
1020 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001021 } else if (mDrawingState.bgColorLayer && alpha == 0) {
Josh Gao194ff392022-09-08 16:19:29 -07001022 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001023 mDrawingState.bgColorLayer->reparent(nullptr);
1024 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001025 return true;
1026 }
1027
Robert Carr6a160312021-05-17 12:08:20 -07001028 mDrawingState.bgColorLayer->setColor(color);
1029 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1030 mDrawingState.bgColorLayer->setAlpha(alpha);
1031 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001032
chaviw13fdc492017-06-27 12:40:18 -07001033 return true;
1034}
1035
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001036bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001037 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001038
Robert Carr6a160312021-05-17 12:08:20 -07001039 mDrawingState.sequence++;
1040 mDrawingState.cornerRadius = cornerRadius;
1041 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001042 setTransactionFlags(eTransactionNeeded);
1043 return true;
1044}
1045
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001046bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001047 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001048 // If we start or stop drawing blur then the layer's visibility state may change so increment
1049 // the magic sequence number.
1050 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1051 mDrawingState.sequence++;
1052 }
Robert Carr6a160312021-05-17 12:08:20 -07001053 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1054 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001055 setTransactionFlags(eTransactionNeeded);
1056 return true;
1057}
Marissa Wall61c58622018-07-18 10:12:20 -07001058
Mathias Agopian13127d82013-03-05 17:47:11 -08001059bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001060 mDrawingState.sequence++;
1061 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001062 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001063 setTransactionFlags(eTransactionNeeded);
1064 return true;
1065}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001066
Lucas Dupinc3800b82020-10-02 16:24:48 -07001067bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001068 // If we start or stop drawing blur then the layer's visibility state may change so increment
1069 // the magic sequence number.
1070 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1071 mDrawingState.sequence++;
1072 }
Robert Carr6a160312021-05-17 12:08:20 -07001073 mDrawingState.blurRegions = blurRegions;
1074 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001075 setTransactionFlags(eTransactionNeeded);
1076 return true;
1077}
1078
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001079bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001080 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1081 if (mDrawingState.flags == newFlags) return false;
1082 mDrawingState.sequence++;
1083 mDrawingState.flags = newFlags;
1084 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001085 setTransactionFlags(eTransactionNeeded);
1086 return true;
1087}
Robert Carr99e27f02016-06-16 15:18:02 -07001088
chaviw25714502021-02-11 10:01:08 -08001089bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001090 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001091 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001092 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001093
Robert Carr6a160312021-05-17 12:08:20 -07001094 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001095 setTransactionFlags(eTransactionNeeded);
1096 return true;
1097}
Robert Carr8d5227b2017-03-16 15:41:03 -07001098
Evan Roskyef876c92019-01-25 17:46:06 -08001099bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001100 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1101 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001102 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001103 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001104}
1105
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001106bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001107 if (mDrawingState.layerStack == layerStack) return false;
1108 mDrawingState.sequence++;
1109 mDrawingState.layerStack = layerStack;
1110 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001111 setTransactionFlags(eTransactionNeeded);
1112 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001113}
1114
Peiyong Linc502cb72019-03-01 15:00:23 -08001115bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001116 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001117 return false;
1118 }
Robert Carr6a160312021-05-17 12:08:20 -07001119 mDrawingState.sequence++;
1120 mDrawingState.colorSpaceAgnostic = agnostic;
1121 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001122 setTransactionFlags(eTransactionNeeded);
1123 return true;
1124}
1125
Sally Qi81d95e62022-03-21 19:41:33 -07001126bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1127 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1128
1129 mDrawingState.sequence++;
1130 mDrawingState.dimmingEnabled = dimmingEnabled;
1131 mDrawingState.modified = true;
1132 setTransactionFlags(eTransactionNeeded);
1133 return true;
1134}
1135
Ana Krulecc84d09b2019-11-02 23:10:29 +01001136bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001137 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1138 mDrawingState.frameRateSelectionPriority = priority;
1139 mDrawingState.sequence++;
1140 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001141 setTransactionFlags(eTransactionNeeded);
1142 return true;
1143}
1144
1145int32_t Layer::getFrameRateSelectionPriority() const {
1146 // Check if layer has priority set.
1147 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1148 return mDrawingState.frameRateSelectionPriority;
1149 }
1150 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001151 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001152 if (parent != nullptr) {
1153 return parent->getFrameRateSelectionPriority();
1154 }
1155
1156 return Layer::PRIORITY_UNSET;
1157}
1158
Andy Labrada096227e2022-06-15 16:58:11 +00001159bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1160 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1161 mDrawingState.defaultFrameRateCompatibility = compatibility;
1162 mDrawingState.modified = true;
1163 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1164 setTransactionFlags(eTransactionNeeded);
1165 return true;
1166}
1167
1168scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1169 return mDrawingState.defaultFrameRateCompatibility;
1170}
1171
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001172bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1173 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1174};
1175
Vishnu Nair73908d12022-10-24 21:46:42 -07001176ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1177 bool useDrawing = state == LayerVector::StateSet::Drawing;
1178 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1179 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001180 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001181 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001182 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001183}
1184
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001185bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001186 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001187 return false;
1188 }
1189
Robert Carr6a160312021-05-17 12:08:20 -07001190 mDrawingState.sequence++;
1191 mDrawingState.shadowRadius = shadowRadius;
1192 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001193 setTransactionFlags(eTransactionNeeded);
1194 return true;
1195}
1196
Vishnu Nair6213bd92020-05-08 17:42:25 -07001197bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001198 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001199 return false;
1200 }
1201
Robert Carr6a160312021-05-17 12:08:20 -07001202 mDrawingState.sequence++;
1203 mDrawingState.fixedTransformHint = fixedTransformHint;
1204 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001205 setTransactionFlags(eTransactionNeeded);
1206 return true;
1207}
1208
John Reckcdb4ed72021-02-04 13:39:33 -05001209bool Layer::setStretchEffect(const StretchEffect& effect) {
1210 StretchEffect temp = effect;
1211 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001212 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001213 return false;
1214 }
Robert Carr6a160312021-05-17 12:08:20 -07001215 mDrawingState.sequence++;
1216 mDrawingState.stretchEffect = temp;
1217 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001218 setTransactionFlags(eTransactionNeeded);
1219 return true;
1220}
1221
John Reckc00c6692021-02-16 11:37:33 -05001222StretchEffect Layer::getStretchEffect() const {
1223 if (mDrawingState.stretchEffect.hasEffect()) {
1224 return mDrawingState.stretchEffect;
1225 }
1226
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001227 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001228 if (parent != nullptr) {
1229 auto effect = parent->getStretchEffect();
1230 if (effect.hasEffect()) {
1231 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1232 return effect;
1233 }
1234 }
1235 return StretchEffect{};
1236}
1237
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001238bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1239 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001240 return false;
1241 }
1242 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001243 mBorderWidth = width;
1244 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001245 return true;
1246}
1247
1248bool Layer::isBorderEnabled() {
1249 return mBorderEnabled;
1250}
1251
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001252float Layer::getBorderWidth() {
1253 return mBorderWidth;
1254}
1255
1256const half4& Layer::getBorderColor() {
1257 return mBorderColor;
1258}
1259
Ady Abrahama850c182021-08-04 13:04:37 -07001260bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1261 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1262 const auto frameRate = [&] {
1263 if (mDrawingState.frameRate.rate.isValid() ||
1264 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1265 return mDrawingState.frameRate;
1266 }
1267
1268 return parentFrameRate;
1269 }();
1270
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001271 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001272
1273 // The frame rate is propagated to the children
1274 bool childrenHaveFrameRate = false;
1275 for (const sp<Layer>& child : mCurrentChildren) {
1276 childrenHaveFrameRate |=
1277 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1278 }
1279
1280 // If we don't have a valid frame rate, but the children do, we set this
1281 // layer as NoVote to allow the children to control the refresh rate
1282 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1283 childrenHaveFrameRate) {
1284 *transactionNeeded |=
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001285 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001286 }
1287
1288 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1289 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001290 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001291 const auto layerVotedWithDefaultCompatibility =
1292 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1293 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1294 const auto layerVotedWithExactCompatibility =
1295 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1296 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1297 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1298}
1299
Ady Abraham60e42ea2020-03-09 19:17:31 -07001300void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001301 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001302 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001303 while (auto parent = layer->getParent()) {
1304 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001305 }
Ady Abrahama850c182021-08-04 13:04:37 -07001306 return layer;
1307 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001308
Ady Abraham60e42ea2020-03-09 19:17:31 -07001309 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001310 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001311
Ady Abrahama850c182021-08-04 13:04:37 -07001312 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001313 if (transactionNeeded) {
1314 mFlinger->setTransactionFlags(eTraversalNeeded);
1315 }
1316}
1317
Ady Abraham71c437d2020-01-31 15:56:57 -08001318bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001319 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001320 return false;
1321 }
1322
Robert Carr6a160312021-05-17 12:08:20 -07001323 mDrawingState.sequence++;
1324 mDrawingState.frameRate = frameRate;
1325 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001326
1327 updateTreeHasFrameRateVote();
1328
Steven Thomas3172e202020-01-06 19:25:30 -08001329 setTransactionFlags(eTransactionNeeded);
1330 return true;
1331}
1332
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001333void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1334 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001335 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001336
1337 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1338 // there are two transactions with the same token, the first one without a buffer and the
1339 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1340 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001341 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1342 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001343 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001344 mDrawingState.bufferSurfaceFrameTX = it->second;
1345 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1346 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1347 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001348 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001349 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001350 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1351 }
1352}
1353
1354void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1355 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001356 mDrawingState.frameTimelineInfo = info;
1357 mDrawingState.postTime = postTime;
1358 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001359 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001360
Robert Carr6a160312021-05-17 12:08:20 -07001361 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001362 bufferSurfaceFrameTX != nullptr) {
1363 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1364 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1365 // being used for BufferSurfaceFrame, don't create a new one.
1366 return;
1367 }
1368 }
1369 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1370 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1371 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001372 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1373 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001374 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001375 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001376 } else {
1377 if (it->second->getPresentState() == PresentState::Presented) {
1378 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1379 // have been from previous vsync.
1380 it->second = createSurfaceFrameForTransaction(info, postTime);
1381 }
1382 }
1383}
1384
1385void Layer::addSurfaceFrameDroppedForBuffer(
1386 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001387 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001388 surfaceFrame->setPresentState(PresentState::Dropped);
1389 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1390}
1391
1392void Layer::addSurfaceFramePresentedForBuffer(
1393 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1394 nsecs_t currentLatchTime) {
1395 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1396 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1397 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001398 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001399}
1400
1401std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1402 const FrameTimelineInfo& info, nsecs_t postTime) {
1403 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001404 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1405 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001406 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001407 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001408 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001409 // For Transactions, the post time is considered to be both queue and acquire fence time.
1410 surfaceFrame->setActualQueueTime(postTime);
1411 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001412 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1413 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001414 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001415 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001416 onSurfaceFrameCreated(surfaceFrame);
1417 return surfaceFrame;
1418}
1419
1420std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1421 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1422 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001423 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001424 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001425 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001426 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001427 // For buffers, acquire fence time will set during latch.
1428 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001429 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1430 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001431 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001432 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001433 onSurfaceFrameCreated(surfaceFrame);
1434 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001435}
1436
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001437bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001438 if (mDrawingState.frameRateForLayerTree == frameRate) {
1439 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001440 }
1441
Ady Abrahama850c182021-08-04 13:04:37 -07001442 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001443
Ady Abrahama850c182021-08-04 13:04:37 -07001444 // TODO(b/195668952): we probably don't need to dirty visible regions here
1445 // or even store frameRateForLayerTree in mDrawingState
1446 mDrawingState.sequence++;
1447 mDrawingState.modified = true;
1448 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001449
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001450 mFlinger->mScheduler
1451 ->recordLayerHistory(sequence, getLayerProps(), systemTime(),
1452 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1453 return true;
1454}
Ady Abrahama850c182021-08-04 13:04:37 -07001455
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001456bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps) {
1457 if (mDrawingState.frameRateForLayerTree == frameRate) {
1458 return false;
1459 }
1460
1461 mDrawingState.frameRateForLayerTree = frameRate;
1462 mFlinger->mScheduler
1463 ->recordLayerHistory(sequence, layerProps, systemTime(),
1464 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001465 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001466}
1467
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001468Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1469 return getDrawingState().frameRateForLayerTree;
1470}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001471
Robert Carr1f0a16a2016-10-24 16:27:39 -07001472bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001473 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001474 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001475 if (parent != nullptr && parent->isHiddenByPolicy()) {
1476 return true;
1477 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001478 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1479 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1480 if (zOrderRelativeOf != nullptr) {
1481 if (zOrderRelativeOf->isHiddenByPolicy()) {
1482 return true;
1483 }
1484 }
1485 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001486 if (CC_UNLIKELY(!isTransformValid())) {
1487 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1488 return true;
1489 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001490 return s.flags & layer_state_t::eLayerHidden;
1491}
1492
David Sodman41fdfc92017-11-06 16:09:56 -08001493uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001494 // TODO: should we do something special if mSecure is set?
1495 if (mProtectedByApp) {
1496 // need a hardware-protected path to external video sink
1497 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001498 }
Riley Andrews03414a12014-07-01 14:22:59 -07001499 if (mPotentialCursor) {
1500 usage |= GraphicBuffer::USAGE_CURSOR;
1501 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001502 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001503 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001504}
1505
Vishnu Nair71fcf912022-10-18 09:14:20 -07001506void Layer::skipReportingTransformHint() {
1507 mSkipReportingTransformHint = true;
1508}
1509
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001510void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1511 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1512 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001513 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001514
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001515 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001516}
1517
Mathias Agopian13127d82013-03-05 17:47:11 -08001518// ----------------------------------------------------------------------------
1519// debugging
1520// ----------------------------------------------------------------------------
1521
Marissa Wall61c58622018-07-18 10:12:20 -07001522// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001523gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001524 using namespace std::string_literals;
1525
Huihong Luo05539a12022-02-23 10:29:40 -08001526 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001527 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001528 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001529 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001530 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001531 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001532
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001533 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001534 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001535 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001536 info.mX = ds.transform.tx();
1537 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001538 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001539 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001540 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001541 info.mFlags = ds.flags;
1542 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001543 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001544 info.mMatrix[0][0] = ds.transform[0][0];
1545 info.mMatrix[0][1] = ds.transform[0][1];
1546 info.mMatrix[1][0] = ds.transform[1][0];
1547 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001548 {
chaviwd62d3062019-09-04 14:48:02 -07001549 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001550 if (buffer != 0) {
1551 info.mActiveBufferWidth = buffer->getWidth();
1552 info.mActiveBufferHeight = buffer->getHeight();
1553 info.mActiveBufferStride = buffer->getStride();
1554 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001555 } else {
1556 info.mActiveBufferWidth = 0;
1557 info.mActiveBufferHeight = 0;
1558 info.mActiveBufferStride = 0;
1559 info.mActiveBufferFormat = 0;
1560 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001561 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001562 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001563 info.mIsOpaque = isOpaque(ds);
1564 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001565 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001566 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001567}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001568
Yiwei Zhang5434a782018-12-05 18:06:32 -08001569void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001570 result.append(kDumpTableRowLength, '-');
1571 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001572 result.append(" Layer name\n");
1573 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001574 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001575 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001576 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001577 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001578 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001579 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1580 result.append(kDumpTableRowLength, '-');
1581 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001582}
1583
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001584void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1585 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001586 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001587 return;
1588 }
1589
Yiwei Zhang5434a782018-12-05 18:06:32 -08001590 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001591 if (mName.length() > 77) {
1592 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001593 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001594 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001595 shortened.append(mName, mName.length() - 36);
1596 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001597 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001598 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001599 }
1600
Yiwei Zhang5434a782018-12-05 18:06:32 -08001601 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001602
Alec Mourib416efd2018-09-06 21:01:59 +00001603 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001604 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001605
Chia-I Wu1e043612018-03-01 09:45:09 -08001606 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001607 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001608 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001609 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001610 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001611 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001612 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001613 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1614 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001615 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001616 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001617 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001618 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001619 const auto frameRate = getFrameRateForLayerTree();
1620 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1621 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001622 ftl::enum_string(frameRate.type).c_str(),
1623 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001624 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001625 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001626 }
Dan Stozae22aec72016-08-01 13:20:59 -07001627
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001628 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1629 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1630
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001631 result.append(kDumpTableRowLength, '-');
1632 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001633}
Dan Stozae22aec72016-08-01 13:20:59 -07001634
Yiwei Zhang5434a782018-12-05 18:06:32 -08001635void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001636 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001637}
1638
Svetoslavd85084b2014-03-20 10:28:31 -07001639void Layer::clearFrameStats() {
1640 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001641}
1642
Jamie Gennis6547ff42013-07-16 20:12:42 -07001643void Layer::logFrameStats() {
1644 mFrameTracker.logAndResetStats(mName);
1645}
1646
Svetoslavd85084b2014-03-20 10:28:31 -07001647void Layer::getFrameStats(FrameStats* outStats) const {
1648 mFrameTracker.getStats(outStats);
1649}
1650
Vishnu Nair76554eb2022-12-09 03:38:36 +00001651void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1652 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
Vishnu Nair3be61902023-04-26 19:47:29 -07001653 StringAppendF(&result, "Layer %s%s pid:%d uid:%d%s\n", getName().c_str(), hasBuffer.c_str(),
1654 mOwnerPid, mOwnerUid, isHandleAlive() ? " handleAlive" : "");
Vishnu Nair0f085c62019-08-30 08:49:12 -07001655}
1656
Brian Anderson5ea5e592016-12-01 16:54:33 -08001657void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001658 const int32_t layerId = getSequence();
1659 mFlinger->mTimeStats->onDestroy(layerId);
1660 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001661}
1662
Vishnu Nair787aa782023-03-17 13:46:46 -07001663size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001664 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001665 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001666 count += 1 + child->getChildrenCount();
1667 }
1668 return count;
1669}
1670
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001671void Layer::setGameModeForTree(GameMode gameMode) {
1672 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001673 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1674 gameMode =
1675 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001676 }
1677 setGameMode(gameMode);
1678 for (const sp<Layer>& child : mCurrentChildren) {
1679 child->setGameModeForTree(gameMode);
1680 }
1681}
1682
Robert Carr1f0a16a2016-10-24 16:27:39 -07001683void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001684 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001685 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001686
Robert Carr1f0a16a2016-10-24 16:27:39 -07001687 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001688 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001689 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001690 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001691}
1692
1693ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001694 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001695 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001696
Robert Carr1323c952019-01-28 18:13:27 -08001697 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001698 const auto removeResult = mCurrentChildren.remove(layer);
1699
1700 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001701 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001702 layer->updateTreeHasFrameRateVote();
1703
1704 return removeResult;
1705}
1706
Robert Carr15eae092018-03-23 13:43:53 -07001707void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001708 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001709 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001710 const float parentShadowRadius =
1711 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001712 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001713 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001714 }
1715}
1716
chaviwf1961f72017-09-18 16:41:07 -07001717bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001718 sp<Layer> newParent;
1719 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001720 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001721 if (newParent == nullptr) {
1722 ALOGE("Unable to promote Layer handle");
1723 return false;
1724 }
1725 if (newParent == this) {
1726 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1727 return false;
1728 }
1729 }
1730
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001731 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001732 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001733 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001734 }
1735
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001736 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001737 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001738 if (!newParent->isRemovedFromCurrentState()) {
1739 addToCurrentState();
1740 } else {
1741 onRemovedFromCurrentState();
1742 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001743 } else {
1744 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001745 }
1746
chaviw06178942017-07-27 10:25:59 -07001747 return true;
1748}
1749
Peiyong Lind3788632018-09-18 16:01:31 -07001750bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001751 static const mat4 identityMatrix = mat4();
1752
Robert Carr6a160312021-05-17 12:08:20 -07001753 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001754 return false;
1755 }
Robert Carr6a160312021-05-17 12:08:20 -07001756 ++mDrawingState.sequence;
1757 mDrawingState.colorTransform = matrix;
1758 mDrawingState.hasColorTransform = matrix != identityMatrix;
1759 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001760 setTransactionFlags(eTransactionNeeded);
1761 return true;
1762}
1763
chaviwf66724d2018-11-28 16:35:21 -08001764mat4 Layer::getColorTransform() const {
1765 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001766 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001767 colorTransform = parent->getColorTransform() * colorTransform;
1768 }
1769 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001770}
1771
1772bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001773 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001774 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001775 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1776 }
1777 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001778}
1779
Chia-I Wu11481472018-05-04 10:43:19 -07001780bool Layer::isLegacyDataSpace() const {
1781 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001782 return !(getDataSpace() &
1783 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1784 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001785}
1786
Robert Carr1f0a16a2016-10-24 16:27:39 -07001787void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001788 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001789}
1790
Robert Carr6a160312021-05-17 12:08:20 -07001791int32_t Layer::getZ(LayerVector::StateSet) const {
1792 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001793}
1794
Robert Carr1c5481e2019-07-01 14:42:27 -07001795bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001796 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001797 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001798 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001799}
1800
David Sodman41fdfc92017-11-06 16:09:56 -08001801__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001802 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001803 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1804 "makeTraversalList received invalid stateSet");
1805 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1806 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001807 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001808
Robert Carr29abff82017-12-04 13:51:20 -08001809 if (state.zOrderRelatives.size() == 0) {
1810 *outSkipRelativeZUsers = true;
1811 return children;
1812 }
1813
chaviwfd462612018-05-31 16:11:27 -07001814 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001815 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001816 sp<Layer> strongRelative = weakRelative.promote();
1817 if (strongRelative != nullptr) {
1818 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001819 }
1820 }
1821
Dan Stoza412903f2017-04-27 13:42:17 -07001822 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001823 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001824 continue;
1825 }
Robert Carrdb66e622017-04-10 16:55:57 -07001826 traverse.add(child);
1827 }
1828
1829 return traverse;
1830}
1831
Robert Carr1f0a16a2016-10-24 16:27:39 -07001832/**
Robert Carrdb66e622017-04-10 16:55:57 -07001833 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001834 */
Dan Stoza412903f2017-04-27 13:42:17 -07001835void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001836 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1837 // produce a new list for traversing, including our relatives, and not including our children
1838 // who are relatives of another surface. In the case that there are no relative Z,
1839 // makeTraversalList returns our children directly to avoid significant overhead.
1840 // However in this case we need to take the responsibility for filtering children which
1841 // are relatives of another surface here.
1842 bool skipRelativeZUsers = false;
1843 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001844
Robert Carr1f0a16a2016-10-24 16:27:39 -07001845 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001846 for (; i < list.size(); i++) {
1847 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001848 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1849 continue;
1850 }
1851
chaviw301b1d82019-11-06 13:15:09 -08001852 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001853 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001854 }
Dan Stoza412903f2017-04-27 13:42:17 -07001855 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001856 }
Robert Carr29abff82017-12-04 13:51:20 -08001857
Dan Stoza412903f2017-04-27 13:42:17 -07001858 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001859 for (; i < list.size(); i++) {
1860 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001861
Robert Carr29abff82017-12-04 13:51:20 -08001862 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1863 continue;
1864 }
Dan Stoza412903f2017-04-27 13:42:17 -07001865 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001866 }
1867}
1868
1869/**
Robert Carrdb66e622017-04-10 16:55:57 -07001870 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001871 */
Dan Stoza412903f2017-04-27 13:42:17 -07001872void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1873 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001874 // See traverseInZOrder for documentation.
1875 bool skipRelativeZUsers = false;
1876 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001877
Robert Carr1f0a16a2016-10-24 16:27:39 -07001878 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001879 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001880 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001881
1882 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1883 continue;
1884 }
1885
chaviw301b1d82019-11-06 13:15:09 -08001886 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001887 break;
1888 }
Dan Stoza412903f2017-04-27 13:42:17 -07001889 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001890 }
Dan Stoza412903f2017-04-27 13:42:17 -07001891 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001892 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001893 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001894
1895 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1896 continue;
1897 }
1898
Dan Stoza412903f2017-04-27 13:42:17 -07001899 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001900 }
1901}
1902
Edgar Arriaga844fa672020-01-16 14:21:42 -08001903void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1904 visitor(this);
1905 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001906 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001907 for (const sp<Layer>& child : children) {
1908 child->traverse(state, visitor);
1909 }
1910}
1911
Vishnu Nair787aa782023-03-17 13:46:46 -07001912void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
1913 for (const sp<Layer>& child : mDrawingChildren) {
1914 visitor(child.get());
1915 }
1916}
1917
chaviw4b129c22018-04-09 16:19:43 -07001918LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1919 const std::vector<Layer*>& layersInTree) {
1920 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1921 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001922 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1923 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001924 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001925
chaviwfd462612018-05-31 16:11:27 -07001926 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001927 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1928 sp<Layer> strongRelative = weakRelative.promote();
1929 // Only add relative layers that are also descendents of the top most parent of the tree.
1930 // If a relative layer is not a descendent, then it should be ignored.
1931 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1932 traverse.add(strongRelative);
1933 }
1934 }
1935
1936 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001937 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001938 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1939 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1940 // the child here since it won't be added later as a relative.
1941 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1942 childState.zOrderRelativeOf.promote().get())) {
1943 continue;
1944 }
1945 traverse.add(child);
1946 }
1947
1948 return traverse;
1949}
1950
1951void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1952 LayerVector::StateSet stateSet,
1953 const LayerVector::Visitor& visitor) {
1954 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001955
1956 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001957 for (; i < list.size(); i++) {
1958 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001959 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001960 break;
1961 }
chaviw4b129c22018-04-09 16:19:43 -07001962 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001963 }
chaviw4b129c22018-04-09 16:19:43 -07001964
chaviwa76b2712017-09-20 12:02:26 -07001965 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001966 for (; i < list.size(); i++) {
1967 const auto& relative = list[i];
1968 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001969 }
1970}
1971
chaviw4b129c22018-04-09 16:19:43 -07001972std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1973 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1974 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1975
1976 std::vector<Layer*> layersInTree = {this};
1977 for (size_t i = 0; i < children.size(); i++) {
1978 const auto& child = children[i];
1979 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1980 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1981 }
1982
1983 return layersInTree;
1984}
1985
1986void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1987 const LayerVector::Visitor& visitor) {
1988 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1989 std::sort(layersInTree.begin(), layersInTree.end());
1990 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1991}
1992
Peiyong Linefefaac2018-08-17 12:27:51 -07001993ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001994 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001995}
1996
Garfield Tan2c1782c2022-02-16 15:25:05 -08001997bool Layer::isTransformValid() const {
1998 float transformDet = getTransform().det();
1999 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2000}
2001
chaviw13fdc492017-06-27 12:40:18 -07002002half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002003 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002004
chaviw13fdc492017-06-27 12:40:18 -07002005 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2006 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002007}
Robert Carr6452f122017-03-21 10:41:29 -07002008
Vishnu Nair6213bd92020-05-08 17:42:25 -07002009ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002010 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002011 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2012 return fixedTransformHint;
2013 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002014 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002015 if (!p) return fixedTransformHint;
2016 return p->getFixedTransformHint();
2017}
2018
chaviw13fdc492017-06-27 12:40:18 -07002019half4 Layer::getColor() const {
2020 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002021 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002022}
Robert Carr6452f122017-03-21 10:41:29 -07002023
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002024int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002025 if (getDrawingState().backgroundBlurRadius == 0) {
2026 return 0;
2027 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002028
Vishnu Nair29810f72022-07-01 16:38:41 +00002029 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002030 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2031 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002032}
2033
Galia Peychevae0acf382021-04-12 21:22:34 +02002034const std::vector<BlurRegion> Layer::getBlurRegions() const {
2035 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002036 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002037 for (auto& region : regionsCopy) {
2038 region.alpha = region.alpha * layerAlpha;
2039 }
2040 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002041}
2042
Vishnu Naire14c6b32022-08-06 04:20:15 +00002043RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002044 // Get parent settings
2045 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002046 const auto& parent = mDrawingParent.promote();
2047 if (parent != nullptr) {
2048 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002049 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002050 ui::Transform t = getActiveTransform(getDrawingState());
2051 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002052 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002053 parentSettings.radius.x *= t.getScaleX();
2054 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002055 }
2056 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002057
2058 // Get layer settings
2059 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002060 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002061 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002062 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002063
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002064 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002065 // If the parent and the layer have rounded corner settings, use the parent settings if the
2066 // parent crop is entirely inside the layer crop.
2067 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2068 if (parentSettings.cropRect.left > layerCropRect.left &&
2069 parentSettings.cropRect.top > layerCropRect.top &&
2070 parentSettings.cropRect.right < layerCropRect.right &&
2071 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2072 return parentSettings;
2073 } else {
2074 return layerSettings;
2075 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002076 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002077 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002078 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002079 return parentSettings;
2080 }
2081 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002082}
2083
Robert Carr88b85e12022-03-21 15:47:35 -07002084bool Layer::findInHierarchy(const sp<Layer>& l) {
2085 if (l == this) {
2086 return true;
2087 }
2088 for (auto& child : mDrawingChildren) {
2089 if (child->findInHierarchy(l)) {
2090 return true;
2091 }
2092 }
2093 return false;
2094}
2095
Robert Carr1f0a16a2016-10-24 16:27:39 -07002096void Layer::commitChildList() {
2097 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2098 const auto& child = mCurrentChildren[i];
2099 child->commitChildList();
2100 }
2101 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002102 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002103 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2104 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2105 if (zOrderRelativeOf == nullptr) return;
2106 if (findInHierarchy(zOrderRelativeOf)) {
2107 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2108 zOrderRelativeOf->mName.c_str());
2109 ALOGE("Severing rel Z loop, potentially dangerous");
2110 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002111 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002112 }
2113 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002114}
2115
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002116
chaviw3277faf2021-05-19 16:45:23 -05002117void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002118 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002119 mDrawingState.touchableRegionCrop =
2120 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002121 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002122 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002123 setTransactionFlags(eTransactionNeeded);
2124}
2125
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002126LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002127 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002128 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002129 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2130
Vishnu Nair00b90132021-11-05 14:03:40 -07002131 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nair2f65e972023-04-04 16:36:28 +00002132 ui::LayerStack layerStack =
2133 (mSnapshot) ? mSnapshot->outputFilter.layerStack : ui::INVALID_LAYER_STACK;
2134 writeCompositionStateToProto(layerProto, layerStack);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002135 }
2136
chaviw08f3cb22020-01-13 13:17:21 -08002137 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002138 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002139 }
chaviw6d89e2d2020-01-14 14:42:01 -08002140
2141 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002142}
2143
Vishnu Nair2f65e972023-04-04 16:36:28 +00002144void Layer::writeCompositionStateToProto(LayerProto* layerProto, ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002145 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002146 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +00002147
2148 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002149 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002150 const auto compositionType = getCompositionType(*display);
2151 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +00002152 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +00002153 [&]() { return layerProto->mutable_visible_region(); });
2154 }
2155}
2156
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002157void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002158 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002159 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002160 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002161 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002162 [&]() { return layerInfo->mutable_active_buffer(); });
2163 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2164 layerInfo->mutable_buffer_transform());
2165 }
2166 layerInfo->set_invalidate(contentDirty);
2167 layerInfo->set_is_protected(isProtected());
2168 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2169 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002170 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002171 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002172 layerInfo->set_corner_radius(
2173 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002174 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2175 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2176 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2177 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2178 [&]() { return layerInfo->mutable_position(); });
2179 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002180 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2181 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002182
Vishnu Nair00b90132021-11-05 14:03:40 -07002183 if (hasColorTransform()) {
2184 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002185 }
2186
Vishnu Nair60db8c02020-04-02 11:55:16 -07002187 LayerProtoHelper::writeToProto(mSourceBounds,
2188 [&]() { return layerInfo->mutable_source_bounds(); });
2189 LayerProtoHelper::writeToProto(mScreenBounds,
2190 [&]() { return layerInfo->mutable_screen_bounds(); });
2191 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2192 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2193 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002194}
2195
2196void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002197 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002198 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2199 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002200 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002201
chaviw766c9c52021-02-10 17:36:47 -08002202 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002203
Vishnu Nair00b90132021-11-05 14:03:40 -07002204 layerInfo->set_id(sequence);
2205 layerInfo->set_name(getName().c_str());
2206 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002207
Vishnu Nair00b90132021-11-05 14:03:40 -07002208 for (const auto& child : children) {
2209 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002210 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002211
Vishnu Nair00b90132021-11-05 14:03:40 -07002212 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2213 sp<Layer> strongRelative = weakRelative.promote();
2214 if (strongRelative != nullptr) {
2215 layerInfo->add_relatives(strongRelative->sequence);
2216 }
2217 }
2218
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002219 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002220 [&]() { return layerInfo->mutable_transparent_region(); });
2221
2222 layerInfo->set_layer_stack(getLayerStack().id);
2223 layerInfo->set_z(state.z);
2224
2225 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2226 return layerInfo->mutable_requested_position();
2227 });
2228
Vishnu Nair00b90132021-11-05 14:03:40 -07002229 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2230
2231 layerInfo->set_is_opaque(isOpaque(state));
2232
2233 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2234 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2235 LayerProtoHelper::writeToProto(state.color,
2236 [&]() { return layerInfo->mutable_requested_color(); });
2237 layerInfo->set_flags(state.flags);
2238
2239 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2240 layerInfo->mutable_requested_transform());
2241
2242 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2243 if (parent != nullptr) {
2244 layerInfo->set_parent(parent->sequence);
2245 } else {
2246 layerInfo->set_parent(-1);
2247 }
2248
2249 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2250 if (zOrderRelativeOf != nullptr) {
2251 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2252 } else {
2253 layerInfo->set_z_order_relative_of(-1);
2254 }
2255
2256 layerInfo->set_is_relative_of(state.isRelativeOf);
2257
2258 layerInfo->set_owner_uid(mOwnerUid);
2259
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002260 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002261 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002262 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002263 info = fillInputInfo(
2264 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002265 } else {
2266 info = state.inputInfo;
2267 }
2268
2269 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002270 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002271 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002272
Vishnu Nair00b90132021-11-05 14:03:40 -07002273 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002274 auto protoMap = layerInfo->mutable_metadata();
2275 for (const auto& entry : state.metadata.mMap) {
2276 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2277 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002278 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002279
2280 LayerProtoHelper::writeToProto(state.destinationFrame,
2281 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002282}
2283
Robert Carr2e102c92018-10-23 12:11:15 -07002284bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002285 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002286}
2287
Prabir Pradhan33da9462022-06-14 14:55:57 +00002288// Applies the given transform to the region, while protecting against overflows caused by any
2289// offsets. If applying the offset in the transform to any of the Rects in the region would result
2290// in an overflow, they are not added to the output Region.
2291static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2292 const std::string& debugWindowName) {
2293 // Round the translation using the same rounding strategy used by ui::Transform.
2294 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2295 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2296
2297 ui::Transform transformWithoutOffset = t;
2298 transformWithoutOffset.set(0.f, 0.f);
2299
2300 const Region transformed = transformWithoutOffset.transform(r);
2301
2302 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2303 Region ret;
2304 for (const auto& rect : transformed) {
2305 Rect newRect;
2306 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2307 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2308 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2309 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2310 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2311 debugWindowName.c_str());
2312 continue;
2313 }
2314 ret.orSelf(newRect);
2315 }
2316 return ret;
2317}
2318
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002319void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002320 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2321 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002322 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002323 }
2324
Vishnu Nairfed7c122023-03-18 01:54:43 +00002325 const Rect roundedFrameInDisplay = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002326 info.frameLeft = roundedFrameInDisplay.left;
2327 info.frameTop = roundedFrameInDisplay.top;
2328 info.frameRight = roundedFrameInDisplay.right;
2329 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002330
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002331 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002332 inputToLayer.set(inputBounds.left, inputBounds.top);
2333 const ui::Transform layerToScreen = getInputTransform();
2334 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002335
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002336 // InputDispatcher expects a display-to-input transform.
2337 info.transform = inputToDisplay.inverse();
2338
2339 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002340 info.touchableRegion =
2341 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002342}
2343
chaviw3277faf2021-05-19 16:45:23 -05002344void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002345 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002346 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002347 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002348 }
2349 if (p != nullptr) {
2350 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2351 }
2352}
2353
Vishnu Naira066d902021-09-13 18:40:17 -07002354gui::DropInputMode Layer::getDropInputMode() const {
2355 gui::DropInputMode mode = mDrawingState.dropInputMode;
2356 if (mode == gui::DropInputMode::ALL) {
2357 return mode;
2358 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002359 sp<Layer> parent = mDrawingParent.promote();
2360 if (parent) {
2361 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002362 if (parentMode != gui::DropInputMode::NONE) {
2363 return parentMode;
2364 }
2365 }
2366 return mode;
2367}
2368
2369void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002370 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002371 return;
2372 }
2373
2374 // Check if we need to drop input unconditionally
2375 gui::DropInputMode dropInputMode = getDropInputMode();
2376 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002377 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002378 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2379 return;
2380 }
2381
2382 // Check if we need to check if the window is obscured by parent
2383 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2384 return;
2385 }
2386
2387 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002388 sp<Layer> parent = mDrawingParent.promote();
2389 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002390 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002391 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2392 static_cast<float>(getAlpha()));
2393 }
2394
2395 // Check if the parent has cropped the buffer
2396 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2397 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002398 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002399 return;
2400 }
2401
2402 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2403 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2404 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2405 // match then the layer has not been cropped by its parents.
2406 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2407 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2408
2409 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002410 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002411 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2412 getDebugName());
2413 } else {
2414 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2415 // input if the window is obscured. This check should be done in surfaceflinger but the
2416 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2417 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002418 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002419 }
2420}
2421
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002422WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002423 if (!hasInputInfo()) {
2424 mDrawingState.inputInfo.name = getName();
2425 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2426 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002427 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002428 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002429 }
2430
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002431 const ui::Transform& displayTransform =
2432 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2433
chaviw3277faf2021-05-19 16:45:23 -05002434 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002435 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002436 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002437
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002438 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002439
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002440 if (displayArgs.transform == nullptr) {
2441 // Do not let the window receive touches if it is not associated with a valid display
2442 // transform. We still allow the window to receive keys and prevent ANRs.
2443 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2444 }
2445
Patrick Williams1caf3b72023-03-31 10:59:10 -05002446 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !isVisibleForInput());
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002447
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002448 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002449 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002450 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002451
Vishnu Nair16a938f2021-09-24 07:14:54 -07002452 // If the window will be blacked out on a display because the display does not have the secure
2453 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002454 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002455 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002456 }
2457
Vishnu Nairfed7c122023-03-18 01:54:43 +00002458 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002459 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002460 Rect inputBoundsInDisplaySpace;
2461 if (!cropLayer) {
2462 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2463 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2464 } else {
2465 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2466 inputBoundsInDisplaySpace =
2467 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2468 }
2469 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002470 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002471 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2472 Rect inputBoundsInDisplaySpace =
2473 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2474 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002475 }
2476
Winson Chunga30f7c92021-06-29 15:42:56 -07002477 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2478 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002479 if (isTrustedOverlay()) {
2480 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2481 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002482
chaviwaf87b3e2019-10-01 16:59:28 -07002483 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2484 // touches from going outside the cloned area.
2485 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002486 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002487 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2488 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002489 info.touchableRegion = info.touchableRegion.intersect(rect);
2490 }
2491 }
2492
Robert Carr720e5062018-07-30 17:45:14 -07002493 return info;
2494}
2495
Vishnu Nairfed7c122023-03-18 01:54:43 +00002496Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2497 const ui::Transform& screenToDisplay) {
2498 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2499 // frame and transform used for the layer, which determines the bounds and the coordinate space
2500 // within which the layer will receive input.
2501
2502 // Coordinate space definitions:
2503 // - display: The display device's coordinate space. Correlates to pixels on the display.
2504 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2505 // - layer: The coordinate space of this layer.
2506 // - input: The coordinate space in which this layer will receive input events. This could be
2507 // different than layer space if a surfaceInset is used, which changes the origin
2508 // of the input space.
2509
2510 // Crop the input bounds to ensure it is within the parent's bounds.
2511 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2512 const ui::Transform layerToScreen = getInputTransform();
2513 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2514 return Rect{layerToDisplay.transform(croppedInputBounds)};
2515}
2516
chaviwaf87b3e2019-10-01 16:59:28 -07002517sp<Layer> Layer::getClonedRoot() {
2518 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002519 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002520 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002521 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002522 return nullptr;
2523 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002524 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002525}
2526
Robert Carredd13602020-04-13 17:24:34 -07002527bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002528 return mDrawingState.inputInfo.token != nullptr ||
2529 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002530}
2531
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002532compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002533 const DisplayDevice* display) const {
2534 if (!display) return nullptr;
Vishnu Naird47bcee2023-02-24 18:08:51 +00002535 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2536 return display->getCompositionDisplay()->getOutputLayerForLayer(
2537 getCompositionEngineLayerFE());
2538 }
2539 sp<LayerFE> layerFE;
2540 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2541 for (auto& [p, layer] : mLayerFEs) {
2542 if (p == path) {
2543 layerFE = layer;
2544 }
2545 }
2546
2547 if (!layerFE) return nullptr;
2548 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002549}
2550
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002551Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2552 const auto outputLayer = findOutputLayerForDisplay(display);
2553 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002554}
2555
Vishnu Nairde177252023-04-21 12:44:10 -07002556void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom, uint32_t mirrorRootId) {
2557 mSnapshot->path.id = clonedFrom->getSequence();
2558 mSnapshot->path.mirrorRootId = mirrorRootId;
2559
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002560 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002561 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002562 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2563 mPotentialCursor = clonedFrom->mPotentialCursor;
2564 mProtectedByApp = clonedFrom->mProtectedByApp;
2565 updateCloneBufferInfo();
2566}
2567
2568void Layer::updateCloneBufferInfo() {
2569 if (!isClone() || !isClonedFromAlive()) {
2570 return;
2571 }
2572
2573 sp<Layer> clonedFrom = getClonedFrom();
2574 mBufferInfo = clonedFrom->mBufferInfo;
2575 mSidebandStream = clonedFrom->mSidebandStream;
2576 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2577 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2578 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2579
2580 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2581 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2582 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2583 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2584 // the cloned drawingState again.
2585 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2586 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2587 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2588 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2589
2590 cloneDrawingState(clonedFrom.get());
2591
2592 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2593 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2594 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2595 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002596}
chaviw74b03172019-08-19 11:09:03 -07002597
Vishnu Nair3be61902023-04-26 19:47:29 -07002598bool Layer::updateMirrorInfo(const std::deque<Layer*>& cloneRootsPendingUpdates) {
chaviw74b03172019-08-19 11:09:03 -07002599 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2600 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2601 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2602 // that case, we want to delete the reference to the clone since we want it to get
2603 // destroyed. The root, this layer, will still be around since the client can continue
2604 // to hold a reference, but no cloned layers will be displayed.
2605 mClonedChild = nullptr;
Vishnu Nair3be61902023-04-26 19:47:29 -07002606 return true;
chaviw74b03172019-08-19 11:09:03 -07002607 }
2608
2609 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2610 // If the real layer exists and is in current state, add the clone as a child of the root.
2611 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2612 // copied to drawingState for the root layer. So the clonedChild is always removed from
2613 // drawingState and then needs to be added back each traversal.
2614 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2615 addChildToDrawing(mClonedChild);
2616 }
2617
2618 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002619 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002620 mClonedChild->updateClonedRelatives(clonedLayersMap);
Vishnu Nair3be61902023-04-26 19:47:29 -07002621
2622 for (Layer* root : cloneRootsPendingUpdates) {
2623 if (clonedLayersMap.find(sp<Layer>::fromExisting(root)) != clonedLayersMap.end()) {
2624 return false;
2625 }
2626 }
2627 return true;
chaviw74b03172019-08-19 11:09:03 -07002628}
2629
2630void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2631 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2632 // to the clone. If the real layer is no longer alive, continue traversing the children
2633 // since we may be able to pull out other children that are still alive.
2634 if (isClonedFromAlive()) {
2635 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002636 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002637 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002638 }
2639
2640 // The clone layer may have children in drawingState since they may have been created and
2641 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2642 // that already exist, since we can just re-use them.
2643 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2644 // not updated in the regular traversal. They are skipped since the root will lose the
2645 // reference to them when it copies its currentChildren to drawing.
2646 for (sp<Layer>& child : mDrawingChildren) {
2647 child->updateClonedDrawingState(clonedLayersMap);
2648 }
2649}
2650
2651void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2652 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2653 mDrawingChildren.clear();
2654
2655 if (!isClonedFromAlive()) {
2656 return;
2657 }
2658
2659 sp<Layer> clonedFrom = getClonedFrom();
2660 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2661 if (child == mirrorRoot) {
2662 // This is to avoid cyclical mirroring.
2663 continue;
2664 }
2665 sp<Layer> clonedChild = clonedLayersMap[child];
2666 if (clonedChild == nullptr) {
Vishnu Nairde177252023-04-21 12:44:10 -07002667 clonedChild = child->createClone(mirrorRoot->getSequence());
chaviw74b03172019-08-19 11:09:03 -07002668 clonedLayersMap[child] = clonedChild;
2669 }
2670 addChildToDrawing(clonedChild);
2671 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2672 }
2673}
2674
chaviwaf87b3e2019-10-01 16:59:28 -07002675void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2676 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2677 if (cropLayer != nullptr) {
2678 if (clonedLayersMap.count(cropLayer) == 0) {
2679 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2680 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002681 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002682 } else {
2683 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2684 mDrawingState.touchableRegionCrop = clonedCropLayer;
2685 }
2686 }
2687 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2688 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002689 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002690}
2691
2692void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002693 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002694 mDrawingState.zOrderRelatives.clear();
2695
2696 if (!isClonedFromAlive()) {
2697 return;
2698 }
2699
chaviwaf87b3e2019-10-01 16:59:28 -07002700 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002701 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002702 const sp<Layer>& relative = relativeWeak.promote();
2703 if (clonedLayersMap.count(relative) > 0) {
2704 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002705 mDrawingState.zOrderRelatives.add(clonedRelative);
2706 }
2707 }
2708
2709 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2710 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2711 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2712 // still traverse the children, but the layer with the missing relativeOf will not be shown
2713 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002714 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2715 if (clonedLayersMap.count(relativeOf) > 0) {
2716 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002717 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2718 }
2719
chaviwaf87b3e2019-10-01 16:59:28 -07002720 updateClonedInputInfo(clonedLayersMap);
2721
chaviw74b03172019-08-19 11:09:03 -07002722 for (sp<Layer>& child : mDrawingChildren) {
2723 child->updateClonedRelatives(clonedLayersMap);
2724 }
2725}
2726
2727void Layer::addChildToDrawing(const sp<Layer>& layer) {
2728 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002729 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002730}
2731
Steven Thomas62a4cf82020-01-31 12:04:03 -08002732Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2733 switch (compatibility) {
2734 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2735 return FrameRateCompatibility::Default;
2736 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2737 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002738 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2739 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002740 case ANATIVEWINDOW_FRAME_RATE_MIN:
2741 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002742 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2743 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002744 default:
2745 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2746 return FrameRateCompatibility::Default;
2747 }
2748}
2749
Marin Shalamanovc5986772021-03-16 16:09:49 +01002750scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2751 switch (strategy) {
2752 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2753 return Seamlessness::OnlySeamless;
2754 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2755 return Seamlessness::SeamedAndSeamless;
2756 default:
2757 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2758 return Seamlessness::Default;
2759 }
2760}
2761
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002762bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002763 const State& s(mDrawingState);
2764 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2765 return true;
2766 }
2767
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002768 sp<Layer> parent = mDrawingParent.promote();
2769 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002770}
2771
Robert Carr6a0382d2021-07-01 15:57:17 -07002772void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2773 mClonedChild = clonedChild;
2774 mHadClonedChild = true;
Vishnu Nair3be61902023-04-26 19:47:29 -07002775 mFlinger->mLayerMirrorRoots.push_back(this);
Robert Carr6a0382d2021-07-01 15:57:17 -07002776}
2777
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002778bool Layer::setDropInputMode(gui::DropInputMode mode) {
2779 if (mDrawingState.dropInputMode == mode) {
2780 return false;
2781 }
2782 mDrawingState.dropInputMode = mode;
2783 return true;
2784}
2785
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002786void Layer::cloneDrawingState(const Layer* from) {
2787 mDrawingState = from->mDrawingState;
2788 // Skip callback info since they are not applicable for cloned layers.
2789 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002790 // TODO (b/238781169) currently broken for mirror layers because we do not
2791 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002792 mDrawingState.callbackHandles = {};
2793}
2794
Patrick Williamsbb25f802022-08-30 23:02:34 +00002795void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2796 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002797 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002798 if (!listener) {
2799 return;
2800 }
2801 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002802 uint32_t currentMaxAcquiredBufferCount =
2803 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002804 listener->onReleaseBuffer({buffer->getId(), framenumber},
2805 releaseFence ? releaseFence : Fence::NO_FENCE,
2806 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002807}
2808
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002809void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
2810 ui::LayerStack layerStack) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002811 // If we are displayed on multiple displays in a single composition cycle then we would
2812 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2813 // For example we can only use it if all the displays are client comp, and we need
2814 // to merge all the client comp fences. We could do this, but for now we just
2815 // disable the optimization when a layer is composed on multiple displays.
2816 if (mClearClientCompositionFenceOnLayerDisplayed) {
2817 mLastClientCompositionFence = nullptr;
2818 } else {
2819 mClearClientCompositionFenceOnLayerDisplayed = true;
2820 }
2821
2822 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2823 // buffer that was presented on this layer. The first transaction that came in this frame that
2824 // replaced the previous buffer on this layer needs this release fence, because the fence will
2825 // let the client know when that previous buffer is removed from the screen.
2826 //
2827 // Every other transaction on this layer does not need a release fence because no other
2828 // Transactions that were set on this layer this frame are going to have their preceding buffer
2829 // removed from the display this frame.
2830 //
2831 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2832 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2833 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2834 // the previous buffer will be released this frame. The third transaction also contains a
2835 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2836 // transaction will now no longer be presented so it is released immediately and the third
2837 // transaction doesn't need a previous release fence.
2838 sp<CallbackHandle> ch;
2839 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002840 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002841 ch = handle;
2842 break;
2843 }
2844 }
2845
2846 // Prevent tracing the same release multiple times.
2847 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2848 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2849 }
2850
2851 if (ch != nullptr) {
2852 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2853 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2854 ch->name = mName;
2855 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002856 mPreviouslyPresentedLayerStacks.push_back(layerStack);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002857}
2858
2859void Layer::onSurfaceFrameCreated(
2860 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2861 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2862 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2863 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2864 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002865 if (hasBufferOrSidebandStreamInDrawing()) {
2866 // Only log for layers with a buffer, since we expect the jank data to be drained for
2867 // these, while there may be no jank listeners for bufferless layers.
2868 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2869 mName.c_str());
2870 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2871 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2872 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002873 mPendingJankClassifications.pop_front();
2874 }
2875 mPendingJankClassifications.emplace_back(surfaceFrame);
2876}
2877
2878void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2879 for (const auto& handle : mDrawingState.callbackHandles) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -07002880 if (mFlinger->mLayerLifecycleManagerEnabled) {
2881 handle->transformHint = mTransformHint;
2882 } else {
2883 handle->transformHint = mSkipReportingTransformHint
2884 ? std::nullopt
2885 : std::make_optional<uint32_t>(mTransformHintLegacy);
2886 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002887 handle->dequeueReadyTime = dequeueReadyTime;
2888 handle->currentMaxAcquiredBufferCount =
2889 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2890 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2891 handle->previousReleaseCallbackId.framenumber);
2892 }
2893
2894 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002895 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002896 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2897 break;
2898 }
2899 }
2900
2901 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002902 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002903 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2904 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002905 mDrawingState.callbackHandles = {};
2906}
2907
2908bool Layer::willPresentCurrentTransaction() const {
2909 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2910 return (getSidebandStreamChanged() || getAutoRefresh() ||
2911 (mDrawingState.modified &&
2912 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2913}
2914
2915bool Layer::setTransform(uint32_t transform) {
2916 if (mDrawingState.bufferTransform == transform) return false;
2917 mDrawingState.bufferTransform = transform;
2918 mDrawingState.modified = true;
2919 setTransactionFlags(eTransactionNeeded);
2920 return true;
2921}
2922
2923bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2924 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2925 mDrawingState.sequence++;
2926 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2927 mDrawingState.modified = true;
2928 setTransactionFlags(eTransactionNeeded);
2929 return true;
2930}
2931
2932bool Layer::setBufferCrop(const Rect& bufferCrop) {
2933 if (mDrawingState.bufferCrop == bufferCrop) return false;
2934
2935 mDrawingState.sequence++;
2936 mDrawingState.bufferCrop = bufferCrop;
2937
2938 mDrawingState.modified = true;
2939 setTransactionFlags(eTransactionNeeded);
2940 return true;
2941}
2942
2943bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2944 if (mDrawingState.destinationFrame == destinationFrame) return false;
2945
2946 mDrawingState.sequence++;
2947 mDrawingState.destinationFrame = destinationFrame;
2948
2949 mDrawingState.modified = true;
2950 setTransactionFlags(eTransactionNeeded);
2951 return true;
2952}
2953
2954// Translate destination frame into scale and position. If a destination frame is not set, use the
2955// provided scale and position
2956bool Layer::updateGeometry() {
2957 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2958 mDrawingState.destinationFrame.isEmpty()) {
2959 // If destination frame is not set, use the requested transform set via
2960 // Layer::setPosition and Layer::setMatrix.
2961 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2962 }
2963
2964 Rect destRect = mDrawingState.destinationFrame;
2965 int32_t destW = destRect.width();
2966 int32_t destH = destRect.height();
2967 if (destRect.left < 0) {
2968 destRect.left = 0;
2969 destRect.right = destW;
2970 }
2971 if (destRect.top < 0) {
2972 destRect.top = 0;
2973 destRect.bottom = destH;
2974 }
2975
2976 if (!mDrawingState.buffer) {
2977 ui::Transform t;
2978 t.set(destRect.left, destRect.top);
2979 return assignTransform(&mDrawingState.transform, t);
2980 }
2981
2982 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2983 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2984 // Undo any transformations on the buffer.
2985 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2986 std::swap(bufferWidth, bufferHeight);
2987 }
Leon Scroggins III85d4b222023-05-09 13:58:18 -04002988 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00002989 if (mDrawingState.transformToDisplayInverse) {
2990 if (invTransform & ui::Transform::ROT_90) {
2991 std::swap(bufferWidth, bufferHeight);
2992 }
2993 }
2994
2995 float sx = destW / static_cast<float>(bufferWidth);
2996 float sy = destH / static_cast<float>(bufferHeight);
2997 ui::Transform t;
2998 t.set(sx, 0, 0, sy);
2999 t.set(destRect.left, destRect.top);
3000 return assignTransform(&mDrawingState.transform, t);
3001}
3002
3003bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3004 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3005 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3006 return false;
3007 }
3008
3009 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3010
3011 mDrawingState.sequence++;
3012 mDrawingState.modified = true;
3013 setTransactionFlags(eTransactionNeeded);
3014
3015 return true;
3016}
3017
3018bool Layer::setPosition(float x, float y) {
3019 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3020 return false;
3021 }
3022
3023 mRequestedTransform.set(x, y);
3024
3025 mDrawingState.sequence++;
3026 mDrawingState.modified = true;
3027 setTransactionFlags(eTransactionNeeded);
3028
3029 return true;
3030}
3031
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003032void Layer::resetDrawingStateBufferInfo() {
3033 mDrawingState.producerId = 0;
3034 mDrawingState.frameNumber = 0;
3035 mDrawingState.releaseBufferListener = nullptr;
3036 mDrawingState.buffer = nullptr;
3037 mDrawingState.acquireFence = sp<Fence>::make(-1);
3038 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3039 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3040 mDrawingState.releaseBufferEndpoint = nullptr;
3041}
3042
Patrick Williamsbb25f802022-08-30 23:02:34 +00003043bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3044 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3045 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003046 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003047 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003048
3049 const bool frameNumberChanged =
3050 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3051 const uint64_t frameNumber =
3052 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003053 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003054
3055 if (mDrawingState.buffer) {
3056 mReleasePreviousBuffer = true;
3057 if (!mBufferInfo.mBuffer ||
3058 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3059 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3060 // If mDrawingState has a buffer, and we are about to update again
3061 // before swapping to drawing state, then the first buffer will be
3062 // dropped and we should decrement the pending buffer count and
3063 // call any release buffer callbacks if set.
3064 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3065 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003066 mDrawingState.acquireFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003067 decrementPendingBufferCount();
3068 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3069 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3070 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
3071 mDrawingState.bufferSurfaceFrameTX.reset();
3072 }
3073 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3074 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3075 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003076 mLastClientCompositionFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003077 mLastClientCompositionFence = nullptr;
3078 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003079 } else if (buffer) {
Vishnu Nairc09c0232023-03-02 03:22:35 +00003080 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3081 // we don't want to incorrectly classify a frame if we miss the desired present time.
3082 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003083 }
3084
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003085 mDrawingState.desiredPresentTime = desiredPresentTime;
3086 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3087 mDrawingState.latchedVsyncId = info.vsyncId;
Ady Abraham55269162023-05-09 11:26:06 -07003088 mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003089 mDrawingState.modified = true;
3090 if (!buffer) {
3091 resetDrawingStateBufferInfo();
3092 setTransactionFlags(eTransactionNeeded);
3093 mDrawingState.bufferSurfaceFrameTX = nullptr;
3094 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3095 return true;
3096 }
3097
liulijuneb489f62022-10-17 22:02:14 +08003098 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -07003099 mDrawingState.barrierProducerId =
3100 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003101 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -07003102 mDrawingState.barrierFrameNumber =
3103 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
3104
3105 // TODO(b/277265947) log and flush transaction trace when we detect out of order updates
Patrick Williamsbb25f802022-08-30 23:02:34 +00003106 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3107 mDrawingState.buffer = std::move(buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003108 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3109 ? bufferData.acquireFence
3110 : Fence::NO_FENCE;
3111 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3112 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3113 // We latched this buffer unsiganled, so we need to pass the acquire fence
3114 // on the callback instead of just the acquire time, since it's unknown at
3115 // this point.
3116 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3117 } else {
3118 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3119 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003120 setTransactionFlags(eTransactionNeeded);
3121
3122 const int32_t layerId = getSequence();
3123 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3124 mOwnerUid, postTime, getGameMode());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003125
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003126 if (mFlinger->mLegacyFrontEndEnabled) {
3127 recordLayerHistoryBufferUpdate(getLayerProps());
3128 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003129
3130 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3131
3132 if (dequeueTime && *dequeueTime != 0) {
3133 const uint64_t bufferId = mDrawingState.buffer->getId();
3134 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3135 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3136 FrameTracer::FrameEvent::DEQUEUE);
3137 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3138 FrameTracer::FrameEvent::QUEUE);
3139 }
3140
3141 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3142 return true;
3143}
3144
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003145void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3146 mDrawingState.desiredPresentTime = desiredPresentTime;
3147 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3148}
3149
3150void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps) {
Ady Abraham55269162023-05-09 11:26:06 -07003151 ATRACE_CALL();
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003152 const nsecs_t presentTime = [&] {
Ady Abraham55269162023-05-09 11:26:06 -07003153 if (!mDrawingState.isAutoTimestamp) {
3154 ATRACE_FORMAT_INSTANT("desiredPresentTime");
3155 return mDrawingState.desiredPresentTime;
3156 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003157
Ady Abraham55269162023-05-09 11:26:06 -07003158 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3159 const auto prediction =
3160 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3161 mDrawingState.latchedVsyncId);
3162 if (prediction.has_value()) {
3163 ATRACE_FORMAT_INSTANT("predictedPresentTime");
3164 return prediction->presentTime;
3165 }
3166 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003167
3168 return static_cast<nsecs_t>(0);
3169 }();
Ady Abraham55269162023-05-09 11:26:06 -07003170
3171 if (ATRACE_ENABLED() && presentTime > 0) {
3172 const auto presentIn = TimePoint::fromNs(presentTime) - TimePoint::now();
3173 ATRACE_FORMAT_INSTANT("presentIn %s", to_string(presentIn).c_str());
3174 }
3175
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003176 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3177 scheduler::LayerHistory::LayerUpdateType::Buffer);
3178}
3179
3180void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps) {
3181 const nsecs_t presentTime =
3182 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
3183 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3184 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3185}
3186
Patrick Williamsbb25f802022-08-30 23:02:34 +00003187bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003188 if (mDrawingState.dataspace == dataspace) return false;
3189 mDrawingState.dataspace = dataspace;
3190 mDrawingState.modified = true;
3191 setTransactionFlags(eTransactionNeeded);
3192 return true;
3193}
3194
John Reck68796592023-01-25 13:47:12 -05003195bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07003196 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3197 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05003198 return false;
Sally Qi963049b2023-03-23 14:06:21 -07003199 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3200 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05003201 mDrawingState.modified = true;
3202 setTransactionFlags(eTransactionNeeded);
3203 return true;
3204}
3205
Alec Mourif4af03e2023-02-11 00:25:24 +00003206bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3207 if (mDrawingState.cachingHint == cachingHint) return false;
3208 mDrawingState.cachingHint = cachingHint;
3209 mDrawingState.modified = true;
3210 setTransactionFlags(eTransactionNeeded);
3211 return true;
3212}
3213
Patrick Williamsbb25f802022-08-30 23:02:34 +00003214bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3215 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3216 mDrawingState.hdrMetadata = hdrMetadata;
3217 mDrawingState.modified = true;
3218 setTransactionFlags(eTransactionNeeded);
3219 return true;
3220}
3221
3222bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003223 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003224 mDrawingState.surfaceDamageRegion = surfaceDamage;
3225 mDrawingState.modified = true;
3226 setTransactionFlags(eTransactionNeeded);
3227 return true;
3228}
3229
3230bool Layer::setApi(int32_t api) {
3231 if (mDrawingState.api == api) return false;
3232 mDrawingState.api = api;
3233 mDrawingState.modified = true;
3234 setTransactionFlags(eTransactionNeeded);
3235 return true;
3236}
3237
3238bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3239 if (mDrawingState.sidebandStream == sidebandStream) return false;
3240
3241 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3242 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3243 } else if (sidebandStream != nullptr) {
3244 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3245 }
3246
3247 mDrawingState.sidebandStream = sidebandStream;
3248 mDrawingState.modified = true;
3249 setTransactionFlags(eTransactionNeeded);
3250 if (!mSidebandStreamChanged.exchange(true)) {
3251 // mSidebandStreamChanged was false
3252 mFlinger->onLayerUpdate();
3253 }
3254 return true;
3255}
3256
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003257bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3258 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003259 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3260 if (handles.empty()) {
3261 mReleasePreviousBuffer = false;
3262 return false;
3263 }
3264
Pascal Muetschard81cef292023-02-06 12:18:52 +01003265 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003266 for (const auto& handle : handles) {
3267 // If this transaction set a buffer on this layer, release its previous buffer
3268 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3269
3270 // If this layer will be presented in this frame
3271 if (willPresent) {
3272 // If this transaction set an acquire fence on this layer, set its acquire time
3273 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3274 handle->frameNumber = mDrawingState.frameNumber;
3275
3276 // Store so latched time and release fence can be set
3277 mDrawingState.callbackHandles.push_back(handle);
3278
3279 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003280 // Queue this handle to be notified below.
3281 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003282 }
3283 }
3284
Pascal Muetschard81cef292023-02-06 12:18:52 +01003285 if (!remainingHandles.empty()) {
3286 // Notify the transaction completed threads these handles are done. These are only the
3287 // handles that were not added to the mDrawingState, which will be notified later.
3288 std::vector<JankData> jankData;
3289 transferAvailableJankData(remainingHandles, jankData);
3290 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3291 }
3292
Patrick Williamsbb25f802022-08-30 23:02:34 +00003293 mReleasePreviousBuffer = false;
3294 mCallbackHandleAcquireTimeOrFence = -1;
3295
3296 return willPresent;
3297}
3298
3299Rect Layer::getBufferSize(const State& /*s*/) const {
3300 // for buffer state layers we use the display frame size as the buffer size.
3301
3302 if (mBufferInfo.mBuffer == nullptr) {
3303 return Rect::INVALID_RECT;
3304 }
3305
3306 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3307 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3308
3309 // Undo any transformations on the buffer and return the result.
3310 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3311 std::swap(bufWidth, bufHeight);
3312 }
3313
3314 if (getTransformToDisplayInverse()) {
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003315 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003316 if (invTransform & ui::Transform::ROT_90) {
3317 std::swap(bufWidth, bufHeight);
3318 }
3319 }
3320
3321 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3322}
3323
3324FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3325 if (mBufferInfo.mBuffer == nullptr) {
3326 return parentBounds;
3327 }
3328
3329 return getBufferSize(getDrawingState()).toFloatRect();
3330}
3331
3332bool Layer::fenceHasSignaled() const {
3333 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3334 return true;
3335 }
3336
3337 const bool fenceSignaled =
3338 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3339 if (!fenceSignaled) {
3340 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3341 TimeStats::LatchSkipReason::LateAcquire);
3342 }
3343
3344 return fenceSignaled;
3345}
3346
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003347void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003348 for (const auto& handle : mDrawingState.callbackHandles) {
3349 handle->refreshStartTime = refreshStartTime;
3350 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003351}
3352
3353void Layer::setAutoRefresh(bool autoRefresh) {
3354 mDrawingState.autoRefresh = autoRefresh;
3355}
3356
3357bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3358 // 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 +00003359 auto* snapshot = editLayerSnapshot();
3360 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003361
3362 if (mSidebandStreamChanged.exchange(false)) {
3363 const State& s(getDrawingState());
3364 // mSidebandStreamChanged was true
3365 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003366 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003367 if (mSidebandStream != nullptr) {
3368 setTransactionFlags(eTransactionNeeded);
3369 mFlinger->setTransactionFlags(eTraversalNeeded);
3370 }
3371 recomputeVisibleRegions = true;
3372
3373 return true;
3374 }
3375 return false;
3376}
3377
3378bool Layer::hasFrameUpdate() const {
3379 const State& c(getDrawingState());
3380 return (mDrawingStateModified || mDrawingState.modified) &&
3381 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3382}
3383
Vishnu Naird47bcee2023-02-24 18:08:51 +00003384void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003385 const State& s(getDrawingState());
3386
3387 if (!s.buffer) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003388 if (bgColorOnly || mBufferInfo.mBuffer) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003389 for (auto& handle : mDrawingState.callbackHandles) {
3390 handle->latchTime = latchTime;
3391 }
3392 }
3393 return;
3394 }
3395
3396 for (auto& handle : mDrawingState.callbackHandles) {
3397 if (handle->frameNumber == mDrawingState.frameNumber) {
3398 handle->latchTime = latchTime;
3399 }
3400 }
3401
3402 const int32_t layerId = getSequence();
3403 const uint64_t bufferId = mDrawingState.buffer->getId();
3404 const uint64_t frameNumber = mDrawingState.frameNumber;
3405 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3406 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3407 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3408
3409 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3410 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3411 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3412 FrameTracer::FrameEvent::LATCH);
3413
3414 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3415 if (bufferSurfaceFrame != nullptr &&
3416 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3417 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3418 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3419 // are processing the next state.
3420 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3421 mDrawingState.acquireFenceTime->getSignalTime(),
3422 latchTime);
3423 mDrawingState.bufferSurfaceFrameTX.reset();
3424 }
3425
3426 std::deque<sp<CallbackHandle>> remainingHandles;
3427 mFlinger->getTransactionCallbackInvoker()
3428 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3429 mDrawingState.callbackHandles = remainingHandles;
3430
3431 mDrawingStateModified = false;
3432}
3433
3434void Layer::gatherBufferInfo() {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003435 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3436 mPreviousReleaseBufferEndpoint = mBufferInfo.mReleaseBufferEndpoint;
3437 if (!mDrawingState.buffer) {
3438 mBufferInfo = {};
3439 return;
3440 }
3441
3442 if ((!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer))) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003443 decrementPendingBufferCount();
3444 }
3445
Patrick Williamsbb25f802022-08-30 23:02:34 +00003446 mBufferInfo.mBuffer = mDrawingState.buffer;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003447 mBufferInfo.mReleaseBufferEndpoint = mDrawingState.releaseBufferEndpoint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003448 mBufferInfo.mFence = mDrawingState.acquireFence;
3449 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3450 mBufferInfo.mPixelFormat =
3451 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3452 mBufferInfo.mFrameLatencyNeeded = true;
3453 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3454 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3455 mBufferInfo.mFence = mDrawingState.acquireFence;
3456 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3457 auto lastDataspace = mBufferInfo.mDataspace;
3458 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003459 if (mBufferInfo.mBuffer != nullptr) {
3460 auto& mapper = GraphicBufferMapper::get();
3461 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
3462 // and don't need to possibly remaps buffers.
3463 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
3464 status_t err = OK;
3465 {
3466 ATRACE_NAME("getDataspace");
3467 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
3468 }
3469 if (err != OK || dataspace != mBufferInfo.mDataspace) {
3470 {
3471 ATRACE_NAME("setDataspace");
3472 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
3473 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
3474 }
3475
3476 // Some GPU drivers may cache gralloc metadata which means before we composite we need
3477 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
3478 // compatible with old vendors, with a ticking clock.
3479 static const int32_t kVendorVersion =
3480 base::GetIntProperty("ro.vndk.version", __ANDROID_API_FUTURE__);
3481 if (const auto format =
3482 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
3483 mBufferInfo.mBuffer->getPixelFormat());
3484 err == OK && kVendorVersion < __ANDROID_API_U__ &&
3485 (format ==
3486 aidl::android::hardware::graphics::common::PixelFormat::
3487 IMPLEMENTATION_DEFINED ||
3488 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
3489 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
3490 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
3491 mBufferInfo.mBuffer->remapBuffer();
3492 }
3493 }
3494 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003495 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003496 mFlinger->mHdrLayerInfoChanged = true;
3497 }
Sally Qi963049b2023-03-23 14:06:21 -07003498 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3499 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05003500 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003501 }
3502 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3503 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3504 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3505 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3506 mBufferInfo.mApi = mDrawingState.api;
3507 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003508}
3509
3510Rect Layer::computeBufferCrop(const State& s) {
3511 if (s.buffer && !s.bufferCrop.isEmpty()) {
3512 Rect bufferCrop;
3513 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3514 return bufferCrop;
3515 } else if (s.buffer) {
3516 return s.buffer->getBounds();
3517 } else {
3518 return s.bufferCrop;
3519 }
3520}
3521
Vishnu Nairde177252023-04-21 12:44:10 -07003522sp<Layer> Layer::createClone(uint32_t mirrorRootId) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003523 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3524 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003525 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Vishnu Nairde177252023-04-21 12:44:10 -07003526 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this), mirrorRootId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003527 return layer;
3528}
3529
Patrick Williamsbb25f802022-08-30 23:02:34 +00003530void Layer::decrementPendingBufferCount() {
3531 int32_t pendingBuffers = --mPendingBufferTransactions;
3532 tracePendingBufferCount(pendingBuffers);
3533}
3534
3535void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3536 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3537}
3538
3539/*
3540 * We don't want to send the layer's transform to input, but rather the
3541 * parent's transform. This is because Layer's transform is
3542 * information about how the buffer is placed on screen. The parent's
3543 * transform makes more sense to send since it's information about how the
3544 * layer is placed on screen. This transform is used by input to determine
3545 * how to go from screen space back to window space.
3546 */
3547ui::Transform Layer::getInputTransform() const {
3548 if (!hasBufferOrSidebandStream()) {
3549 return getTransform();
3550 }
3551 sp<Layer> parent = mDrawingParent.promote();
3552 if (parent == nullptr) {
3553 return ui::Transform();
3554 }
3555
3556 return parent->getTransform();
3557}
3558
3559/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003560 * Returns the bounds used to fill the input frame and the touchable region.
3561 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003562 * Similar to getInputTransform, we need to update the bounds to include the transform.
3563 * This is because bounds don't include the buffer transform, where the input assumes
3564 * that's already included.
3565 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003566std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3567 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3568 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3569 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3570 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3571 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003572 }
3573
Vishnu Nairfed7c122023-03-18 01:54:43 +00003574 bool inputBoundsValid = croppedBufferSize.isValid();
3575 if (!inputBoundsValid) {
3576 /**
3577 * Input bounds are based on the layer crop or buffer size. But if we are using
3578 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3579 * we can use the parent bounds as the input bounds if the layer does not have buffer
3580 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3581 * use the parent bounds. A layer without a buffer can get input. So when a window is
3582 * initially added, its touchable region can fill its parent layer bounds and that can
3583 * have negative consequences.
3584 */
3585 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003586 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003587
3588 // Clamp surface inset to the input bounds.
3589 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3590 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3591 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3592
3593 // Apply the insets to the input bounds.
3594 inputBounds.left += xSurfaceInset;
3595 inputBounds.top += ySurfaceInset;
3596 inputBounds.right -= xSurfaceInset;
3597 inputBounds.bottom -= ySurfaceInset;
3598
3599 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003600}
3601
Ady Abraham005398b2023-06-05 13:59:41 -07003602bool Layer::isSimpleBufferUpdate(const layer_state_t& s) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003603 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3604
3605 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3606 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3607 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3608 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3609 layer_state_t::eReparent;
3610
Patrick Williamsbb25f802022-08-30 23:02:34 +00003611 if ((s.what & requiredFlags) != requiredFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003612 ATRACE_FORMAT_INSTANT("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3613 (s.what | requiredFlags) & ~s.what);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003614 return false;
3615 }
3616
3617 if (s.what & deniedFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003618 ATRACE_FORMAT_INSTANT("%s: false [has denied flags 0x%" PRIx64 "]", __func__,
3619 s.what & deniedFlags);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003620 return false;
3621 }
3622
Patrick Williamsbb25f802022-08-30 23:02:34 +00003623 if (s.what & layer_state_t::ePositionChanged) {
3624 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
Ady Abraham005398b2023-06-05 13:59:41 -07003625 ATRACE_FORMAT_INSTANT("%s: false [ePositionChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003626 return false;
3627 }
3628 }
3629
3630 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003631 if (mDrawingState.color.a != s.color.a) {
Ady Abraham005398b2023-06-05 13:59:41 -07003632 ATRACE_FORMAT_INSTANT("%s: false [eAlphaChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003633 return false;
3634 }
3635 }
3636
3637 if (s.what & layer_state_t::eColorTransformChanged) {
3638 if (mDrawingState.colorTransform != s.colorTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003639 ATRACE_FORMAT_INSTANT("%s: false [eColorTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003640 return false;
3641 }
3642 }
3643
3644 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003645 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Ady Abraham005398b2023-06-05 13:59:41 -07003646 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundColorChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003647 return false;
3648 }
3649 }
3650
3651 if (s.what & layer_state_t::eMatrixChanged) {
3652 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3653 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3654 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3655 mRequestedTransform.dsdy() != s.matrix.dsdy) {
Ady Abraham005398b2023-06-05 13:59:41 -07003656 ATRACE_FORMAT_INSTANT("%s: false [eMatrixChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003657 return false;
3658 }
3659 }
3660
3661 if (s.what & layer_state_t::eCornerRadiusChanged) {
3662 if (mDrawingState.cornerRadius != s.cornerRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003663 ATRACE_FORMAT_INSTANT("%s: false [eCornerRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003664 return false;
3665 }
3666 }
3667
3668 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3669 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
Ady Abraham005398b2023-06-05 13:59:41 -07003670 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003671 return false;
3672 }
3673 }
3674
Vishnu Nairbbceb462022-10-10 04:52:13 +00003675 if (s.what & layer_state_t::eBufferTransformChanged) {
3676 if (mDrawingState.bufferTransform != s.bufferTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003677 ATRACE_FORMAT_INSTANT("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003678 return false;
3679 }
3680 }
3681
3682 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3683 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
Ady Abraham005398b2023-06-05 13:59:41 -07003684 ATRACE_FORMAT_INSTANT("%s: false [eTransformToDisplayInverseChanged changed]",
3685 __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003686 return false;
3687 }
3688 }
3689
3690 if (s.what & layer_state_t::eCropChanged) {
3691 if (mDrawingState.crop != s.crop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003692 ATRACE_FORMAT_INSTANT("%s: false [eCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003693 return false;
3694 }
3695 }
3696
3697 if (s.what & layer_state_t::eDataspaceChanged) {
3698 if (mDrawingState.dataspace != s.dataspace) {
Ady Abraham005398b2023-06-05 13:59:41 -07003699 ATRACE_FORMAT_INSTANT("%s: false [eDataspaceChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003700 return false;
3701 }
3702 }
3703
3704 if (s.what & layer_state_t::eHdrMetadataChanged) {
3705 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
Ady Abraham005398b2023-06-05 13:59:41 -07003706 ATRACE_FORMAT_INSTANT("%s: false [eHdrMetadataChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003707 return false;
3708 }
3709 }
3710
3711 if (s.what & layer_state_t::eSidebandStreamChanged) {
3712 if (mDrawingState.sidebandStream != s.sidebandStream) {
Ady Abraham005398b2023-06-05 13:59:41 -07003713 ATRACE_FORMAT_INSTANT("%s: false [eSidebandStreamChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003714 return false;
3715 }
3716 }
3717
3718 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3719 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
Ady Abraham005398b2023-06-05 13:59:41 -07003720 ATRACE_FORMAT_INSTANT("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003721 return false;
3722 }
3723 }
3724
3725 if (s.what & layer_state_t::eShadowRadiusChanged) {
3726 if (mDrawingState.shadowRadius != s.shadowRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003727 ATRACE_FORMAT_INSTANT("%s: false [eShadowRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003728 return false;
3729 }
3730 }
3731
3732 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3733 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
Ady Abraham005398b2023-06-05 13:59:41 -07003734 ATRACE_FORMAT_INSTANT("%s: false [eFixedTransformHintChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003735 return false;
3736 }
3737 }
3738
3739 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3740 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
Ady Abraham005398b2023-06-05 13:59:41 -07003741 ATRACE_FORMAT_INSTANT("%s: false [eTrustedOverlayChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003742 return false;
3743 }
3744 }
3745
3746 if (s.what & layer_state_t::eStretchChanged) {
3747 StretchEffect temp = s.stretchEffect;
3748 temp.sanitize();
3749 if (mDrawingState.stretchEffect != temp) {
Ady Abraham005398b2023-06-05 13:59:41 -07003750 ATRACE_FORMAT_INSTANT("%s: false [eStretchChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003751 return false;
3752 }
3753 }
3754
3755 if (s.what & layer_state_t::eBufferCropChanged) {
3756 if (mDrawingState.bufferCrop != s.bufferCrop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003757 ATRACE_FORMAT_INSTANT("%s: false [eBufferCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003758 return false;
3759 }
3760 }
3761
3762 if (s.what & layer_state_t::eDestinationFrameChanged) {
3763 if (mDrawingState.destinationFrame != s.destinationFrame) {
Ady Abraham005398b2023-06-05 13:59:41 -07003764 ATRACE_FORMAT_INSTANT("%s: false [eDestinationFrameChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003765 return false;
3766 }
3767 }
3768
3769 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3770 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
Ady Abraham005398b2023-06-05 13:59:41 -07003771 ATRACE_FORMAT_INSTANT("%s: false [eDimmingEnabledChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003772 return false;
3773 }
3774 }
3775
John Reck68796592023-01-25 13:47:12 -05003776 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07003777 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
3778 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
Ady Abraham005398b2023-06-05 13:59:41 -07003779 ATRACE_FORMAT_INSTANT("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05003780 return false;
3781 }
3782 }
3783
Patrick Williamsbb25f802022-08-30 23:02:34 +00003784 return true;
3785}
3786
3787bool Layer::isHdrY410() const {
3788 // pixel format is HDR Y410 masquerading as RGBA_1010102
3789 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3790 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3791 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3792}
3793
Vishnu Naire14c6b32022-08-06 04:20:15 +00003794sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003795 // 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 +00003796 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003797}
3798
Vishnu Naire14c6b32022-08-06 04:20:15 +00003799const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003800 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003801}
3802
Vishnu Naire14c6b32022-08-06 04:20:15 +00003803LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003804 return mSnapshot.get();
3805}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003806
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003807std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3808 return std::move(mSnapshot);
3809}
3810
3811void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3812 mSnapshot = std::move(snapshot);
3813}
3814
Patrick Williamsbb25f802022-08-30 23:02:34 +00003815const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003816 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003817}
3818
Patrick Williams7584c6a2022-10-29 02:10:58 +00003819sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003820 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003821 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3822 return result;
3823}
3824
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003825sp<LayerFE> Layer::getCompositionEngineLayerFE(
3826 const frontend::LayerHierarchy::TraversalPath& path) {
3827 for (auto& [p, layerFE] : mLayerFEs) {
3828 if (p == path) {
3829 return layerFE;
3830 }
3831 }
3832 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3833 mLayerFEs.emplace_back(path, layerFE);
3834 return layerFE;
3835}
3836
Patrick Williamsbb25f802022-08-30 23:02:34 +00003837void Layer::useSurfaceDamage() {
3838 if (mFlinger->mForceFullDamage) {
3839 surfaceDamageRegion = Region::INVALID_REGION;
3840 } else {
3841 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3842 }
3843}
3844
3845void Layer::useEmptyDamage() {
3846 surfaceDamageRegion.clear();
3847}
3848
3849bool Layer::isOpaque(const Layer::State& s) const {
3850 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3851 // layer's opaque flag.
3852 if (!hasSomethingToDraw()) {
3853 return false;
3854 }
3855
3856 // if the layer has the opaque flag, then we're always opaque
3857 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3858 return true;
3859 }
3860
3861 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003862 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003863 return true;
3864 }
3865
3866 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3867 return fillsColor() && getAlpha() == 1.0_hf;
3868}
3869
3870bool Layer::canReceiveInput() const {
3871 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3872}
3873
3874bool Layer::isVisible() const {
3875 if (!hasSomethingToDraw()) {
3876 return false;
3877 }
3878
3879 if (isHiddenByPolicy()) {
3880 return false;
3881 }
3882
3883 return getAlpha() > 0.0f || hasBlur();
3884}
3885
3886void Layer::onPostComposition(const DisplayDevice* display,
3887 const std::shared_ptr<FenceTime>& glDoneFence,
3888 const std::shared_ptr<FenceTime>& presentFence,
3889 const CompositorTiming& compositorTiming) {
3890 // mFrameLatencyNeeded is true when a new frame was latched for the
3891 // composition.
3892 if (!mBufferInfo.mFrameLatencyNeeded) return;
3893
3894 for (const auto& handle : mDrawingState.callbackHandles) {
3895 handle->gpuCompositionDoneFence = glDoneFence;
3896 handle->compositorTiming = compositorTiming;
3897 }
3898
3899 // Update mFrameTracker.
3900 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3901 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3902
3903 const int32_t layerId = getSequence();
3904 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3905
3906 const auto outputLayer = findOutputLayerForDisplay(display);
3907 if (outputLayer && outputLayer->requiresClientComposition()) {
3908 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3909 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3910 clientCompositionTimestamp,
3911 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3912 // Update the SurfaceFrames in the drawing state
3913 if (mDrawingState.bufferSurfaceFrameTX) {
3914 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3915 }
3916 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3917 surfaceFrame->setGpuComposition();
3918 }
3919 }
3920
3921 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3922 if (frameReadyFence->isValid()) {
3923 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3924 } else {
3925 // There was no fence for this frame, so assume that it was ready
3926 // to be presented at the desired present time.
3927 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3928 }
3929
3930 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08003931 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003932 const std::optional<Fps> renderRate =
3933 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3934
3935 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3936 const auto gameMode = getGameMode();
3937
3938 if (presentFence->isValid()) {
3939 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3940 refreshRate, renderRate, vote, gameMode);
3941 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3942 presentFence,
3943 FrameTracer::FrameEvent::PRESENT_FENCE);
3944 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3945 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3946 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003947 // The HWC doesn't support present fences, so use the present timestamp instead.
3948 const nsecs_t presentTimestamp =
3949 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3950
3951 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3952 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3953 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3954
Patrick Williamsbb25f802022-08-30 23:02:34 +00003955 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3956 refreshRate, renderRate, vote, gameMode);
3957 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3958 mCurrentFrameNumber, actualPresentTime,
3959 FrameTracer::FrameEvent::PRESENT_FENCE);
3960 mFrameTracker.setActualPresentTime(actualPresentTime);
3961 }
3962 }
3963
3964 mFrameTracker.advanceFrame();
3965 mBufferInfo.mFrameLatencyNeeded = false;
3966}
3967
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003968bool Layer::willReleaseBufferOnLatch() const {
3969 return !mDrawingState.buffer && mBufferInfo.mBuffer;
3970}
3971
Patrick Williamsbb25f802022-08-30 23:02:34 +00003972bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003973 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
3974 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
3975}
3976
3977bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003978 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3979 getDrawingState().frameNumber);
3980
3981 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3982
3983 if (refreshRequired) {
3984 return refreshRequired;
3985 }
3986
3987 // If the head buffer's acquire fence hasn't signaled yet, return and
3988 // try again later
3989 if (!fenceHasSignaled()) {
3990 ATRACE_NAME("!fenceHasSignaled()");
3991 mFlinger->onLayerUpdate();
3992 return false;
3993 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00003994 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003995
3996 // Capture the old state of the layer for comparisons later
3997 BufferInfo oldBufferInfo = mBufferInfo;
3998 const bool oldOpacity = isOpaque(mDrawingState);
3999 mPreviousFrameNumber = mCurrentFrameNumber;
4000 mCurrentFrameNumber = mDrawingState.frameNumber;
4001 gatherBufferInfo();
4002
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004003 if (mBufferInfo.mBuffer) {
4004 // We latched a buffer that will be presented soon. Clear the previously presented layer
4005 // stack list.
4006 mPreviouslyPresentedLayerStacks.clear();
4007 }
4008
4009 if (mDrawingState.buffer == nullptr) {
4010 const bool bufferReleased = oldBufferInfo.mBuffer != nullptr;
4011 recomputeVisibleRegions = bufferReleased;
4012 return bufferReleased;
4013 }
4014
Patrick Williamsbb25f802022-08-30 23:02:34 +00004015 if (oldBufferInfo.mBuffer == nullptr) {
4016 // the first time we receive a buffer, we need to trigger a
4017 // geometry invalidation.
4018 recomputeVisibleRegions = true;
4019 }
4020
4021 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
4022 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
4023 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
4024 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
4025 recomputeVisibleRegions = true;
4026 }
4027
4028 if (oldBufferInfo.mBuffer != nullptr) {
4029 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
4030 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
4031 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
4032 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
4033 recomputeVisibleRegions = true;
4034 }
4035 }
4036
4037 if (oldOpacity != isOpaque(mDrawingState)) {
4038 recomputeVisibleRegions = true;
4039 }
4040
4041 return true;
4042}
4043
4044bool Layer::hasReadyFrame() const {
4045 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4046}
4047
4048bool Layer::isProtected() const {
4049 return (mBufferInfo.mBuffer != nullptr) &&
4050 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4051}
4052
Patrick Williamsbb25f802022-08-30 23:02:34 +00004053void Layer::latchAndReleaseBuffer() {
4054 if (hasReadyFrame()) {
4055 bool ignored = false;
4056 latchBuffer(ignored, systemTime());
4057 }
4058 releasePendingBuffer(systemTime());
4059}
4060
4061PixelFormat Layer::getPixelFormat() const {
4062 return mBufferInfo.mPixelFormat;
4063}
4064
4065bool Layer::getTransformToDisplayInverse() const {
4066 return mBufferInfo.mTransformToDisplayInverse;
4067}
4068
4069Rect Layer::getBufferCrop() const {
4070 // this is the crop rectangle that applies to the buffer
4071 // itself (as opposed to the window)
4072 if (!mBufferInfo.mCrop.isEmpty()) {
4073 // if the buffer crop is defined, we use that
4074 return mBufferInfo.mCrop;
4075 } else if (mBufferInfo.mBuffer != nullptr) {
4076 // otherwise we use the whole buffer
4077 return mBufferInfo.mBuffer->getBounds();
4078 } else {
4079 // if we don't have a buffer yet, we use an empty/invalid crop
4080 return Rect();
4081 }
4082}
4083
4084uint32_t Layer::getBufferTransform() const {
4085 return mBufferInfo.mTransform;
4086}
4087
4088ui::Dataspace Layer::getDataSpace() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004089 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4090}
4091
4092ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4093 ui::Dataspace updatedDataspace = dataspace;
4094 // translate legacy dataspaces to modern dataspaces
4095 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00004096 // Treat unknown dataspaces as V0_sRGB
4097 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00004098 case ui::Dataspace::SRGB:
4099 updatedDataspace = ui::Dataspace::V0_SRGB;
4100 break;
4101 case ui::Dataspace::SRGB_LINEAR:
4102 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4103 break;
4104 case ui::Dataspace::JFIF:
4105 updatedDataspace = ui::Dataspace::V0_JFIF;
4106 break;
4107 case ui::Dataspace::BT601_625:
4108 updatedDataspace = ui::Dataspace::V0_BT601_625;
4109 break;
4110 case ui::Dataspace::BT601_525:
4111 updatedDataspace = ui::Dataspace::V0_BT601_525;
4112 break;
4113 case ui::Dataspace::BT709:
4114 updatedDataspace = ui::Dataspace::V0_BT709;
4115 break;
4116 default:
4117 break;
4118 }
4119
4120 return updatedDataspace;
4121}
4122
4123sp<GraphicBuffer> Layer::getBuffer() const {
4124 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4125}
4126
Vishnu Nairb76d99a2023-03-19 18:22:31 -07004127void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4128 mTransformHintLegacy = getFixedTransformHint();
4129 if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4130 mTransformHintLegacy = displayTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004131 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004132 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004133}
4134
4135const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4136 return mBufferInfo.mBuffer;
4137}
4138
4139bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004140 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004141 return false;
4142 }
4143
4144 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004145 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004146 mDrawingState.modified = true;
4147 setTransactionFlags(eTransactionNeeded);
4148 return true;
4149}
4150
4151bool Layer::fillsColor() const {
4152 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4153 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4154}
4155
4156bool Layer::hasBlur() const {
4157 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4158}
4159
Vishnu Nairba354102022-08-01 00:14:18 +00004160void Layer::updateSnapshot(bool updateGeometry) {
4161 if (!getCompositionEngineLayerFE()) {
4162 return;
4163 }
4164
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004165 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004166 if (updateGeometry) {
4167 prepareBasicGeometryCompositionState();
4168 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004169 snapshot->roundedCorner = getRoundedCornerState();
4170 snapshot->stretchEffect = getStretchEffect();
4171 snapshot->transformedBounds = mScreenBounds;
4172 if (mEffectiveShadowRadius > 0.f) {
4173 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4174
4175 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4176 // it if transparent regions are present. This may not be necessary since shadows are
4177 // typically cast by layers without transparent regions.
4178 snapshot->shadowSettings.boundaries = mBounds;
4179
4180 const float casterAlpha = snapshot->alpha;
4181 const bool casterIsOpaque =
4182 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4183
4184 // If the casting layer is translucent, we need to fill in the shadow underneath the
4185 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4186 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4187 snapshot->shadowSettings.ambientColor *= casterAlpha;
4188 snapshot->shadowSettings.spotColor *= casterAlpha;
4189 }
4190 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004191 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004192 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004193 snapshot->layerOpaqueFlagSet =
4194 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004195 snapshot->isHdrY410 = isHdrY410();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004196 sp<Layer> p = mDrawingParent.promote();
4197 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004198 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004199 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004200 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004201 }
4202 snapshot->bufferSize = getBufferSize(mDrawingState);
4203 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004204 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004205 preparePerFrameCompositionState();
4206}
4207
Vishnu Naire14c6b32022-08-06 04:20:15 +00004208void Layer::updateChildrenSnapshots(bool updateGeometry) {
4209 for (const sp<Layer>& child : mDrawingChildren) {
4210 child->updateSnapshot(updateGeometry);
4211 child->updateChildrenSnapshots(updateGeometry);
4212 }
4213}
4214
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004215void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4216 mSnapshot->layerMetadata = parentMetadata;
4217 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4218 for (const sp<Layer>& child : mDrawingChildren) {
4219 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4220 }
4221}
4222
4223void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4224 std::unordered_set<Layer*>& visited) {
4225 if (visited.find(this) != visited.end()) {
4226 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4227 return;
4228 }
4229 visited.insert(this);
4230
4231 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4232
4233 if (mDrawingState.zOrderRelatives.empty()) {
4234 return;
4235 }
4236 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4237 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4238 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4239 sp<Layer> relative = weakRelative.promote();
4240 if (!relative) {
4241 continue;
4242 }
4243 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4244 }
4245}
4246
Chavi Weingarten328a8312023-01-26 21:17:52 +00004247bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004248 TrustedPresentationListener const& listener) {
4249 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4250 mTrustedPresentationListener = listener;
4251 mTrustedPresentationThresholds = thresholds;
4252 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4253 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4254 mFlinger->mNumTrustedPresentationListeners++;
4255 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4256 mFlinger->mNumTrustedPresentationListeners--;
4257 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004258
4259 // Reset trusted presentation states to ensure we start the time again.
4260 mEnteredTrustedPresentationStateTime = -1;
4261 mLastReportedTrustedPresentationState = false;
4262 mLastComputedTrustedPresentationState = false;
4263
4264 // If there's a new trusted presentation listener, the code needs to go through the composite
4265 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4266 // we're already in the requested state.
4267 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004268}
4269
Vishnu Naira156f482023-02-22 00:23:38 +00004270void Layer::updateLastLatchTime(nsecs_t latchTime) {
4271 mLastLatchTime = latchTime;
4272}
4273
Mathias Agopian13127d82013-03-05 17:47:11 -08004274// ---------------------------------------------------------------------------
4275
Marin Shalamanov46084422020-10-13 12:33:42 +02004276std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004277 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4278 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004279}
4280
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004281} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004282
4283#if defined(__gl_h_)
4284#error "don't include gl/gl.h in this file"
4285#endif
4286
4287#if defined(__gl2_h_)
4288#error "don't include gl2/gl2.h in this file"
4289#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004290
4291// TODO(b/129481165): remove the #pragma below and fix conversion issues
4292#pragma clang diagnostic pop // ignored "-Wconversion"