blob: ba6f9679084cf3ff4eaf65210393bc94117deecf [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) {
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000405 const auto outputLayer = findOutputLayerForDisplay(display, snapshot->path);
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);
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000744 return getCompositionType(outputLayer);
745}
746
747aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
748 const compositionengine::OutputLayer* outputLayer) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -0800749 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500750 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800751 }
752 if (outputLayer->getState().hwc) {
753 return (*outputLayer->getState().hwc).hwcCompositionType;
754 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500755 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800756 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800757}
758
Mathias Agopian13127d82013-03-05 17:47:11 -0800759// ----------------------------------------------------------------------------
760// local state
761// ----------------------------------------------------------------------------
762
David Sodman41fdfc92017-11-06 16:09:56 -0800763bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800764 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700765 if (s.flags & layer_state_t::eLayerSecure) {
766 return true;
767 }
768
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000769 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700770 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700771}
772
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100773void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
774 std::vector<JankData>& jankData) {
775 if (mPendingJankClassifications.empty() ||
776 !mPendingJankClassifications.front()->getJankType()) {
777 return;
778 }
779
780 bool includeJankData = false;
781 for (const auto& handle : handles) {
782 for (const auto& cb : handle->callbackIds) {
783 if (cb.includeJankData) {
784 includeJankData = true;
785 break;
786 }
787 }
788
789 if (includeJankData) {
790 jankData.reserve(mPendingJankClassifications.size());
791 break;
792 }
793 }
794
795 while (!mPendingJankClassifications.empty() &&
796 mPendingJankClassifications.front()->getJankType()) {
797 if (includeJankData) {
798 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
799 mPendingJankClassifications.front();
800 jankData.emplace_back(
801 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
802 }
803 mPendingJankClassifications.pop_front();
804 }
805}
806
Mathias Agopian13127d82013-03-05 17:47:11 -0800807// ----------------------------------------------------------------------------
808// transaction
809// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800810
Vishnu Naira156f482023-02-22 00:23:38 +0000811uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700812 ATRACE_CALL();
813
Robert Carr0758e5d2021-03-11 22:15:04 -0800814 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700815 mDrawingStateModified = mDrawingState.modified;
816 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700817
Alec Mourib416efd2018-09-06 21:01:59 +0000818 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700819
Robert Carr6a160312021-05-17 12:08:20 -0700820 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800821 // invalidate and recompute the visible regions if needed
822 flags |= Layer::eVisibleRegion;
823 }
824
Robert Carr6a160312021-05-17 12:08:20 -0700825 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800826 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000827 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800828 flags |= eVisibleRegion;
829 this->contentDirty = true;
830
831 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700832 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800833 }
834
Arthur Hung9ed43392022-05-27 06:31:57 +0000835 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
836 mFlinger->mUpdateInputInfo = true;
837 }
838
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700839 commitTransaction();
Robert Carra1257842020-01-31 13:48:28 -0800840
Mathias Agopian13127d82013-03-05 17:47:11 -0800841 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800842}
843
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700844void Layer::commitTransaction() {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000845 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
846 // bufferSurfaceFrameTX will be presented in latchBuffer.
847 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
848 if (surfaceFrame->getPresentState() != PresentState::Presented) {
849 // With applyPendingStates, we could end up having presented surfaceframes from previous
850 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800851 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000852 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
853 }
854 }
Robert Carr6a160312021-05-17 12:08:20 -0700855 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700856}
857
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700858uint32_t Layer::clearTransactionFlags(uint32_t mask) {
859 const auto flags = mTransactionFlags & mask;
860 mTransactionFlags &= ~mask;
861 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800862}
863
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700864void Layer::setTransactionFlags(uint32_t mask) {
865 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800866}
867
Robert Carr1f0a16a2016-10-24 16:27:39 -0700868bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
869 ssize_t idx = mCurrentChildren.indexOf(childLayer);
870 if (idx < 0) {
871 return false;
872 }
873 if (childLayer->setLayer(z)) {
874 mCurrentChildren.removeAt(idx);
875 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800876 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700877 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800878 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700879}
880
Robert Carr503c7042017-09-27 15:06:08 -0700881bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
882 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
883 ssize_t idx = mCurrentChildren.indexOf(childLayer);
884 if (idx < 0) {
885 return false;
886 }
887 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
888 mCurrentChildren.removeAt(idx);
889 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800890 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700891 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800892 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700893}
894
Robert Carrae060832016-11-28 10:51:00 -0800895bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700896 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
897 mDrawingState.sequence++;
898 mDrawingState.z = z;
899 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700900
Robert Carra70e91c2021-06-11 13:59:52 -0700901 mFlinger->mSomeChildrenChanged = true;
902
Robert Carrdb66e622017-04-10 16:55:57 -0700903 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700904 if (mDrawingState.zOrderRelativeOf != nullptr) {
905 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700906 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700907 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700908 }
chaviw606e5cf2019-03-01 10:12:10 -0800909 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700910 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800911 setTransactionFlags(eTransactionNeeded);
912 return true;
913}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700914
Robert Carrdb66e622017-04-10 16:55:57 -0700915void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700916 mDrawingState.zOrderRelatives.remove(relative);
917 mDrawingState.sequence++;
918 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700919 setTransactionFlags(eTransactionNeeded);
920}
921
922void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700923 mDrawingState.zOrderRelatives.add(relative);
924 mDrawingState.modified = true;
925 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700926 setTransactionFlags(eTransactionNeeded);
927}
928
chaviw606e5cf2019-03-01 10:12:10 -0800929void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700930 mDrawingState.zOrderRelativeOf = relativeOf;
931 mDrawingState.sequence++;
932 mDrawingState.modified = true;
933 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700934
chaviw606e5cf2019-03-01 10:12:10 -0800935 setTransactionFlags(eTransactionNeeded);
936}
937
Robert Carr503d2bd2017-12-04 15:49:47 -0800938bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000939 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700940 if (relative == nullptr) {
941 return false;
942 }
943
Robert Carr6a160312021-05-17 12:08:20 -0700944 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
945 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800946 return false;
947 }
948
Robert Carr88b85e12022-03-21 15:47:35 -0700949 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
950 (relative->mDrawingState.zOrderRelativeOf == this)) {
951 ALOGE("Detected relative layer loop between %s and %s",
952 mName.c_str(), relative->mName.c_str());
953 ALOGE("Ignoring new call to set relative layer");
954 return false;
955 }
956
Robert Carra70e91c2021-06-11 13:59:52 -0700957 mFlinger->mSomeChildrenChanged = true;
958
Robert Carr6a160312021-05-17 12:08:20 -0700959 mDrawingState.sequence++;
960 mDrawingState.modified = true;
961 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700962
Robert Carr6a160312021-05-17 12:08:20 -0700963 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700964 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700965 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700966 }
chaviw606e5cf2019-03-01 10:12:10 -0800967 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700968 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700969
970 setTransactionFlags(eTransactionNeeded);
971
972 return true;
973}
974
Winson Chunga30f7c92021-06-29 15:42:56 -0700975bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
976 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
977 mDrawingState.isTrustedOverlay = isTrustedOverlay;
978 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000979 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700980 setTransactionFlags(eTransactionNeeded);
981 return true;
982}
983
984bool Layer::isTrustedOverlay() const {
985 if (getDrawingState().isTrustedOverlay) {
986 return true;
987 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000988 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700989 return (p != nullptr) && p->isTrustedOverlay();
990}
991
Dan Stoza9e56aa02015-11-02 13:00:03 -0800992bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700993 if (mDrawingState.color.a == alpha) return false;
994 mDrawingState.sequence++;
995 mDrawingState.color.a = alpha;
996 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800997 setTransactionFlags(eTransactionNeeded);
998 return true;
999}
chaviw13fdc492017-06-27 12:40:18 -07001000
Valerie Haudd0b7572019-01-29 14:59:27 -08001001bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -07001002 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -07001003 return false;
Valerie Hauaa194562019-02-05 16:21:38 -08001004 }
Robert Carr6a160312021-05-17 12:08:20 -07001005 mDrawingState.sequence++;
1006 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -08001007 setTransactionFlags(eTransactionNeeded);
1008
Robert Carr6a160312021-05-17 12:08:20 -07001009 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001010 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001011 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001012 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001013 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08001014 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001015 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001016
Valerie Haudd0b7572019-01-29 14:59:27 -08001017 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001018 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001019 mFlinger->mLayersAdded = true;
1020 // set up SF to handle added color layer
1021 if (isRemovedFromCurrentState()) {
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->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001024 }
1025 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001026 } else if (mDrawingState.bgColorLayer && alpha == 0) {
Josh Gao194ff392022-09-08 16:19:29 -07001027 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001028 mDrawingState.bgColorLayer->reparent(nullptr);
1029 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001030 return true;
1031 }
1032
Robert Carr6a160312021-05-17 12:08:20 -07001033 mDrawingState.bgColorLayer->setColor(color);
1034 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1035 mDrawingState.bgColorLayer->setAlpha(alpha);
1036 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001037
chaviw13fdc492017-06-27 12:40:18 -07001038 return true;
1039}
1040
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001041bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001042 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001043
Robert Carr6a160312021-05-17 12:08:20 -07001044 mDrawingState.sequence++;
1045 mDrawingState.cornerRadius = cornerRadius;
1046 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001047 setTransactionFlags(eTransactionNeeded);
1048 return true;
1049}
1050
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001051bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001052 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001053 // If we start or stop drawing blur then the layer's visibility state may change so increment
1054 // the magic sequence number.
1055 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1056 mDrawingState.sequence++;
1057 }
Robert Carr6a160312021-05-17 12:08:20 -07001058 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1059 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001060 setTransactionFlags(eTransactionNeeded);
1061 return true;
1062}
Marissa Wall61c58622018-07-18 10:12:20 -07001063
Mathias Agopian13127d82013-03-05 17:47:11 -08001064bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001065 mDrawingState.sequence++;
1066 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001067 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001068 setTransactionFlags(eTransactionNeeded);
1069 return true;
1070}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001071
Lucas Dupinc3800b82020-10-02 16:24:48 -07001072bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001073 // If we start or stop drawing blur then the layer's visibility state may change so increment
1074 // the magic sequence number.
1075 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1076 mDrawingState.sequence++;
1077 }
Robert Carr6a160312021-05-17 12:08:20 -07001078 mDrawingState.blurRegions = blurRegions;
1079 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001080 setTransactionFlags(eTransactionNeeded);
1081 return true;
1082}
1083
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001084bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001085 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1086 if (mDrawingState.flags == newFlags) return false;
1087 mDrawingState.sequence++;
1088 mDrawingState.flags = newFlags;
1089 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001090 setTransactionFlags(eTransactionNeeded);
1091 return true;
1092}
Robert Carr99e27f02016-06-16 15:18:02 -07001093
chaviw25714502021-02-11 10:01:08 -08001094bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001095 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001096 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001097 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001098
Robert Carr6a160312021-05-17 12:08:20 -07001099 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001100 setTransactionFlags(eTransactionNeeded);
1101 return true;
1102}
Robert Carr8d5227b2017-03-16 15:41:03 -07001103
Evan Roskyef876c92019-01-25 17:46:06 -08001104bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001105 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1106 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001107 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001108 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001109}
1110
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001111bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001112 if (mDrawingState.layerStack == layerStack) return false;
1113 mDrawingState.sequence++;
1114 mDrawingState.layerStack = layerStack;
1115 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001116 setTransactionFlags(eTransactionNeeded);
1117 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001118}
1119
Peiyong Linc502cb72019-03-01 15:00:23 -08001120bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001121 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001122 return false;
1123 }
Robert Carr6a160312021-05-17 12:08:20 -07001124 mDrawingState.sequence++;
1125 mDrawingState.colorSpaceAgnostic = agnostic;
1126 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001127 setTransactionFlags(eTransactionNeeded);
1128 return true;
1129}
1130
Sally Qi81d95e62022-03-21 19:41:33 -07001131bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1132 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1133
1134 mDrawingState.sequence++;
1135 mDrawingState.dimmingEnabled = dimmingEnabled;
1136 mDrawingState.modified = true;
1137 setTransactionFlags(eTransactionNeeded);
1138 return true;
1139}
1140
Ana Krulecc84d09b2019-11-02 23:10:29 +01001141bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001142 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1143 mDrawingState.frameRateSelectionPriority = priority;
1144 mDrawingState.sequence++;
1145 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001146 setTransactionFlags(eTransactionNeeded);
1147 return true;
1148}
1149
1150int32_t Layer::getFrameRateSelectionPriority() const {
1151 // Check if layer has priority set.
1152 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1153 return mDrawingState.frameRateSelectionPriority;
1154 }
1155 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001156 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001157 if (parent != nullptr) {
1158 return parent->getFrameRateSelectionPriority();
1159 }
1160
1161 return Layer::PRIORITY_UNSET;
1162}
1163
Andy Labrada096227e2022-06-15 16:58:11 +00001164bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1165 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1166 mDrawingState.defaultFrameRateCompatibility = compatibility;
1167 mDrawingState.modified = true;
1168 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1169 setTransactionFlags(eTransactionNeeded);
1170 return true;
1171}
1172
1173scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1174 return mDrawingState.defaultFrameRateCompatibility;
1175}
1176
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001177bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1178 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1179};
1180
Vishnu Nair73908d12022-10-24 21:46:42 -07001181ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1182 bool useDrawing = state == LayerVector::StateSet::Drawing;
1183 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1184 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001185 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001186 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001187 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001188}
1189
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001190bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001191 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001192 return false;
1193 }
1194
Robert Carr6a160312021-05-17 12:08:20 -07001195 mDrawingState.sequence++;
1196 mDrawingState.shadowRadius = shadowRadius;
1197 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001198 setTransactionFlags(eTransactionNeeded);
1199 return true;
1200}
1201
Vishnu Nair6213bd92020-05-08 17:42:25 -07001202bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001203 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001204 return false;
1205 }
1206
Robert Carr6a160312021-05-17 12:08:20 -07001207 mDrawingState.sequence++;
1208 mDrawingState.fixedTransformHint = fixedTransformHint;
1209 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001210 setTransactionFlags(eTransactionNeeded);
1211 return true;
1212}
1213
John Reckcdb4ed72021-02-04 13:39:33 -05001214bool Layer::setStretchEffect(const StretchEffect& effect) {
1215 StretchEffect temp = effect;
1216 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001217 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001218 return false;
1219 }
Robert Carr6a160312021-05-17 12:08:20 -07001220 mDrawingState.sequence++;
1221 mDrawingState.stretchEffect = temp;
1222 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001223 setTransactionFlags(eTransactionNeeded);
1224 return true;
1225}
1226
John Reckc00c6692021-02-16 11:37:33 -05001227StretchEffect Layer::getStretchEffect() const {
1228 if (mDrawingState.stretchEffect.hasEffect()) {
1229 return mDrawingState.stretchEffect;
1230 }
1231
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001232 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001233 if (parent != nullptr) {
1234 auto effect = parent->getStretchEffect();
1235 if (effect.hasEffect()) {
1236 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1237 return effect;
1238 }
1239 }
1240 return StretchEffect{};
1241}
1242
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001243bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1244 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001245 return false;
1246 }
1247 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001248 mBorderWidth = width;
1249 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001250 return true;
1251}
1252
1253bool Layer::isBorderEnabled() {
1254 return mBorderEnabled;
1255}
1256
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001257float Layer::getBorderWidth() {
1258 return mBorderWidth;
1259}
1260
1261const half4& Layer::getBorderColor() {
1262 return mBorderColor;
1263}
1264
Ady Abrahama850c182021-08-04 13:04:37 -07001265bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1266 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1267 const auto frameRate = [&] {
1268 if (mDrawingState.frameRate.rate.isValid() ||
1269 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1270 return mDrawingState.frameRate;
1271 }
1272
1273 return parentFrameRate;
1274 }();
1275
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001276 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001277
1278 // The frame rate is propagated to the children
1279 bool childrenHaveFrameRate = false;
1280 for (const sp<Layer>& child : mCurrentChildren) {
1281 childrenHaveFrameRate |=
1282 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1283 }
1284
1285 // If we don't have a valid frame rate, but the children do, we set this
1286 // layer as NoVote to allow the children to control the refresh rate
1287 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1288 childrenHaveFrameRate) {
1289 *transactionNeeded |=
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001290 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001291 }
1292
1293 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1294 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001295 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001296 const auto layerVotedWithDefaultCompatibility =
1297 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1298 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1299 const auto layerVotedWithExactCompatibility =
1300 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1301 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1302 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1303}
1304
Ady Abraham60e42ea2020-03-09 19:17:31 -07001305void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001306 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001307 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001308 while (auto parent = layer->getParent()) {
1309 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001310 }
Ady Abrahama850c182021-08-04 13:04:37 -07001311 return layer;
1312 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001313
Ady Abraham60e42ea2020-03-09 19:17:31 -07001314 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001315 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001316
Ady Abrahama850c182021-08-04 13:04:37 -07001317 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001318 if (transactionNeeded) {
1319 mFlinger->setTransactionFlags(eTraversalNeeded);
1320 }
1321}
1322
Ady Abraham71c437d2020-01-31 15:56:57 -08001323bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001324 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001325 return false;
1326 }
1327
Robert Carr6a160312021-05-17 12:08:20 -07001328 mDrawingState.sequence++;
1329 mDrawingState.frameRate = frameRate;
1330 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001331
1332 updateTreeHasFrameRateVote();
1333
Steven Thomas3172e202020-01-06 19:25:30 -08001334 setTransactionFlags(eTransactionNeeded);
1335 return true;
1336}
1337
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001338void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1339 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001340 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001341
1342 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1343 // there are two transactions with the same token, the first one without a buffer and the
1344 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1345 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001346 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1347 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001348 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001349 mDrawingState.bufferSurfaceFrameTX = it->second;
1350 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1351 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1352 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001353 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001354 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001355 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1356 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001357
1358 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001359}
1360
1361void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1362 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001363 mDrawingState.frameTimelineInfo = info;
1364 mDrawingState.postTime = postTime;
1365 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001366 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001367
Robert Carr6a160312021-05-17 12:08:20 -07001368 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001369 bufferSurfaceFrameTX != nullptr) {
1370 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1371 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1372 // being used for BufferSurfaceFrame, don't create a new one.
1373 return;
1374 }
1375 }
1376 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1377 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1378 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001379 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1380 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001381 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001382 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001383 } else {
1384 if (it->second->getPresentState() == PresentState::Presented) {
1385 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1386 // have been from previous vsync.
1387 it->second = createSurfaceFrameForTransaction(info, postTime);
1388 }
1389 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001390
1391 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001392}
1393
1394void Layer::addSurfaceFrameDroppedForBuffer(
Ady Abraham5a3e3562023-06-07 10:32:08 -07001395 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t dropTime) {
1396 surfaceFrame->setDropTime(dropTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001397 surfaceFrame->setPresentState(PresentState::Dropped);
1398 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1399}
1400
1401void Layer::addSurfaceFramePresentedForBuffer(
1402 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1403 nsecs_t currentLatchTime) {
1404 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1405 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1406 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001407 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001408}
1409
1410std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1411 const FrameTimelineInfo& info, nsecs_t postTime) {
1412 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001413 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1414 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001415 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001416 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001417 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001418 // For Transactions, the post time is considered to be both queue and acquire fence time.
1419 surfaceFrame->setActualQueueTime(postTime);
1420 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001421 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1422 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001423 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001424 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001425 onSurfaceFrameCreated(surfaceFrame);
1426 return surfaceFrame;
1427}
1428
1429std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1430 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1431 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001432 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001433 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001434 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001435 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001436 // For buffers, acquire fence time will set during latch.
1437 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001438 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1439 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001440 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001441 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001442 onSurfaceFrameCreated(surfaceFrame);
1443 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001444}
1445
Ady Abraham5a3e3562023-06-07 10:32:08 -07001446void Layer::setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
1447 std::string debugName) {
1448 if (info.skippedFrameVsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
1449 return;
1450 }
1451
1452 FrameTimelineInfo skippedFrameTimelineInfo = info;
1453 skippedFrameTimelineInfo.vsyncId = info.skippedFrameVsyncId;
1454
1455 auto surfaceFrame =
1456 mFlinger->mFrameTimeline->createSurfaceFrameForToken(skippedFrameTimelineInfo,
1457 mOwnerPid, mOwnerUid,
1458 getSequence(), mName, debugName,
1459 /*isBuffer*/ false, getGameMode());
1460 surfaceFrame->setActualStartTime(skippedFrameTimelineInfo.skippedFrameStartTimeNanos);
1461 // For Transactions, the post time is considered to be both queue and acquire fence time.
1462 surfaceFrame->setActualQueueTime(postTime);
1463 surfaceFrame->setAcquireFenceTime(postTime);
1464 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1465 if (fps) {
1466 surfaceFrame->setRenderRate(*fps);
1467 }
1468 onSurfaceFrameCreated(surfaceFrame);
1469 addSurfaceFrameDroppedForBuffer(surfaceFrame, postTime);
1470}
1471
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001472bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001473 if (mDrawingState.frameRateForLayerTree == frameRate) {
1474 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001475 }
1476
Ady Abrahama850c182021-08-04 13:04:37 -07001477 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001478
Ady Abrahama850c182021-08-04 13:04:37 -07001479 // TODO(b/195668952): we probably don't need to dirty visible regions here
1480 // or even store frameRateForLayerTree in mDrawingState
1481 mDrawingState.sequence++;
1482 mDrawingState.modified = true;
1483 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001484
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001485 mFlinger->mScheduler
1486 ->recordLayerHistory(sequence, getLayerProps(), systemTime(),
1487 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1488 return true;
1489}
Ady Abrahama850c182021-08-04 13:04:37 -07001490
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001491bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps) {
1492 if (mDrawingState.frameRateForLayerTree == frameRate) {
1493 return false;
1494 }
1495
1496 mDrawingState.frameRateForLayerTree = frameRate;
1497 mFlinger->mScheduler
1498 ->recordLayerHistory(sequence, layerProps, systemTime(),
1499 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001500 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001501}
1502
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001503Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1504 return getDrawingState().frameRateForLayerTree;
1505}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001506
Robert Carr1f0a16a2016-10-24 16:27:39 -07001507bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001508 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001509 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001510 if (parent != nullptr && parent->isHiddenByPolicy()) {
1511 return true;
1512 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001513 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1514 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1515 if (zOrderRelativeOf != nullptr) {
1516 if (zOrderRelativeOf->isHiddenByPolicy()) {
1517 return true;
1518 }
1519 }
1520 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001521 if (CC_UNLIKELY(!isTransformValid())) {
1522 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1523 return true;
1524 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001525 return s.flags & layer_state_t::eLayerHidden;
1526}
1527
David Sodman41fdfc92017-11-06 16:09:56 -08001528uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001529 // TODO: should we do something special if mSecure is set?
1530 if (mProtectedByApp) {
1531 // need a hardware-protected path to external video sink
1532 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001533 }
Riley Andrews03414a12014-07-01 14:22:59 -07001534 if (mPotentialCursor) {
1535 usage |= GraphicBuffer::USAGE_CURSOR;
1536 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001537 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001538 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001539}
1540
Vishnu Nair71fcf912022-10-18 09:14:20 -07001541void Layer::skipReportingTransformHint() {
1542 mSkipReportingTransformHint = true;
1543}
1544
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001545void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1546 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1547 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001548 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001549
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001550 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001551}
1552
Mathias Agopian13127d82013-03-05 17:47:11 -08001553// ----------------------------------------------------------------------------
1554// debugging
1555// ----------------------------------------------------------------------------
1556
Marissa Wall61c58622018-07-18 10:12:20 -07001557// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001558gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001559 using namespace std::string_literals;
1560
Huihong Luo05539a12022-02-23 10:29:40 -08001561 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001562 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001563 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001564 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001565 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001566 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001567
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001568 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001569 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001570 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001571 info.mX = ds.transform.tx();
1572 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001573 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001574 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001575 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001576 info.mFlags = ds.flags;
1577 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001578 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001579 info.mMatrix[0][0] = ds.transform[0][0];
1580 info.mMatrix[0][1] = ds.transform[0][1];
1581 info.mMatrix[1][0] = ds.transform[1][0];
1582 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001583 {
chaviwd62d3062019-09-04 14:48:02 -07001584 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001585 if (buffer != 0) {
1586 info.mActiveBufferWidth = buffer->getWidth();
1587 info.mActiveBufferHeight = buffer->getHeight();
1588 info.mActiveBufferStride = buffer->getStride();
1589 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001590 } else {
1591 info.mActiveBufferWidth = 0;
1592 info.mActiveBufferHeight = 0;
1593 info.mActiveBufferStride = 0;
1594 info.mActiveBufferFormat = 0;
1595 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001596 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001597 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001598 info.mIsOpaque = isOpaque(ds);
1599 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001600 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001601 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001602}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001603
Yiwei Zhang5434a782018-12-05 18:06:32 -08001604void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001605 result.append(kDumpTableRowLength, '-');
1606 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001607 result.append(" Layer name\n");
1608 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001609 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001610 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001611 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001612 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001613 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001614 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1615 result.append(kDumpTableRowLength, '-');
1616 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001617}
1618
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001619void Layer::miniDumpLegacy(std::string& result, const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001620 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001621 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001622 return;
1623 }
1624
Yiwei Zhang5434a782018-12-05 18:06:32 -08001625 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001626 if (mName.length() > 77) {
1627 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001628 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001629 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001630 shortened.append(mName, mName.length() - 36);
1631 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001632 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001633 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001634 }
1635
Yiwei Zhang5434a782018-12-05 18:06:32 -08001636 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001637
Alec Mourib416efd2018-09-06 21:01:59 +00001638 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001639 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001640
Chia-I Wu1e043612018-03-01 09:45:09 -08001641 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001642 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001643 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001644 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001645 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001646 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001647 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001648 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1649 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001650 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001651 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001652 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001653 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001654 const auto frameRate = getFrameRateForLayerTree();
1655 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1656 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001657 ftl::enum_string(frameRate.type).c_str(),
1658 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001659 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001660 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001661 }
Dan Stozae22aec72016-08-01 13:20:59 -07001662
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001663 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1664 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1665
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001666 result.append(kDumpTableRowLength, '-');
1667 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001668}
Dan Stozae22aec72016-08-01 13:20:59 -07001669
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001670void Layer::miniDump(std::string& result, const frontend::LayerSnapshot& snapshot,
1671 const DisplayDevice& display) const {
1672 const auto outputLayer = findOutputLayerForDisplay(&display, snapshot.path);
1673 if (!outputLayer) {
1674 return;
1675 }
1676
1677 StringAppendF(&result, " %s\n", snapshot.debugName.c_str());
1678 StringAppendF(&result, " %10zu | ", snapshot.globalZ);
1679 StringAppendF(&result, " %10d | ",
1680 snapshot.layerMetadata.getInt32(gui::METADATA_WINDOW_TYPE, 0));
1681 StringAppendF(&result, "%10s | ", toString(getCompositionType(outputLayer)).c_str());
1682 const auto& outputLayerState = outputLayer->getState();
1683 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1684 const Rect& frame = outputLayerState.displayFrame;
1685 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1686 const FloatRect& crop = outputLayerState.sourceCrop;
1687 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
1688 crop.bottom);
1689 const auto frameRate = snapshot.frameRate;
1690 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1691 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
1692 ftl::enum_string(frameRate.type).c_str(),
1693 ftl::enum_string(frameRate.seamlessness).c_str());
1694 } else {
1695 result.append(41, ' ');
1696 }
1697
1698 const auto focused = isLayerFocusedBasedOnPriority(snapshot.frameRateSelectionPriority);
1699 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1700
1701 result.append(kDumpTableRowLength, '-');
1702 result.append("\n");
1703}
1704
Yiwei Zhang5434a782018-12-05 18:06:32 -08001705void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001706 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001707}
1708
Svetoslavd85084b2014-03-20 10:28:31 -07001709void Layer::clearFrameStats() {
1710 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001711}
1712
Jamie Gennis6547ff42013-07-16 20:12:42 -07001713void Layer::logFrameStats() {
1714 mFrameTracker.logAndResetStats(mName);
1715}
1716
Svetoslavd85084b2014-03-20 10:28:31 -07001717void Layer::getFrameStats(FrameStats* outStats) const {
1718 mFrameTracker.getStats(outStats);
1719}
1720
Vishnu Nair76554eb2022-12-09 03:38:36 +00001721void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1722 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
Vishnu Nair3be61902023-04-26 19:47:29 -07001723 StringAppendF(&result, "Layer %s%s pid:%d uid:%d%s\n", getName().c_str(), hasBuffer.c_str(),
1724 mOwnerPid, mOwnerUid, isHandleAlive() ? " handleAlive" : "");
Vishnu Nair0f085c62019-08-30 08:49:12 -07001725}
1726
Brian Anderson5ea5e592016-12-01 16:54:33 -08001727void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001728 const int32_t layerId = getSequence();
1729 mFlinger->mTimeStats->onDestroy(layerId);
1730 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001731}
1732
Vishnu Nair787aa782023-03-17 13:46:46 -07001733size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001734 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001735 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001736 count += 1 + child->getChildrenCount();
1737 }
1738 return count;
1739}
1740
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001741void Layer::setGameModeForTree(GameMode gameMode) {
1742 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001743 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1744 gameMode =
1745 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001746 }
1747 setGameMode(gameMode);
1748 for (const sp<Layer>& child : mCurrentChildren) {
1749 child->setGameModeForTree(gameMode);
1750 }
1751}
1752
Robert Carr1f0a16a2016-10-24 16:27:39 -07001753void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001754 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001755 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001756
Robert Carr1f0a16a2016-10-24 16:27:39 -07001757 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001758 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001759 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001760 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001761}
1762
1763ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001764 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001765 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001766
Robert Carr1323c952019-01-28 18:13:27 -08001767 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001768 const auto removeResult = mCurrentChildren.remove(layer);
1769
1770 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001771 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001772 layer->updateTreeHasFrameRateVote();
1773
1774 return removeResult;
1775}
1776
Robert Carr15eae092018-03-23 13:43:53 -07001777void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001778 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001779 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001780 const float parentShadowRadius =
1781 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001782 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001783 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001784 }
1785}
1786
chaviwf1961f72017-09-18 16:41:07 -07001787bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001788 sp<Layer> newParent;
1789 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001790 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001791 if (newParent == nullptr) {
1792 ALOGE("Unable to promote Layer handle");
1793 return false;
1794 }
1795 if (newParent == this) {
1796 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1797 return false;
1798 }
1799 }
1800
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001801 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001802 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001803 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001804 }
1805
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001806 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001807 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001808 if (!newParent->isRemovedFromCurrentState()) {
1809 addToCurrentState();
1810 } else {
1811 onRemovedFromCurrentState();
1812 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001813 } else {
1814 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001815 }
1816
chaviw06178942017-07-27 10:25:59 -07001817 return true;
1818}
1819
Peiyong Lind3788632018-09-18 16:01:31 -07001820bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001821 static const mat4 identityMatrix = mat4();
1822
Robert Carr6a160312021-05-17 12:08:20 -07001823 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001824 return false;
1825 }
Robert Carr6a160312021-05-17 12:08:20 -07001826 ++mDrawingState.sequence;
1827 mDrawingState.colorTransform = matrix;
1828 mDrawingState.hasColorTransform = matrix != identityMatrix;
1829 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001830 setTransactionFlags(eTransactionNeeded);
1831 return true;
1832}
1833
chaviwf66724d2018-11-28 16:35:21 -08001834mat4 Layer::getColorTransform() const {
1835 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001836 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001837 colorTransform = parent->getColorTransform() * colorTransform;
1838 }
1839 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001840}
1841
1842bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001843 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001844 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001845 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1846 }
1847 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001848}
1849
Chia-I Wu11481472018-05-04 10:43:19 -07001850bool Layer::isLegacyDataSpace() const {
1851 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001852 return !(getDataSpace() &
1853 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1854 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001855}
1856
Robert Carr1f0a16a2016-10-24 16:27:39 -07001857void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001858 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001859}
1860
Robert Carr6a160312021-05-17 12:08:20 -07001861int32_t Layer::getZ(LayerVector::StateSet) const {
1862 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001863}
1864
Robert Carr1c5481e2019-07-01 14:42:27 -07001865bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001866 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001867 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001868 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001869}
1870
David Sodman41fdfc92017-11-06 16:09:56 -08001871__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001872 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001873 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1874 "makeTraversalList received invalid stateSet");
1875 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1876 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001877 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001878
Robert Carr29abff82017-12-04 13:51:20 -08001879 if (state.zOrderRelatives.size() == 0) {
1880 *outSkipRelativeZUsers = true;
1881 return children;
1882 }
1883
chaviwfd462612018-05-31 16:11:27 -07001884 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001885 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001886 sp<Layer> strongRelative = weakRelative.promote();
1887 if (strongRelative != nullptr) {
1888 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001889 }
1890 }
1891
Dan Stoza412903f2017-04-27 13:42:17 -07001892 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001893 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001894 continue;
1895 }
Robert Carrdb66e622017-04-10 16:55:57 -07001896 traverse.add(child);
1897 }
1898
1899 return traverse;
1900}
1901
Robert Carr1f0a16a2016-10-24 16:27:39 -07001902/**
Robert Carrdb66e622017-04-10 16:55:57 -07001903 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001904 */
Dan Stoza412903f2017-04-27 13:42:17 -07001905void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001906 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1907 // produce a new list for traversing, including our relatives, and not including our children
1908 // who are relatives of another surface. In the case that there are no relative Z,
1909 // makeTraversalList returns our children directly to avoid significant overhead.
1910 // However in this case we need to take the responsibility for filtering children which
1911 // are relatives of another surface here.
1912 bool skipRelativeZUsers = false;
1913 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001914
Robert Carr1f0a16a2016-10-24 16:27:39 -07001915 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001916 for (; i < list.size(); i++) {
1917 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001918 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1919 continue;
1920 }
1921
chaviw301b1d82019-11-06 13:15:09 -08001922 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001923 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001924 }
Dan Stoza412903f2017-04-27 13:42:17 -07001925 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001926 }
Robert Carr29abff82017-12-04 13:51:20 -08001927
Dan Stoza412903f2017-04-27 13:42:17 -07001928 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001929 for (; i < list.size(); i++) {
1930 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001931
Robert Carr29abff82017-12-04 13:51:20 -08001932 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1933 continue;
1934 }
Dan Stoza412903f2017-04-27 13:42:17 -07001935 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001936 }
1937}
1938
1939/**
Robert Carrdb66e622017-04-10 16:55:57 -07001940 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001941 */
Dan Stoza412903f2017-04-27 13:42:17 -07001942void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1943 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001944 // See traverseInZOrder for documentation.
1945 bool skipRelativeZUsers = false;
1946 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001947
Robert Carr1f0a16a2016-10-24 16:27:39 -07001948 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001949 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001950 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001951
1952 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1953 continue;
1954 }
1955
chaviw301b1d82019-11-06 13:15:09 -08001956 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001957 break;
1958 }
Dan Stoza412903f2017-04-27 13:42:17 -07001959 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001960 }
Dan Stoza412903f2017-04-27 13:42:17 -07001961 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001962 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001963 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001964
1965 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1966 continue;
1967 }
1968
Dan Stoza412903f2017-04-27 13:42:17 -07001969 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001970 }
1971}
1972
Edgar Arriaga844fa672020-01-16 14:21:42 -08001973void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1974 visitor(this);
1975 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001976 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001977 for (const sp<Layer>& child : children) {
1978 child->traverse(state, visitor);
1979 }
1980}
1981
Vishnu Nair787aa782023-03-17 13:46:46 -07001982void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
1983 for (const sp<Layer>& child : mDrawingChildren) {
1984 visitor(child.get());
1985 }
1986}
1987
chaviw4b129c22018-04-09 16:19:43 -07001988LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1989 const std::vector<Layer*>& layersInTree) {
1990 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1991 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001992 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1993 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001994 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001995
chaviwfd462612018-05-31 16:11:27 -07001996 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001997 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1998 sp<Layer> strongRelative = weakRelative.promote();
1999 // Only add relative layers that are also descendents of the top most parent of the tree.
2000 // If a relative layer is not a descendent, then it should be ignored.
2001 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
2002 traverse.add(strongRelative);
2003 }
2004 }
2005
2006 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07002007 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002008 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
2009 // descendent of the top most parent of the tree. If it's not a descendent, then just add
2010 // the child here since it won't be added later as a relative.
2011 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
2012 childState.zOrderRelativeOf.promote().get())) {
2013 continue;
2014 }
2015 traverse.add(child);
2016 }
2017
2018 return traverse;
2019}
2020
2021void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
2022 LayerVector::StateSet stateSet,
2023 const LayerVector::Visitor& visitor) {
2024 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07002025
2026 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07002027 for (; i < list.size(); i++) {
2028 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08002029 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07002030 break;
2031 }
chaviw4b129c22018-04-09 16:19:43 -07002032 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002033 }
chaviw4b129c22018-04-09 16:19:43 -07002034
chaviwa76b2712017-09-20 12:02:26 -07002035 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07002036 for (; i < list.size(); i++) {
2037 const auto& relative = list[i];
2038 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002039 }
2040}
2041
chaviw4b129c22018-04-09 16:19:43 -07002042std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2043 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2044 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2045
2046 std::vector<Layer*> layersInTree = {this};
2047 for (size_t i = 0; i < children.size(); i++) {
2048 const auto& child = children[i];
2049 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2050 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2051 }
2052
2053 return layersInTree;
2054}
2055
2056void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2057 const LayerVector::Visitor& visitor) {
2058 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2059 std::sort(layersInTree.begin(), layersInTree.end());
2060 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2061}
2062
Peiyong Linefefaac2018-08-17 12:27:51 -07002063ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08002064 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002065}
2066
Garfield Tan2c1782c2022-02-16 15:25:05 -08002067bool Layer::isTransformValid() const {
2068 float transformDet = getTransform().det();
2069 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2070}
2071
chaviw13fdc492017-06-27 12:40:18 -07002072half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002073 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002074
chaviw13fdc492017-06-27 12:40:18 -07002075 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2076 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002077}
Robert Carr6452f122017-03-21 10:41:29 -07002078
Vishnu Nair6213bd92020-05-08 17:42:25 -07002079ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002080 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002081 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2082 return fixedTransformHint;
2083 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002084 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002085 if (!p) return fixedTransformHint;
2086 return p->getFixedTransformHint();
2087}
2088
chaviw13fdc492017-06-27 12:40:18 -07002089half4 Layer::getColor() const {
2090 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002091 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002092}
Robert Carr6452f122017-03-21 10:41:29 -07002093
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002094int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002095 if (getDrawingState().backgroundBlurRadius == 0) {
2096 return 0;
2097 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002098
Vishnu Nair29810f72022-07-01 16:38:41 +00002099 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002100 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2101 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002102}
2103
Galia Peychevae0acf382021-04-12 21:22:34 +02002104const std::vector<BlurRegion> Layer::getBlurRegions() const {
2105 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002106 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002107 for (auto& region : regionsCopy) {
2108 region.alpha = region.alpha * layerAlpha;
2109 }
2110 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002111}
2112
Vishnu Naire14c6b32022-08-06 04:20:15 +00002113RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002114 // Get parent settings
2115 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002116 const auto& parent = mDrawingParent.promote();
2117 if (parent != nullptr) {
2118 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002119 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002120 ui::Transform t = getActiveTransform(getDrawingState());
2121 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002122 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002123 parentSettings.radius.x *= t.getScaleX();
2124 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002125 }
2126 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002127
2128 // Get layer settings
2129 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002130 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002131 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002132 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002133
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002134 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002135 // If the parent and the layer have rounded corner settings, use the parent settings if the
2136 // parent crop is entirely inside the layer crop.
2137 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2138 if (parentSettings.cropRect.left > layerCropRect.left &&
2139 parentSettings.cropRect.top > layerCropRect.top &&
2140 parentSettings.cropRect.right < layerCropRect.right &&
2141 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2142 return parentSettings;
2143 } else {
2144 return layerSettings;
2145 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002146 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002147 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002148 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002149 return parentSettings;
2150 }
2151 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002152}
2153
Robert Carr88b85e12022-03-21 15:47:35 -07002154bool Layer::findInHierarchy(const sp<Layer>& l) {
2155 if (l == this) {
2156 return true;
2157 }
2158 for (auto& child : mDrawingChildren) {
2159 if (child->findInHierarchy(l)) {
2160 return true;
2161 }
2162 }
2163 return false;
2164}
2165
Robert Carr1f0a16a2016-10-24 16:27:39 -07002166void Layer::commitChildList() {
2167 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2168 const auto& child = mCurrentChildren[i];
2169 child->commitChildList();
2170 }
2171 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002172 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002173 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2174 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2175 if (zOrderRelativeOf == nullptr) return;
2176 if (findInHierarchy(zOrderRelativeOf)) {
2177 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2178 zOrderRelativeOf->mName.c_str());
2179 ALOGE("Severing rel Z loop, potentially dangerous");
2180 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002181 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002182 }
2183 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002184}
2185
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002186
chaviw3277faf2021-05-19 16:45:23 -05002187void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002188 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002189 mDrawingState.touchableRegionCrop =
2190 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002191 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002192 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002193 setTransactionFlags(eTransactionNeeded);
2194}
2195
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002196LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002197 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002198 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002199 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2200
Vishnu Nair00b90132021-11-05 14:03:40 -07002201 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nair2f65e972023-04-04 16:36:28 +00002202 ui::LayerStack layerStack =
2203 (mSnapshot) ? mSnapshot->outputFilter.layerStack : ui::INVALID_LAYER_STACK;
2204 writeCompositionStateToProto(layerProto, layerStack);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002205 }
2206
chaviw08f3cb22020-01-13 13:17:21 -08002207 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002208 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002209 }
chaviw6d89e2d2020-01-14 14:42:01 -08002210
2211 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002212}
2213
Vishnu Nair2f65e972023-04-04 16:36:28 +00002214void Layer::writeCompositionStateToProto(LayerProto* layerProto, ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002215 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002216 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +00002217
2218 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002219 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002220 const auto compositionType = getCompositionType(*display);
2221 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +00002222 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +00002223 [&]() { return layerProto->mutable_visible_region(); });
2224 }
2225}
2226
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002227void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002228 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002229 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002230 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002231 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002232 [&]() { return layerInfo->mutable_active_buffer(); });
2233 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2234 layerInfo->mutable_buffer_transform());
2235 }
2236 layerInfo->set_invalidate(contentDirty);
2237 layerInfo->set_is_protected(isProtected());
2238 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2239 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002240 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002241 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002242 layerInfo->set_corner_radius(
2243 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002244 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2245 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2246 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2247 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2248 [&]() { return layerInfo->mutable_position(); });
2249 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002250 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2251 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002252
Vishnu Nair00b90132021-11-05 14:03:40 -07002253 if (hasColorTransform()) {
2254 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002255 }
2256
Vishnu Nair60db8c02020-04-02 11:55:16 -07002257 LayerProtoHelper::writeToProto(mSourceBounds,
2258 [&]() { return layerInfo->mutable_source_bounds(); });
2259 LayerProtoHelper::writeToProto(mScreenBounds,
2260 [&]() { return layerInfo->mutable_screen_bounds(); });
2261 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2262 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2263 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002264}
2265
2266void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002267 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002268 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2269 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002270 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002271
chaviw766c9c52021-02-10 17:36:47 -08002272 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002273
Vishnu Nair00b90132021-11-05 14:03:40 -07002274 layerInfo->set_id(sequence);
2275 layerInfo->set_name(getName().c_str());
2276 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002277
Vishnu Nair00b90132021-11-05 14:03:40 -07002278 for (const auto& child : children) {
2279 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002280 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002281
Vishnu Nair00b90132021-11-05 14:03:40 -07002282 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2283 sp<Layer> strongRelative = weakRelative.promote();
2284 if (strongRelative != nullptr) {
2285 layerInfo->add_relatives(strongRelative->sequence);
2286 }
2287 }
2288
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002289 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002290 [&]() { return layerInfo->mutable_transparent_region(); });
2291
2292 layerInfo->set_layer_stack(getLayerStack().id);
2293 layerInfo->set_z(state.z);
2294
2295 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2296 return layerInfo->mutable_requested_position();
2297 });
2298
Vishnu Nair00b90132021-11-05 14:03:40 -07002299 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2300
2301 layerInfo->set_is_opaque(isOpaque(state));
2302
2303 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2304 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2305 LayerProtoHelper::writeToProto(state.color,
2306 [&]() { return layerInfo->mutable_requested_color(); });
2307 layerInfo->set_flags(state.flags);
2308
2309 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2310 layerInfo->mutable_requested_transform());
2311
2312 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2313 if (parent != nullptr) {
2314 layerInfo->set_parent(parent->sequence);
2315 } else {
2316 layerInfo->set_parent(-1);
2317 }
2318
2319 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2320 if (zOrderRelativeOf != nullptr) {
2321 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2322 } else {
2323 layerInfo->set_z_order_relative_of(-1);
2324 }
2325
2326 layerInfo->set_is_relative_of(state.isRelativeOf);
2327
2328 layerInfo->set_owner_uid(mOwnerUid);
2329
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002330 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002331 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002332 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002333 info = fillInputInfo(
2334 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002335 } else {
2336 info = state.inputInfo;
2337 }
2338
2339 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002340 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002341 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002342
Vishnu Nair00b90132021-11-05 14:03:40 -07002343 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002344 auto protoMap = layerInfo->mutable_metadata();
2345 for (const auto& entry : state.metadata.mMap) {
2346 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2347 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002348 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002349
2350 LayerProtoHelper::writeToProto(state.destinationFrame,
2351 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002352}
2353
Robert Carr2e102c92018-10-23 12:11:15 -07002354bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002355 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002356}
2357
Prabir Pradhan33da9462022-06-14 14:55:57 +00002358// Applies the given transform to the region, while protecting against overflows caused by any
2359// offsets. If applying the offset in the transform to any of the Rects in the region would result
2360// in an overflow, they are not added to the output Region.
2361static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2362 const std::string& debugWindowName) {
2363 // Round the translation using the same rounding strategy used by ui::Transform.
2364 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2365 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2366
2367 ui::Transform transformWithoutOffset = t;
2368 transformWithoutOffset.set(0.f, 0.f);
2369
2370 const Region transformed = transformWithoutOffset.transform(r);
2371
2372 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2373 Region ret;
2374 for (const auto& rect : transformed) {
2375 Rect newRect;
2376 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2377 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2378 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2379 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2380 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2381 debugWindowName.c_str());
2382 continue;
2383 }
2384 ret.orSelf(newRect);
2385 }
2386 return ret;
2387}
2388
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002389void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002390 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2391 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002392 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002393 }
2394
Vishnu Nairfed7c122023-03-18 01:54:43 +00002395 const Rect roundedFrameInDisplay = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002396 info.frameLeft = roundedFrameInDisplay.left;
2397 info.frameTop = roundedFrameInDisplay.top;
2398 info.frameRight = roundedFrameInDisplay.right;
2399 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002400
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002401 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002402 inputToLayer.set(inputBounds.left, inputBounds.top);
2403 const ui::Transform layerToScreen = getInputTransform();
2404 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002405
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002406 // InputDispatcher expects a display-to-input transform.
2407 info.transform = inputToDisplay.inverse();
2408
2409 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002410 info.touchableRegion =
2411 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002412}
2413
chaviw3277faf2021-05-19 16:45:23 -05002414void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002415 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002416 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002417 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002418 }
2419 if (p != nullptr) {
2420 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2421 }
2422}
2423
Vishnu Naira066d902021-09-13 18:40:17 -07002424gui::DropInputMode Layer::getDropInputMode() const {
2425 gui::DropInputMode mode = mDrawingState.dropInputMode;
2426 if (mode == gui::DropInputMode::ALL) {
2427 return mode;
2428 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002429 sp<Layer> parent = mDrawingParent.promote();
2430 if (parent) {
2431 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002432 if (parentMode != gui::DropInputMode::NONE) {
2433 return parentMode;
2434 }
2435 }
2436 return mode;
2437}
2438
2439void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002440 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002441 return;
2442 }
2443
2444 // Check if we need to drop input unconditionally
2445 gui::DropInputMode dropInputMode = getDropInputMode();
2446 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002447 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002448 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2449 return;
2450 }
2451
2452 // Check if we need to check if the window is obscured by parent
2453 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2454 return;
2455 }
2456
2457 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002458 sp<Layer> parent = mDrawingParent.promote();
2459 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002460 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002461 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2462 static_cast<float>(getAlpha()));
2463 }
2464
2465 // Check if the parent has cropped the buffer
2466 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2467 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002468 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002469 return;
2470 }
2471
2472 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2473 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2474 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2475 // match then the layer has not been cropped by its parents.
2476 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2477 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2478
2479 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002480 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002481 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2482 getDebugName());
2483 } else {
2484 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2485 // input if the window is obscured. This check should be done in surfaceflinger but the
2486 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2487 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002488 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002489 }
2490}
2491
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002492WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002493 if (!hasInputInfo()) {
2494 mDrawingState.inputInfo.name = getName();
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002495 mDrawingState.inputInfo.ownerUid = gui::Uid{mOwnerUid};
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00002496 mDrawingState.inputInfo.ownerPid = gui::Pid{mOwnerPid};
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002497 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002498 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002499 }
2500
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002501 const ui::Transform& displayTransform =
2502 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2503
chaviw3277faf2021-05-19 16:45:23 -05002504 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002505 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002506 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002507
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002508 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002509
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002510 if (displayArgs.transform == nullptr) {
2511 // Do not let the window receive touches if it is not associated with a valid display
2512 // transform. We still allow the window to receive keys and prevent ANRs.
2513 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2514 }
2515
Patrick Williams1caf3b72023-03-31 10:59:10 -05002516 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !isVisibleForInput());
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002517
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002518 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002519 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002520 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002521
Vishnu Nair16a938f2021-09-24 07:14:54 -07002522 // If the window will be blacked out on a display because the display does not have the secure
2523 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002524 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002525 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002526 }
2527
Vishnu Nairfed7c122023-03-18 01:54:43 +00002528 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002529 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002530 Rect inputBoundsInDisplaySpace;
2531 if (!cropLayer) {
2532 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2533 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2534 } else {
2535 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2536 inputBoundsInDisplaySpace =
2537 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2538 }
2539 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002540 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002541 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2542 Rect inputBoundsInDisplaySpace =
2543 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2544 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002545 }
2546
Winson Chunga30f7c92021-06-29 15:42:56 -07002547 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2548 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002549 if (isTrustedOverlay()) {
2550 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2551 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002552
chaviwaf87b3e2019-10-01 16:59:28 -07002553 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2554 // touches from going outside the cloned area.
2555 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002556 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002557 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2558 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002559 info.touchableRegion = info.touchableRegion.intersect(rect);
2560 }
2561 }
2562
Robert Carr720e5062018-07-30 17:45:14 -07002563 return info;
2564}
2565
Vishnu Nairfed7c122023-03-18 01:54:43 +00002566Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2567 const ui::Transform& screenToDisplay) {
2568 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2569 // frame and transform used for the layer, which determines the bounds and the coordinate space
2570 // within which the layer will receive input.
2571
2572 // Coordinate space definitions:
2573 // - display: The display device's coordinate space. Correlates to pixels on the display.
2574 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2575 // - layer: The coordinate space of this layer.
2576 // - input: The coordinate space in which this layer will receive input events. This could be
2577 // different than layer space if a surfaceInset is used, which changes the origin
2578 // of the input space.
2579
2580 // Crop the input bounds to ensure it is within the parent's bounds.
2581 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2582 const ui::Transform layerToScreen = getInputTransform();
2583 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2584 return Rect{layerToDisplay.transform(croppedInputBounds)};
2585}
2586
chaviwaf87b3e2019-10-01 16:59:28 -07002587sp<Layer> Layer::getClonedRoot() {
2588 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002589 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002590 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002591 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002592 return nullptr;
2593 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002594 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002595}
2596
Robert Carredd13602020-04-13 17:24:34 -07002597bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002598 return mDrawingState.inputInfo.token != nullptr ||
2599 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002600}
2601
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002602compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002603 const DisplayDevice* display) const {
2604 if (!display) return nullptr;
Lloyd Pique30db6402023-06-26 18:56:51 +00002605 if (!mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00002606 return display->getCompositionDisplay()->getOutputLayerForLayer(
2607 getCompositionEngineLayerFE());
2608 }
2609 sp<LayerFE> layerFE;
2610 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2611 for (auto& [p, layer] : mLayerFEs) {
2612 if (p == path) {
2613 layerFE = layer;
2614 }
2615 }
2616
2617 if (!layerFE) return nullptr;
2618 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002619}
2620
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002621compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
2622 const DisplayDevice* display, const frontend::LayerHierarchy::TraversalPath& path) const {
2623 if (!display) return nullptr;
Vishnu Naire9ee0002023-07-01 03:14:51 +00002624 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2625 return display->getCompositionDisplay()->getOutputLayerForLayer(
2626 getCompositionEngineLayerFE());
2627 }
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002628 sp<LayerFE> layerFE;
2629 for (auto& [p, layer] : mLayerFEs) {
2630 if (p == path) {
2631 layerFE = layer;
2632 }
2633 }
2634
2635 if (!layerFE) return nullptr;
2636 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
2637}
2638
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002639Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2640 const auto outputLayer = findOutputLayerForDisplay(display);
2641 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002642}
2643
Vishnu Nairde177252023-04-21 12:44:10 -07002644void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom, uint32_t mirrorRootId) {
2645 mSnapshot->path.id = clonedFrom->getSequence();
2646 mSnapshot->path.mirrorRootId = mirrorRootId;
2647
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002648 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002649 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002650 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2651 mPotentialCursor = clonedFrom->mPotentialCursor;
2652 mProtectedByApp = clonedFrom->mProtectedByApp;
2653 updateCloneBufferInfo();
2654}
2655
2656void Layer::updateCloneBufferInfo() {
2657 if (!isClone() || !isClonedFromAlive()) {
2658 return;
2659 }
2660
2661 sp<Layer> clonedFrom = getClonedFrom();
2662 mBufferInfo = clonedFrom->mBufferInfo;
2663 mSidebandStream = clonedFrom->mSidebandStream;
2664 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2665 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2666 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2667
2668 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2669 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2670 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2671 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2672 // the cloned drawingState again.
2673 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2674 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2675 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2676 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2677
2678 cloneDrawingState(clonedFrom.get());
2679
2680 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2681 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2682 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2683 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002684}
chaviw74b03172019-08-19 11:09:03 -07002685
Vishnu Nair3be61902023-04-26 19:47:29 -07002686bool Layer::updateMirrorInfo(const std::deque<Layer*>& cloneRootsPendingUpdates) {
chaviw74b03172019-08-19 11:09:03 -07002687 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2688 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2689 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2690 // that case, we want to delete the reference to the clone since we want it to get
2691 // destroyed. The root, this layer, will still be around since the client can continue
2692 // to hold a reference, but no cloned layers will be displayed.
2693 mClonedChild = nullptr;
Vishnu Nair3be61902023-04-26 19:47:29 -07002694 return true;
chaviw74b03172019-08-19 11:09:03 -07002695 }
2696
2697 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2698 // If the real layer exists and is in current state, add the clone as a child of the root.
2699 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2700 // copied to drawingState for the root layer. So the clonedChild is always removed from
2701 // drawingState and then needs to be added back each traversal.
2702 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2703 addChildToDrawing(mClonedChild);
2704 }
2705
2706 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002707 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002708 mClonedChild->updateClonedRelatives(clonedLayersMap);
Vishnu Nair3be61902023-04-26 19:47:29 -07002709
2710 for (Layer* root : cloneRootsPendingUpdates) {
2711 if (clonedLayersMap.find(sp<Layer>::fromExisting(root)) != clonedLayersMap.end()) {
2712 return false;
2713 }
2714 }
2715 return true;
chaviw74b03172019-08-19 11:09:03 -07002716}
2717
2718void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2719 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2720 // to the clone. If the real layer is no longer alive, continue traversing the children
2721 // since we may be able to pull out other children that are still alive.
2722 if (isClonedFromAlive()) {
2723 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002724 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002725 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002726 }
2727
2728 // The clone layer may have children in drawingState since they may have been created and
2729 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2730 // that already exist, since we can just re-use them.
2731 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2732 // not updated in the regular traversal. They are skipped since the root will lose the
2733 // reference to them when it copies its currentChildren to drawing.
2734 for (sp<Layer>& child : mDrawingChildren) {
2735 child->updateClonedDrawingState(clonedLayersMap);
2736 }
2737}
2738
2739void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2740 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2741 mDrawingChildren.clear();
2742
2743 if (!isClonedFromAlive()) {
2744 return;
2745 }
2746
2747 sp<Layer> clonedFrom = getClonedFrom();
2748 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2749 if (child == mirrorRoot) {
2750 // This is to avoid cyclical mirroring.
2751 continue;
2752 }
2753 sp<Layer> clonedChild = clonedLayersMap[child];
2754 if (clonedChild == nullptr) {
Vishnu Nairde177252023-04-21 12:44:10 -07002755 clonedChild = child->createClone(mirrorRoot->getSequence());
chaviw74b03172019-08-19 11:09:03 -07002756 clonedLayersMap[child] = clonedChild;
2757 }
2758 addChildToDrawing(clonedChild);
2759 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2760 }
2761}
2762
chaviwaf87b3e2019-10-01 16:59:28 -07002763void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2764 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2765 if (cropLayer != nullptr) {
2766 if (clonedLayersMap.count(cropLayer) == 0) {
2767 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2768 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002769 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002770 } else {
2771 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2772 mDrawingState.touchableRegionCrop = clonedCropLayer;
2773 }
2774 }
2775 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2776 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002777 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002778}
2779
2780void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002781 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002782 mDrawingState.zOrderRelatives.clear();
2783
2784 if (!isClonedFromAlive()) {
2785 return;
2786 }
2787
chaviwaf87b3e2019-10-01 16:59:28 -07002788 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002789 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002790 const sp<Layer>& relative = relativeWeak.promote();
2791 if (clonedLayersMap.count(relative) > 0) {
2792 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002793 mDrawingState.zOrderRelatives.add(clonedRelative);
2794 }
2795 }
2796
2797 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2798 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2799 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2800 // still traverse the children, but the layer with the missing relativeOf will not be shown
2801 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002802 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2803 if (clonedLayersMap.count(relativeOf) > 0) {
2804 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002805 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2806 }
2807
chaviwaf87b3e2019-10-01 16:59:28 -07002808 updateClonedInputInfo(clonedLayersMap);
2809
chaviw74b03172019-08-19 11:09:03 -07002810 for (sp<Layer>& child : mDrawingChildren) {
2811 child->updateClonedRelatives(clonedLayersMap);
2812 }
2813}
2814
2815void Layer::addChildToDrawing(const sp<Layer>& layer) {
2816 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002817 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002818}
2819
Steven Thomas62a4cf82020-01-31 12:04:03 -08002820Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2821 switch (compatibility) {
2822 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2823 return FrameRateCompatibility::Default;
2824 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2825 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002826 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2827 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002828 case ANATIVEWINDOW_FRAME_RATE_MIN:
2829 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002830 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2831 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002832 default:
2833 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2834 return FrameRateCompatibility::Default;
2835 }
2836}
2837
Marin Shalamanovc5986772021-03-16 16:09:49 +01002838scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2839 switch (strategy) {
2840 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2841 return Seamlessness::OnlySeamless;
2842 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2843 return Seamlessness::SeamedAndSeamless;
2844 default:
2845 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2846 return Seamlessness::Default;
2847 }
2848}
2849
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002850bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002851 const State& s(mDrawingState);
2852 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2853 return true;
2854 }
2855
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002856 sp<Layer> parent = mDrawingParent.promote();
2857 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002858}
2859
Robert Carr6a0382d2021-07-01 15:57:17 -07002860void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2861 mClonedChild = clonedChild;
2862 mHadClonedChild = true;
Vishnu Nair3be61902023-04-26 19:47:29 -07002863 mFlinger->mLayerMirrorRoots.push_back(this);
Robert Carr6a0382d2021-07-01 15:57:17 -07002864}
2865
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002866bool Layer::setDropInputMode(gui::DropInputMode mode) {
2867 if (mDrawingState.dropInputMode == mode) {
2868 return false;
2869 }
2870 mDrawingState.dropInputMode = mode;
2871 return true;
2872}
2873
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002874void Layer::cloneDrawingState(const Layer* from) {
2875 mDrawingState = from->mDrawingState;
2876 // Skip callback info since they are not applicable for cloned layers.
2877 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002878 // TODO (b/238781169) currently broken for mirror layers because we do not
2879 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002880 mDrawingState.callbackHandles = {};
2881}
2882
Patrick Williamsbb25f802022-08-30 23:02:34 +00002883void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2884 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002885 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002886 if (!listener) {
2887 return;
2888 }
2889 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002890 uint32_t currentMaxAcquiredBufferCount =
2891 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002892 listener->onReleaseBuffer({buffer->getId(), framenumber},
2893 releaseFence ? releaseFence : Fence::NO_FENCE,
2894 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002895}
2896
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002897void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
2898 ui::LayerStack layerStack) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002899 // If we are displayed on multiple displays in a single composition cycle then we would
2900 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2901 // For example we can only use it if all the displays are client comp, and we need
2902 // to merge all the client comp fences. We could do this, but for now we just
2903 // disable the optimization when a layer is composed on multiple displays.
2904 if (mClearClientCompositionFenceOnLayerDisplayed) {
2905 mLastClientCompositionFence = nullptr;
2906 } else {
2907 mClearClientCompositionFenceOnLayerDisplayed = true;
2908 }
2909
2910 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2911 // buffer that was presented on this layer. The first transaction that came in this frame that
2912 // replaced the previous buffer on this layer needs this release fence, because the fence will
2913 // let the client know when that previous buffer is removed from the screen.
2914 //
2915 // Every other transaction on this layer does not need a release fence because no other
2916 // Transactions that were set on this layer this frame are going to have their preceding buffer
2917 // removed from the display this frame.
2918 //
2919 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2920 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2921 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2922 // the previous buffer will be released this frame. The third transaction also contains a
2923 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2924 // transaction will now no longer be presented so it is released immediately and the third
2925 // transaction doesn't need a previous release fence.
2926 sp<CallbackHandle> ch;
2927 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002928 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002929 ch = handle;
2930 break;
2931 }
2932 }
2933
2934 // Prevent tracing the same release multiple times.
2935 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2936 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2937 }
2938
2939 if (ch != nullptr) {
2940 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2941 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2942 ch->name = mName;
2943 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002944 mPreviouslyPresentedLayerStacks.push_back(layerStack);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002945}
2946
2947void Layer::onSurfaceFrameCreated(
2948 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2949 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2950 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2951 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2952 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002953 if (hasBufferOrSidebandStreamInDrawing()) {
2954 // Only log for layers with a buffer, since we expect the jank data to be drained for
2955 // these, while there may be no jank listeners for bufferless layers.
2956 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2957 mName.c_str());
2958 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2959 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2960 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002961 mPendingJankClassifications.pop_front();
2962 }
2963 mPendingJankClassifications.emplace_back(surfaceFrame);
2964}
2965
2966void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2967 for (const auto& handle : mDrawingState.callbackHandles) {
Lloyd Pique30db6402023-06-26 18:56:51 +00002968 if (mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -07002969 handle->transformHint = mTransformHint;
2970 } else {
2971 handle->transformHint = mSkipReportingTransformHint
2972 ? std::nullopt
2973 : std::make_optional<uint32_t>(mTransformHintLegacy);
2974 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002975 handle->dequeueReadyTime = dequeueReadyTime;
2976 handle->currentMaxAcquiredBufferCount =
2977 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2978 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2979 handle->previousReleaseCallbackId.framenumber);
2980 }
2981
2982 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002983 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002984 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2985 break;
2986 }
2987 }
2988
2989 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002990 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002991 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2992 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002993 mDrawingState.callbackHandles = {};
2994}
2995
2996bool Layer::willPresentCurrentTransaction() const {
2997 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2998 return (getSidebandStreamChanged() || getAutoRefresh() ||
2999 (mDrawingState.modified &&
3000 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
3001}
3002
3003bool Layer::setTransform(uint32_t transform) {
3004 if (mDrawingState.bufferTransform == transform) return false;
3005 mDrawingState.bufferTransform = transform;
3006 mDrawingState.modified = true;
3007 setTransactionFlags(eTransactionNeeded);
3008 return true;
3009}
3010
3011bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
3012 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
3013 mDrawingState.sequence++;
3014 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
3015 mDrawingState.modified = true;
3016 setTransactionFlags(eTransactionNeeded);
3017 return true;
3018}
3019
3020bool Layer::setBufferCrop(const Rect& bufferCrop) {
3021 if (mDrawingState.bufferCrop == bufferCrop) return false;
3022
3023 mDrawingState.sequence++;
3024 mDrawingState.bufferCrop = bufferCrop;
3025
3026 mDrawingState.modified = true;
3027 setTransactionFlags(eTransactionNeeded);
3028 return true;
3029}
3030
3031bool Layer::setDestinationFrame(const Rect& destinationFrame) {
3032 if (mDrawingState.destinationFrame == destinationFrame) return false;
3033
3034 mDrawingState.sequence++;
3035 mDrawingState.destinationFrame = destinationFrame;
3036
3037 mDrawingState.modified = true;
3038 setTransactionFlags(eTransactionNeeded);
3039 return true;
3040}
3041
3042// Translate destination frame into scale and position. If a destination frame is not set, use the
3043// provided scale and position
3044bool Layer::updateGeometry() {
3045 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
3046 mDrawingState.destinationFrame.isEmpty()) {
3047 // If destination frame is not set, use the requested transform set via
3048 // Layer::setPosition and Layer::setMatrix.
3049 return assignTransform(&mDrawingState.transform, mRequestedTransform);
3050 }
3051
3052 Rect destRect = mDrawingState.destinationFrame;
3053 int32_t destW = destRect.width();
3054 int32_t destH = destRect.height();
3055 if (destRect.left < 0) {
3056 destRect.left = 0;
3057 destRect.right = destW;
3058 }
3059 if (destRect.top < 0) {
3060 destRect.top = 0;
3061 destRect.bottom = destH;
3062 }
3063
3064 if (!mDrawingState.buffer) {
3065 ui::Transform t;
3066 t.set(destRect.left, destRect.top);
3067 return assignTransform(&mDrawingState.transform, t);
3068 }
3069
3070 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3071 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3072 // Undo any transformations on the buffer.
3073 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3074 std::swap(bufferWidth, bufferHeight);
3075 }
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003076 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003077 if (mDrawingState.transformToDisplayInverse) {
3078 if (invTransform & ui::Transform::ROT_90) {
3079 std::swap(bufferWidth, bufferHeight);
3080 }
3081 }
3082
3083 float sx = destW / static_cast<float>(bufferWidth);
3084 float sy = destH / static_cast<float>(bufferHeight);
3085 ui::Transform t;
3086 t.set(sx, 0, 0, sy);
3087 t.set(destRect.left, destRect.top);
3088 return assignTransform(&mDrawingState.transform, t);
3089}
3090
3091bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3092 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3093 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3094 return false;
3095 }
3096
3097 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3098
3099 mDrawingState.sequence++;
3100 mDrawingState.modified = true;
3101 setTransactionFlags(eTransactionNeeded);
3102
3103 return true;
3104}
3105
3106bool Layer::setPosition(float x, float y) {
3107 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3108 return false;
3109 }
3110
3111 mRequestedTransform.set(x, y);
3112
3113 mDrawingState.sequence++;
3114 mDrawingState.modified = true;
3115 setTransactionFlags(eTransactionNeeded);
3116
3117 return true;
3118}
3119
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003120void Layer::resetDrawingStateBufferInfo() {
3121 mDrawingState.producerId = 0;
3122 mDrawingState.frameNumber = 0;
3123 mDrawingState.releaseBufferListener = nullptr;
3124 mDrawingState.buffer = nullptr;
3125 mDrawingState.acquireFence = sp<Fence>::make(-1);
3126 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3127 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3128 mDrawingState.releaseBufferEndpoint = nullptr;
3129}
3130
Patrick Williamsbb25f802022-08-30 23:02:34 +00003131bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3132 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3133 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003134 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003135 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003136
3137 const bool frameNumberChanged =
3138 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3139 const uint64_t frameNumber =
3140 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003141 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003142
3143 if (mDrawingState.buffer) {
3144 mReleasePreviousBuffer = true;
3145 if (!mBufferInfo.mBuffer ||
3146 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3147 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3148 // If mDrawingState has a buffer, and we are about to update again
3149 // before swapping to drawing state, then the first buffer will be
3150 // dropped and we should decrement the pending buffer count and
3151 // call any release buffer callbacks if set.
3152 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3153 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003154 mDrawingState.acquireFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003155 decrementPendingBufferCount();
3156 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3157 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
Ady Abraham5a3e3562023-06-07 10:32:08 -07003158 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX, systemTime());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003159 mDrawingState.bufferSurfaceFrameTX.reset();
3160 }
3161 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3162 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3163 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003164 mLastClientCompositionFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003165 mLastClientCompositionFence = nullptr;
3166 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003167 } else if (buffer) {
Vishnu Nairc09c0232023-03-02 03:22:35 +00003168 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3169 // we don't want to incorrectly classify a frame if we miss the desired present time.
3170 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003171 }
3172
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003173 mDrawingState.desiredPresentTime = desiredPresentTime;
3174 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3175 mDrawingState.latchedVsyncId = info.vsyncId;
Ady Abraham55269162023-05-09 11:26:06 -07003176 mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003177 mDrawingState.modified = true;
3178 if (!buffer) {
3179 resetDrawingStateBufferInfo();
3180 setTransactionFlags(eTransactionNeeded);
3181 mDrawingState.bufferSurfaceFrameTX = nullptr;
3182 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3183 return true;
3184 }
3185
Vishnu Naird1f74982023-06-15 20:16:51 -07003186 if ((mDrawingState.producerId > bufferData.producerId) ||
3187 ((mDrawingState.producerId == bufferData.producerId) &&
3188 (mDrawingState.frameNumber > frameNumber))) {
3189 ALOGE("Out of order buffers detected for %s producedId=%d frameNumber=%" PRIu64
3190 " -> producedId=%d frameNumber=%" PRIu64,
3191 getDebugName(), mDrawingState.producerId, mDrawingState.frameNumber,
3192 bufferData.producerId, frameNumber);
3193 TransactionTraceWriter::getInstance().invoke("out_of_order_buffers_", /*overwrite=*/false);
3194 }
3195
liulijuneb489f62022-10-17 22:02:14 +08003196 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -07003197 mDrawingState.barrierProducerId =
3198 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003199 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -07003200 mDrawingState.barrierFrameNumber =
3201 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
3202
Patrick Williamsbb25f802022-08-30 23:02:34 +00003203 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3204 mDrawingState.buffer = std::move(buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003205 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3206 ? bufferData.acquireFence
3207 : Fence::NO_FENCE;
3208 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3209 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3210 // We latched this buffer unsiganled, so we need to pass the acquire fence
3211 // on the callback instead of just the acquire time, since it's unknown at
3212 // this point.
3213 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3214 } else {
3215 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3216 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003217 setTransactionFlags(eTransactionNeeded);
3218
3219 const int32_t layerId = getSequence();
3220 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3221 mOwnerUid, postTime, getGameMode());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003222
Lloyd Pique30db6402023-06-26 18:56:51 +00003223 if (mFlinger->mLegacyFrontEndEnabled) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003224 recordLayerHistoryBufferUpdate(getLayerProps());
3225 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003226
3227 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3228
3229 if (dequeueTime && *dequeueTime != 0) {
3230 const uint64_t bufferId = mDrawingState.buffer->getId();
3231 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3232 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3233 FrameTracer::FrameEvent::DEQUEUE);
3234 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3235 FrameTracer::FrameEvent::QUEUE);
3236 }
3237
3238 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3239 return true;
3240}
3241
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003242void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3243 mDrawingState.desiredPresentTime = desiredPresentTime;
3244 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3245}
3246
3247void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps) {
Ady Abraham55269162023-05-09 11:26:06 -07003248 ATRACE_CALL();
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003249 const nsecs_t presentTime = [&] {
Ady Abraham55269162023-05-09 11:26:06 -07003250 if (!mDrawingState.isAutoTimestamp) {
3251 ATRACE_FORMAT_INSTANT("desiredPresentTime");
3252 return mDrawingState.desiredPresentTime;
3253 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003254
Ady Abraham55269162023-05-09 11:26:06 -07003255 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3256 const auto prediction =
3257 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3258 mDrawingState.latchedVsyncId);
3259 if (prediction.has_value()) {
3260 ATRACE_FORMAT_INSTANT("predictedPresentTime");
3261 return prediction->presentTime;
3262 }
3263 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003264
3265 return static_cast<nsecs_t>(0);
3266 }();
Ady Abraham55269162023-05-09 11:26:06 -07003267
3268 if (ATRACE_ENABLED() && presentTime > 0) {
3269 const auto presentIn = TimePoint::fromNs(presentTime) - TimePoint::now();
3270 ATRACE_FORMAT_INSTANT("presentIn %s", to_string(presentIn).c_str());
3271 }
3272
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003273 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3274 scheduler::LayerHistory::LayerUpdateType::Buffer);
3275}
3276
3277void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps) {
3278 const nsecs_t presentTime =
3279 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
3280 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3281 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3282}
3283
Patrick Williamsbb25f802022-08-30 23:02:34 +00003284bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003285 if (mDrawingState.dataspace == dataspace) return false;
3286 mDrawingState.dataspace = dataspace;
3287 mDrawingState.modified = true;
3288 setTransactionFlags(eTransactionNeeded);
3289 return true;
3290}
3291
John Reck68796592023-01-25 13:47:12 -05003292bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07003293 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3294 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05003295 return false;
Sally Qi963049b2023-03-23 14:06:21 -07003296 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3297 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05003298 mDrawingState.modified = true;
3299 setTransactionFlags(eTransactionNeeded);
3300 return true;
3301}
3302
Alec Mourif4af03e2023-02-11 00:25:24 +00003303bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3304 if (mDrawingState.cachingHint == cachingHint) return false;
3305 mDrawingState.cachingHint = cachingHint;
3306 mDrawingState.modified = true;
3307 setTransactionFlags(eTransactionNeeded);
3308 return true;
3309}
3310
Patrick Williamsbb25f802022-08-30 23:02:34 +00003311bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3312 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3313 mDrawingState.hdrMetadata = hdrMetadata;
3314 mDrawingState.modified = true;
3315 setTransactionFlags(eTransactionNeeded);
3316 return true;
3317}
3318
3319bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003320 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003321 mDrawingState.surfaceDamageRegion = surfaceDamage;
3322 mDrawingState.modified = true;
3323 setTransactionFlags(eTransactionNeeded);
3324 return true;
3325}
3326
3327bool Layer::setApi(int32_t api) {
3328 if (mDrawingState.api == api) return false;
3329 mDrawingState.api = api;
3330 mDrawingState.modified = true;
3331 setTransactionFlags(eTransactionNeeded);
3332 return true;
3333}
3334
3335bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3336 if (mDrawingState.sidebandStream == sidebandStream) return false;
3337
3338 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3339 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3340 } else if (sidebandStream != nullptr) {
3341 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3342 }
3343
3344 mDrawingState.sidebandStream = sidebandStream;
3345 mDrawingState.modified = true;
3346 setTransactionFlags(eTransactionNeeded);
3347 if (!mSidebandStreamChanged.exchange(true)) {
3348 // mSidebandStreamChanged was false
3349 mFlinger->onLayerUpdate();
3350 }
3351 return true;
3352}
3353
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003354bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3355 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003356 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3357 if (handles.empty()) {
3358 mReleasePreviousBuffer = false;
3359 return false;
3360 }
3361
Pascal Muetschard81cef292023-02-06 12:18:52 +01003362 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003363 for (const auto& handle : handles) {
3364 // If this transaction set a buffer on this layer, release its previous buffer
3365 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3366
3367 // If this layer will be presented in this frame
3368 if (willPresent) {
3369 // If this transaction set an acquire fence on this layer, set its acquire time
3370 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3371 handle->frameNumber = mDrawingState.frameNumber;
3372
3373 // Store so latched time and release fence can be set
3374 mDrawingState.callbackHandles.push_back(handle);
3375
3376 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003377 // Queue this handle to be notified below.
3378 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003379 }
3380 }
3381
Pascal Muetschard81cef292023-02-06 12:18:52 +01003382 if (!remainingHandles.empty()) {
3383 // Notify the transaction completed threads these handles are done. These are only the
3384 // handles that were not added to the mDrawingState, which will be notified later.
3385 std::vector<JankData> jankData;
3386 transferAvailableJankData(remainingHandles, jankData);
3387 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3388 }
3389
Patrick Williamsbb25f802022-08-30 23:02:34 +00003390 mReleasePreviousBuffer = false;
3391 mCallbackHandleAcquireTimeOrFence = -1;
3392
3393 return willPresent;
3394}
3395
3396Rect Layer::getBufferSize(const State& /*s*/) const {
3397 // for buffer state layers we use the display frame size as the buffer size.
3398
3399 if (mBufferInfo.mBuffer == nullptr) {
3400 return Rect::INVALID_RECT;
3401 }
3402
3403 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3404 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3405
3406 // Undo any transformations on the buffer and return the result.
3407 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3408 std::swap(bufWidth, bufHeight);
3409 }
3410
3411 if (getTransformToDisplayInverse()) {
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003412 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003413 if (invTransform & ui::Transform::ROT_90) {
3414 std::swap(bufWidth, bufHeight);
3415 }
3416 }
3417
3418 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3419}
3420
3421FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3422 if (mBufferInfo.mBuffer == nullptr) {
3423 return parentBounds;
3424 }
3425
3426 return getBufferSize(getDrawingState()).toFloatRect();
3427}
3428
3429bool Layer::fenceHasSignaled() const {
3430 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3431 return true;
3432 }
3433
3434 const bool fenceSignaled =
3435 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3436 if (!fenceSignaled) {
3437 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3438 TimeStats::LatchSkipReason::LateAcquire);
3439 }
3440
3441 return fenceSignaled;
3442}
3443
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003444void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003445 for (const auto& handle : mDrawingState.callbackHandles) {
3446 handle->refreshStartTime = refreshStartTime;
3447 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003448}
3449
3450void Layer::setAutoRefresh(bool autoRefresh) {
3451 mDrawingState.autoRefresh = autoRefresh;
3452}
3453
3454bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3455 // 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 +00003456 auto* snapshot = editLayerSnapshot();
3457 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003458
3459 if (mSidebandStreamChanged.exchange(false)) {
3460 const State& s(getDrawingState());
3461 // mSidebandStreamChanged was true
3462 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003463 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003464 if (mSidebandStream != nullptr) {
3465 setTransactionFlags(eTransactionNeeded);
3466 mFlinger->setTransactionFlags(eTraversalNeeded);
3467 }
3468 recomputeVisibleRegions = true;
3469
3470 return true;
3471 }
3472 return false;
3473}
3474
3475bool Layer::hasFrameUpdate() const {
3476 const State& c(getDrawingState());
3477 return (mDrawingStateModified || mDrawingState.modified) &&
3478 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3479}
3480
Vishnu Naird47bcee2023-02-24 18:08:51 +00003481void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003482 const State& s(getDrawingState());
3483
3484 if (!s.buffer) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003485 if (bgColorOnly || mBufferInfo.mBuffer) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003486 for (auto& handle : mDrawingState.callbackHandles) {
3487 handle->latchTime = latchTime;
3488 }
3489 }
3490 return;
3491 }
3492
3493 for (auto& handle : mDrawingState.callbackHandles) {
3494 if (handle->frameNumber == mDrawingState.frameNumber) {
3495 handle->latchTime = latchTime;
3496 }
3497 }
3498
3499 const int32_t layerId = getSequence();
3500 const uint64_t bufferId = mDrawingState.buffer->getId();
3501 const uint64_t frameNumber = mDrawingState.frameNumber;
3502 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3503 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3504 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3505
3506 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3507 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3508 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3509 FrameTracer::FrameEvent::LATCH);
3510
3511 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3512 if (bufferSurfaceFrame != nullptr &&
3513 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3514 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3515 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3516 // are processing the next state.
3517 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3518 mDrawingState.acquireFenceTime->getSignalTime(),
3519 latchTime);
3520 mDrawingState.bufferSurfaceFrameTX.reset();
3521 }
3522
3523 std::deque<sp<CallbackHandle>> remainingHandles;
3524 mFlinger->getTransactionCallbackInvoker()
3525 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3526 mDrawingState.callbackHandles = remainingHandles;
3527
3528 mDrawingStateModified = false;
3529}
3530
3531void Layer::gatherBufferInfo() {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003532 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3533 mPreviousReleaseBufferEndpoint = mBufferInfo.mReleaseBufferEndpoint;
3534 if (!mDrawingState.buffer) {
3535 mBufferInfo = {};
3536 return;
3537 }
3538
3539 if ((!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer))) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003540 decrementPendingBufferCount();
3541 }
3542
Patrick Williamsbb25f802022-08-30 23:02:34 +00003543 mBufferInfo.mBuffer = mDrawingState.buffer;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003544 mBufferInfo.mReleaseBufferEndpoint = mDrawingState.releaseBufferEndpoint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003545 mBufferInfo.mFence = mDrawingState.acquireFence;
3546 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3547 mBufferInfo.mPixelFormat =
3548 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3549 mBufferInfo.mFrameLatencyNeeded = true;
3550 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3551 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3552 mBufferInfo.mFence = mDrawingState.acquireFence;
3553 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3554 auto lastDataspace = mBufferInfo.mDataspace;
3555 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003556 if (mBufferInfo.mBuffer != nullptr) {
3557 auto& mapper = GraphicBufferMapper::get();
3558 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
3559 // and don't need to possibly remaps buffers.
3560 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
3561 status_t err = OK;
3562 {
3563 ATRACE_NAME("getDataspace");
3564 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
3565 }
3566 if (err != OK || dataspace != mBufferInfo.mDataspace) {
3567 {
3568 ATRACE_NAME("setDataspace");
3569 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
3570 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
3571 }
3572
3573 // Some GPU drivers may cache gralloc metadata which means before we composite we need
3574 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
3575 // compatible with old vendors, with a ticking clock.
3576 static const int32_t kVendorVersion =
3577 base::GetIntProperty("ro.vndk.version", __ANDROID_API_FUTURE__);
3578 if (const auto format =
3579 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
3580 mBufferInfo.mBuffer->getPixelFormat());
3581 err == OK && kVendorVersion < __ANDROID_API_U__ &&
3582 (format ==
3583 aidl::android::hardware::graphics::common::PixelFormat::
3584 IMPLEMENTATION_DEFINED ||
3585 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
3586 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
3587 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
3588 mBufferInfo.mBuffer->remapBuffer();
3589 }
3590 }
3591 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003592 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003593 mFlinger->mHdrLayerInfoChanged = true;
3594 }
Sally Qi963049b2023-03-23 14:06:21 -07003595 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3596 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05003597 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003598 }
3599 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3600 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3601 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3602 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3603 mBufferInfo.mApi = mDrawingState.api;
3604 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003605}
3606
3607Rect Layer::computeBufferCrop(const State& s) {
3608 if (s.buffer && !s.bufferCrop.isEmpty()) {
3609 Rect bufferCrop;
3610 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3611 return bufferCrop;
3612 } else if (s.buffer) {
3613 return s.buffer->getBounds();
3614 } else {
3615 return s.bufferCrop;
3616 }
3617}
3618
Vishnu Nairde177252023-04-21 12:44:10 -07003619sp<Layer> Layer::createClone(uint32_t mirrorRootId) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003620 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3621 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003622 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Vishnu Nairde177252023-04-21 12:44:10 -07003623 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this), mirrorRootId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003624 return layer;
3625}
3626
Patrick Williamsbb25f802022-08-30 23:02:34 +00003627void Layer::decrementPendingBufferCount() {
3628 int32_t pendingBuffers = --mPendingBufferTransactions;
3629 tracePendingBufferCount(pendingBuffers);
3630}
3631
3632void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3633 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3634}
3635
3636/*
3637 * We don't want to send the layer's transform to input, but rather the
3638 * parent's transform. This is because Layer's transform is
3639 * information about how the buffer is placed on screen. The parent's
3640 * transform makes more sense to send since it's information about how the
3641 * layer is placed on screen. This transform is used by input to determine
3642 * how to go from screen space back to window space.
3643 */
3644ui::Transform Layer::getInputTransform() const {
3645 if (!hasBufferOrSidebandStream()) {
3646 return getTransform();
3647 }
3648 sp<Layer> parent = mDrawingParent.promote();
3649 if (parent == nullptr) {
3650 return ui::Transform();
3651 }
3652
3653 return parent->getTransform();
3654}
3655
3656/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003657 * Returns the bounds used to fill the input frame and the touchable region.
3658 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003659 * Similar to getInputTransform, we need to update the bounds to include the transform.
3660 * This is because bounds don't include the buffer transform, where the input assumes
3661 * that's already included.
3662 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003663std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3664 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3665 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3666 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3667 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3668 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003669 }
3670
Vishnu Nairfed7c122023-03-18 01:54:43 +00003671 bool inputBoundsValid = croppedBufferSize.isValid();
3672 if (!inputBoundsValid) {
3673 /**
3674 * Input bounds are based on the layer crop or buffer size. But if we are using
3675 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3676 * we can use the parent bounds as the input bounds if the layer does not have buffer
3677 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3678 * use the parent bounds. A layer without a buffer can get input. So when a window is
3679 * initially added, its touchable region can fill its parent layer bounds and that can
3680 * have negative consequences.
3681 */
3682 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003683 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003684
3685 // Clamp surface inset to the input bounds.
3686 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3687 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3688 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3689
3690 // Apply the insets to the input bounds.
3691 inputBounds.left += xSurfaceInset;
3692 inputBounds.top += ySurfaceInset;
3693 inputBounds.right -= xSurfaceInset;
3694 inputBounds.bottom -= ySurfaceInset;
3695
3696 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003697}
3698
Ady Abraham005398b2023-06-05 13:59:41 -07003699bool Layer::isSimpleBufferUpdate(const layer_state_t& s) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003700 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3701
3702 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3703 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3704 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3705 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3706 layer_state_t::eReparent;
3707
Patrick Williamsbb25f802022-08-30 23:02:34 +00003708 if ((s.what & requiredFlags) != requiredFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003709 ATRACE_FORMAT_INSTANT("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3710 (s.what | requiredFlags) & ~s.what);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003711 return false;
3712 }
3713
3714 if (s.what & deniedFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003715 ATRACE_FORMAT_INSTANT("%s: false [has denied flags 0x%" PRIx64 "]", __func__,
3716 s.what & deniedFlags);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003717 return false;
3718 }
3719
Patrick Williamsbb25f802022-08-30 23:02:34 +00003720 if (s.what & layer_state_t::ePositionChanged) {
3721 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
Ady Abraham005398b2023-06-05 13:59:41 -07003722 ATRACE_FORMAT_INSTANT("%s: false [ePositionChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003723 return false;
3724 }
3725 }
3726
3727 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003728 if (mDrawingState.color.a != s.color.a) {
Ady Abraham005398b2023-06-05 13:59:41 -07003729 ATRACE_FORMAT_INSTANT("%s: false [eAlphaChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003730 return false;
3731 }
3732 }
3733
3734 if (s.what & layer_state_t::eColorTransformChanged) {
3735 if (mDrawingState.colorTransform != s.colorTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003736 ATRACE_FORMAT_INSTANT("%s: false [eColorTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003737 return false;
3738 }
3739 }
3740
3741 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003742 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Ady Abraham005398b2023-06-05 13:59:41 -07003743 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundColorChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003744 return false;
3745 }
3746 }
3747
3748 if (s.what & layer_state_t::eMatrixChanged) {
3749 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3750 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3751 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3752 mRequestedTransform.dsdy() != s.matrix.dsdy) {
Ady Abraham005398b2023-06-05 13:59:41 -07003753 ATRACE_FORMAT_INSTANT("%s: false [eMatrixChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003754 return false;
3755 }
3756 }
3757
3758 if (s.what & layer_state_t::eCornerRadiusChanged) {
3759 if (mDrawingState.cornerRadius != s.cornerRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003760 ATRACE_FORMAT_INSTANT("%s: false [eCornerRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003761 return false;
3762 }
3763 }
3764
3765 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3766 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
Ady Abraham005398b2023-06-05 13:59:41 -07003767 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003768 return false;
3769 }
3770 }
3771
Vishnu Nairbbceb462022-10-10 04:52:13 +00003772 if (s.what & layer_state_t::eBufferTransformChanged) {
3773 if (mDrawingState.bufferTransform != s.bufferTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003774 ATRACE_FORMAT_INSTANT("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003775 return false;
3776 }
3777 }
3778
3779 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3780 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
Ady Abraham005398b2023-06-05 13:59:41 -07003781 ATRACE_FORMAT_INSTANT("%s: false [eTransformToDisplayInverseChanged changed]",
3782 __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003783 return false;
3784 }
3785 }
3786
3787 if (s.what & layer_state_t::eCropChanged) {
3788 if (mDrawingState.crop != s.crop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003789 ATRACE_FORMAT_INSTANT("%s: false [eCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003790 return false;
3791 }
3792 }
3793
3794 if (s.what & layer_state_t::eDataspaceChanged) {
3795 if (mDrawingState.dataspace != s.dataspace) {
Ady Abraham005398b2023-06-05 13:59:41 -07003796 ATRACE_FORMAT_INSTANT("%s: false [eDataspaceChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003797 return false;
3798 }
3799 }
3800
3801 if (s.what & layer_state_t::eHdrMetadataChanged) {
3802 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
Ady Abraham005398b2023-06-05 13:59:41 -07003803 ATRACE_FORMAT_INSTANT("%s: false [eHdrMetadataChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003804 return false;
3805 }
3806 }
3807
3808 if (s.what & layer_state_t::eSidebandStreamChanged) {
3809 if (mDrawingState.sidebandStream != s.sidebandStream) {
Ady Abraham005398b2023-06-05 13:59:41 -07003810 ATRACE_FORMAT_INSTANT("%s: false [eSidebandStreamChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003811 return false;
3812 }
3813 }
3814
3815 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3816 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
Ady Abraham005398b2023-06-05 13:59:41 -07003817 ATRACE_FORMAT_INSTANT("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003818 return false;
3819 }
3820 }
3821
3822 if (s.what & layer_state_t::eShadowRadiusChanged) {
3823 if (mDrawingState.shadowRadius != s.shadowRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003824 ATRACE_FORMAT_INSTANT("%s: false [eShadowRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003825 return false;
3826 }
3827 }
3828
3829 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3830 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
Ady Abraham005398b2023-06-05 13:59:41 -07003831 ATRACE_FORMAT_INSTANT("%s: false [eFixedTransformHintChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003832 return false;
3833 }
3834 }
3835
3836 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3837 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
Ady Abraham005398b2023-06-05 13:59:41 -07003838 ATRACE_FORMAT_INSTANT("%s: false [eTrustedOverlayChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003839 return false;
3840 }
3841 }
3842
3843 if (s.what & layer_state_t::eStretchChanged) {
3844 StretchEffect temp = s.stretchEffect;
3845 temp.sanitize();
3846 if (mDrawingState.stretchEffect != temp) {
Ady Abraham005398b2023-06-05 13:59:41 -07003847 ATRACE_FORMAT_INSTANT("%s: false [eStretchChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003848 return false;
3849 }
3850 }
3851
3852 if (s.what & layer_state_t::eBufferCropChanged) {
3853 if (mDrawingState.bufferCrop != s.bufferCrop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003854 ATRACE_FORMAT_INSTANT("%s: false [eBufferCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003855 return false;
3856 }
3857 }
3858
3859 if (s.what & layer_state_t::eDestinationFrameChanged) {
3860 if (mDrawingState.destinationFrame != s.destinationFrame) {
Ady Abraham005398b2023-06-05 13:59:41 -07003861 ATRACE_FORMAT_INSTANT("%s: false [eDestinationFrameChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003862 return false;
3863 }
3864 }
3865
3866 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3867 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
Ady Abraham005398b2023-06-05 13:59:41 -07003868 ATRACE_FORMAT_INSTANT("%s: false [eDimmingEnabledChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003869 return false;
3870 }
3871 }
3872
John Reck68796592023-01-25 13:47:12 -05003873 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07003874 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
3875 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
Ady Abraham005398b2023-06-05 13:59:41 -07003876 ATRACE_FORMAT_INSTANT("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05003877 return false;
3878 }
3879 }
3880
Patrick Williamsbb25f802022-08-30 23:02:34 +00003881 return true;
3882}
3883
3884bool Layer::isHdrY410() const {
3885 // pixel format is HDR Y410 masquerading as RGBA_1010102
3886 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3887 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3888 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3889}
3890
Vishnu Naire14c6b32022-08-06 04:20:15 +00003891sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003892 // 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 +00003893 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003894}
3895
Vishnu Naire14c6b32022-08-06 04:20:15 +00003896const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003897 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003898}
3899
Vishnu Naire14c6b32022-08-06 04:20:15 +00003900LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003901 return mSnapshot.get();
3902}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003903
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003904std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3905 return std::move(mSnapshot);
3906}
3907
3908void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3909 mSnapshot = std::move(snapshot);
3910}
3911
Patrick Williamsbb25f802022-08-30 23:02:34 +00003912const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003913 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003914}
3915
Patrick Williams7584c6a2022-10-29 02:10:58 +00003916sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003917 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003918 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3919 return result;
3920}
3921
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003922sp<LayerFE> Layer::getCompositionEngineLayerFE(
3923 const frontend::LayerHierarchy::TraversalPath& path) {
3924 for (auto& [p, layerFE] : mLayerFEs) {
3925 if (p == path) {
3926 return layerFE;
3927 }
3928 }
3929 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3930 mLayerFEs.emplace_back(path, layerFE);
3931 return layerFE;
3932}
3933
Patrick Williamsbb25f802022-08-30 23:02:34 +00003934void Layer::useSurfaceDamage() {
3935 if (mFlinger->mForceFullDamage) {
3936 surfaceDamageRegion = Region::INVALID_REGION;
3937 } else {
3938 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3939 }
3940}
3941
3942void Layer::useEmptyDamage() {
3943 surfaceDamageRegion.clear();
3944}
3945
3946bool Layer::isOpaque(const Layer::State& s) const {
3947 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3948 // layer's opaque flag.
3949 if (!hasSomethingToDraw()) {
3950 return false;
3951 }
3952
3953 // if the layer has the opaque flag, then we're always opaque
3954 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3955 return true;
3956 }
3957
3958 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003959 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003960 return true;
3961 }
3962
3963 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3964 return fillsColor() && getAlpha() == 1.0_hf;
3965}
3966
3967bool Layer::canReceiveInput() const {
3968 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3969}
3970
3971bool Layer::isVisible() const {
3972 if (!hasSomethingToDraw()) {
3973 return false;
3974 }
3975
3976 if (isHiddenByPolicy()) {
3977 return false;
3978 }
3979
3980 return getAlpha() > 0.0f || hasBlur();
3981}
3982
3983void Layer::onPostComposition(const DisplayDevice* display,
3984 const std::shared_ptr<FenceTime>& glDoneFence,
3985 const std::shared_ptr<FenceTime>& presentFence,
3986 const CompositorTiming& compositorTiming) {
3987 // mFrameLatencyNeeded is true when a new frame was latched for the
3988 // composition.
3989 if (!mBufferInfo.mFrameLatencyNeeded) return;
3990
3991 for (const auto& handle : mDrawingState.callbackHandles) {
3992 handle->gpuCompositionDoneFence = glDoneFence;
3993 handle->compositorTiming = compositorTiming;
3994 }
3995
3996 // Update mFrameTracker.
3997 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3998 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3999
4000 const int32_t layerId = getSequence();
4001 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
4002
4003 const auto outputLayer = findOutputLayerForDisplay(display);
4004 if (outputLayer && outputLayer->requiresClientComposition()) {
4005 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
4006 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4007 clientCompositionTimestamp,
4008 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
4009 // Update the SurfaceFrames in the drawing state
4010 if (mDrawingState.bufferSurfaceFrameTX) {
4011 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
4012 }
4013 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
4014 surfaceFrame->setGpuComposition();
4015 }
4016 }
4017
4018 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
4019 if (frameReadyFence->isValid()) {
4020 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
4021 } else {
4022 // There was no fence for this frame, so assume that it was ready
4023 // to be presented at the desired present time.
4024 mFrameTracker.setFrameReadyTime(desiredPresentTime);
4025 }
4026
4027 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08004028 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004029 const std::optional<Fps> renderRate =
4030 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
4031
4032 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
4033 const auto gameMode = getGameMode();
4034
4035 if (presentFence->isValid()) {
4036 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
4037 refreshRate, renderRate, vote, gameMode);
4038 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4039 presentFence,
4040 FrameTracer::FrameEvent::PRESENT_FENCE);
4041 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
4042 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
4043 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04004044 // The HWC doesn't support present fences, so use the present timestamp instead.
4045 const nsecs_t presentTimestamp =
4046 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
4047
4048 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
4049 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
4050 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
4051
Patrick Williamsbb25f802022-08-30 23:02:34 +00004052 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
4053 refreshRate, renderRate, vote, gameMode);
4054 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
4055 mCurrentFrameNumber, actualPresentTime,
4056 FrameTracer::FrameEvent::PRESENT_FENCE);
4057 mFrameTracker.setActualPresentTime(actualPresentTime);
4058 }
4059 }
4060
4061 mFrameTracker.advanceFrame();
4062 mBufferInfo.mFrameLatencyNeeded = false;
4063}
4064
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004065bool Layer::willReleaseBufferOnLatch() const {
4066 return !mDrawingState.buffer && mBufferInfo.mBuffer;
4067}
4068
Patrick Williamsbb25f802022-08-30 23:02:34 +00004069bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00004070 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
4071 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
4072}
4073
4074bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004075 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
4076 getDrawingState().frameNumber);
4077
4078 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
4079
4080 if (refreshRequired) {
4081 return refreshRequired;
4082 }
4083
4084 // If the head buffer's acquire fence hasn't signaled yet, return and
4085 // try again later
4086 if (!fenceHasSignaled()) {
4087 ATRACE_NAME("!fenceHasSignaled()");
4088 mFlinger->onLayerUpdate();
4089 return false;
4090 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00004091 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004092
4093 // Capture the old state of the layer for comparisons later
4094 BufferInfo oldBufferInfo = mBufferInfo;
4095 const bool oldOpacity = isOpaque(mDrawingState);
4096 mPreviousFrameNumber = mCurrentFrameNumber;
4097 mCurrentFrameNumber = mDrawingState.frameNumber;
4098 gatherBufferInfo();
4099
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004100 if (mBufferInfo.mBuffer) {
4101 // We latched a buffer that will be presented soon. Clear the previously presented layer
4102 // stack list.
4103 mPreviouslyPresentedLayerStacks.clear();
4104 }
4105
4106 if (mDrawingState.buffer == nullptr) {
4107 const bool bufferReleased = oldBufferInfo.mBuffer != nullptr;
4108 recomputeVisibleRegions = bufferReleased;
4109 return bufferReleased;
4110 }
4111
Patrick Williamsbb25f802022-08-30 23:02:34 +00004112 if (oldBufferInfo.mBuffer == nullptr) {
4113 // the first time we receive a buffer, we need to trigger a
4114 // geometry invalidation.
4115 recomputeVisibleRegions = true;
4116 }
4117
4118 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
4119 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
4120 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
4121 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
4122 recomputeVisibleRegions = true;
4123 }
4124
4125 if (oldBufferInfo.mBuffer != nullptr) {
4126 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
4127 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
4128 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
4129 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
4130 recomputeVisibleRegions = true;
4131 }
4132 }
4133
4134 if (oldOpacity != isOpaque(mDrawingState)) {
4135 recomputeVisibleRegions = true;
4136 }
4137
4138 return true;
4139}
4140
4141bool Layer::hasReadyFrame() const {
4142 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4143}
4144
4145bool Layer::isProtected() const {
4146 return (mBufferInfo.mBuffer != nullptr) &&
4147 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4148}
4149
Patrick Williamsbb25f802022-08-30 23:02:34 +00004150void Layer::latchAndReleaseBuffer() {
4151 if (hasReadyFrame()) {
4152 bool ignored = false;
4153 latchBuffer(ignored, systemTime());
4154 }
4155 releasePendingBuffer(systemTime());
4156}
4157
4158PixelFormat Layer::getPixelFormat() const {
4159 return mBufferInfo.mPixelFormat;
4160}
4161
4162bool Layer::getTransformToDisplayInverse() const {
4163 return mBufferInfo.mTransformToDisplayInverse;
4164}
4165
4166Rect Layer::getBufferCrop() const {
4167 // this is the crop rectangle that applies to the buffer
4168 // itself (as opposed to the window)
4169 if (!mBufferInfo.mCrop.isEmpty()) {
4170 // if the buffer crop is defined, we use that
4171 return mBufferInfo.mCrop;
4172 } else if (mBufferInfo.mBuffer != nullptr) {
4173 // otherwise we use the whole buffer
4174 return mBufferInfo.mBuffer->getBounds();
4175 } else {
4176 // if we don't have a buffer yet, we use an empty/invalid crop
4177 return Rect();
4178 }
4179}
4180
4181uint32_t Layer::getBufferTransform() const {
4182 return mBufferInfo.mTransform;
4183}
4184
4185ui::Dataspace Layer::getDataSpace() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004186 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4187}
4188
4189ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4190 ui::Dataspace updatedDataspace = dataspace;
4191 // translate legacy dataspaces to modern dataspaces
4192 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00004193 // Treat unknown dataspaces as V0_sRGB
4194 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00004195 case ui::Dataspace::SRGB:
4196 updatedDataspace = ui::Dataspace::V0_SRGB;
4197 break;
4198 case ui::Dataspace::SRGB_LINEAR:
4199 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4200 break;
4201 case ui::Dataspace::JFIF:
4202 updatedDataspace = ui::Dataspace::V0_JFIF;
4203 break;
4204 case ui::Dataspace::BT601_625:
4205 updatedDataspace = ui::Dataspace::V0_BT601_625;
4206 break;
4207 case ui::Dataspace::BT601_525:
4208 updatedDataspace = ui::Dataspace::V0_BT601_525;
4209 break;
4210 case ui::Dataspace::BT709:
4211 updatedDataspace = ui::Dataspace::V0_BT709;
4212 break;
4213 default:
4214 break;
4215 }
4216
4217 return updatedDataspace;
4218}
4219
4220sp<GraphicBuffer> Layer::getBuffer() const {
4221 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4222}
4223
Vishnu Nairb76d99a2023-03-19 18:22:31 -07004224void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4225 mTransformHintLegacy = getFixedTransformHint();
4226 if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4227 mTransformHintLegacy = displayTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004228 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004229 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004230}
4231
4232const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4233 return mBufferInfo.mBuffer;
4234}
4235
4236bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004237 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004238 return false;
4239 }
4240
4241 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004242 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004243 mDrawingState.modified = true;
4244 setTransactionFlags(eTransactionNeeded);
4245 return true;
4246}
4247
4248bool Layer::fillsColor() const {
4249 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4250 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4251}
4252
4253bool Layer::hasBlur() const {
4254 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4255}
4256
Vishnu Nairba354102022-08-01 00:14:18 +00004257void Layer::updateSnapshot(bool updateGeometry) {
4258 if (!getCompositionEngineLayerFE()) {
4259 return;
4260 }
4261
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004262 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004263 if (updateGeometry) {
4264 prepareBasicGeometryCompositionState();
4265 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004266 snapshot->roundedCorner = getRoundedCornerState();
4267 snapshot->stretchEffect = getStretchEffect();
4268 snapshot->transformedBounds = mScreenBounds;
4269 if (mEffectiveShadowRadius > 0.f) {
4270 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4271
4272 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4273 // it if transparent regions are present. This may not be necessary since shadows are
4274 // typically cast by layers without transparent regions.
4275 snapshot->shadowSettings.boundaries = mBounds;
4276
4277 const float casterAlpha = snapshot->alpha;
4278 const bool casterIsOpaque =
4279 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4280
4281 // If the casting layer is translucent, we need to fill in the shadow underneath the
4282 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4283 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4284 snapshot->shadowSettings.ambientColor *= casterAlpha;
4285 snapshot->shadowSettings.spotColor *= casterAlpha;
4286 }
4287 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004288 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004289 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004290 snapshot->layerOpaqueFlagSet =
4291 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004292 snapshot->isHdrY410 = isHdrY410();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004293 sp<Layer> p = mDrawingParent.promote();
4294 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004295 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004296 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004297 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004298 }
4299 snapshot->bufferSize = getBufferSize(mDrawingState);
4300 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004301 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004302 preparePerFrameCompositionState();
4303}
4304
Vishnu Naire14c6b32022-08-06 04:20:15 +00004305void Layer::updateChildrenSnapshots(bool updateGeometry) {
4306 for (const sp<Layer>& child : mDrawingChildren) {
4307 child->updateSnapshot(updateGeometry);
4308 child->updateChildrenSnapshots(updateGeometry);
4309 }
4310}
4311
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004312void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4313 mSnapshot->layerMetadata = parentMetadata;
4314 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4315 for (const sp<Layer>& child : mDrawingChildren) {
4316 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4317 }
4318}
4319
4320void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4321 std::unordered_set<Layer*>& visited) {
4322 if (visited.find(this) != visited.end()) {
4323 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4324 return;
4325 }
4326 visited.insert(this);
4327
4328 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4329
4330 if (mDrawingState.zOrderRelatives.empty()) {
4331 return;
4332 }
4333 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4334 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4335 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4336 sp<Layer> relative = weakRelative.promote();
4337 if (!relative) {
4338 continue;
4339 }
4340 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4341 }
4342}
4343
Chavi Weingarten328a8312023-01-26 21:17:52 +00004344bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004345 TrustedPresentationListener const& listener) {
4346 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4347 mTrustedPresentationListener = listener;
4348 mTrustedPresentationThresholds = thresholds;
4349 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4350 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4351 mFlinger->mNumTrustedPresentationListeners++;
4352 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4353 mFlinger->mNumTrustedPresentationListeners--;
4354 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004355
4356 // Reset trusted presentation states to ensure we start the time again.
4357 mEnteredTrustedPresentationStateTime = -1;
4358 mLastReportedTrustedPresentationState = false;
4359 mLastComputedTrustedPresentationState = false;
4360
4361 // If there's a new trusted presentation listener, the code needs to go through the composite
4362 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4363 // we're already in the requested state.
4364 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004365}
4366
Vishnu Naira156f482023-02-22 00:23:38 +00004367void Layer::updateLastLatchTime(nsecs_t latchTime) {
4368 mLastLatchTime = latchTime;
4369}
4370
Mathias Agopian13127d82013-03-05 17:47:11 -08004371// ---------------------------------------------------------------------------
4372
Marin Shalamanov46084422020-10-13 12:33:42 +02004373std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004374 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4375 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004376}
4377
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004378} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004379
4380#if defined(__gl_h_)
4381#error "don't include gl/gl.h in this file"
4382#endif
4383
4384#if defined(__gl2_h_)
4385#error "don't include gl2/gl2.h in this file"
4386#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004387
4388// TODO(b/129481165): remove the #pragma below and fix conversion issues
4389#pragma clang diagnostic pop // ignored "-Wconversion"