blob: b919cc271622b5188dcb46fc37afc5eb6d7526d0 [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"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080079#include "TimeStats/TimeStats.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070080#include "TunnelModeEnabledReporter.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070081
David Sodman41fdfc92017-11-06 16:09:56 -080082#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000083#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085namespace android {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010086namespace {
87constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000088
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000089const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000090
Patrick Williamsbb25f802022-08-30 23:02:34 +000091bool assignTransform(ui::Transform* dst, ui::Transform& from) {
92 if (*dst == from) {
93 return false;
94 }
95 *dst = from;
96 return true;
97}
98
99TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
100 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
101 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
102 const auto frameRateCompatibility = [frameRate] {
103 switch (frameRate.type) {
104 case Layer::FrameRateCompatibility::Default:
105 return FrameRateCompatibility::Default;
106 case Layer::FrameRateCompatibility::ExactOrMultiple:
107 return FrameRateCompatibility::ExactOrMultiple;
108 default:
109 return FrameRateCompatibility::Undefined;
110 }
111 }();
112
113 const auto seamlessness = [frameRate] {
114 switch (frameRate.seamlessness) {
115 case scheduler::Seamlessness::OnlySeamless:
116 return Seamlessness::ShouldBeSeamless;
117 case scheduler::Seamlessness::SeamedAndSeamless:
118 return Seamlessness::NotRequired;
119 default:
120 return Seamlessness::Undefined;
121 }
122 }();
123
124 return TimeStats::SetFrameRateVote{.frameRate = frameRate.rate.getValue(),
125 .frameRateCompatibility = frameRateCompatibility,
126 .seamlessness = seamlessness};
127}
128
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100129} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800130
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700131using namespace ftl::flag_operators;
132
Yiwei Zhang5434a782018-12-05 18:06:32 -0800133using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000134using frontend::LayerSnapshot;
135using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800136using gui::GameMode;
137using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500138using gui::WindowInfo;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800139
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700140using PresentState = frametimeline::SurfaceFrame::PresentState;
141
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700142Layer::Layer(const LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000143 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700144 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000145 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700146 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800147 mWindowType(static_cast<WindowInfo::Type>(
148 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000149 mLayerCreationFlags(args.flags),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000150 mBorderEnabled(false),
151 mTextureName(args.textureName),
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000152 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000153 ALOGV("Creating Layer %s", getDebugName());
154
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700155 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700156 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
157 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
158 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700159 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
160 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700161 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700162 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700163 mDrawingState.z = 0;
164 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700165 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700166 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700167 mDrawingState.transform.set(0, 0);
168 mDrawingState.frameNumber = 0;
Vishnu Nair63221212023-04-06 15:17:37 -0700169 mDrawingState.barrierFrameNumber = 0;
170 mDrawingState.producerId = 0;
171 mDrawingState.barrierProducerId = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700172 mDrawingState.bufferTransform = 0;
173 mDrawingState.transformToDisplayInverse = false;
174 mDrawingState.crop.makeInvalid();
175 mDrawingState.acquireFence = sp<Fence>::make(-1);
176 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
177 mDrawingState.dataspace = ui::Dataspace::UNKNOWN;
Vishnu Nairbc4ee5c2022-08-16 03:19:37 +0000178 mDrawingState.dataspaceRequested = false;
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;
214 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000215
216 mSnapshot->sequence = sequence;
217 mSnapshot->name = getDebugName();
218 mSnapshot->textureName = mTextureName;
219 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000220 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800221}
222
223void Layer::onFirstRef() {
224 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700225}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700226
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700227Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000228 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
229 "Layer destructor called off the main thread.");
230
Patrick Williamsbb25f802022-08-30 23:02:34 +0000231 // The original layer and the clone layer share the same texture and buffer. Therefore, only
232 // one of the layers, in this case the original layer, needs to handle the deletion. The
233 // original layer and the clone should be removed at the same time so there shouldn't be any
234 // issue with the clone layer trying to use the texture.
235 if (mBufferInfo.mBuffer != nullptr) {
236 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
237 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800238 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000239 }
240 if (!isClone()) {
241 // The original layer and the clone layer share the same texture. Therefore, only one of
242 // the layers, in this case the original layer, needs to handle the deletion. The original
243 // layer and the clone should be removed at the same time so there shouldn't be any issue
244 // with the clone layer trying to use the deleted texture.
245 mFlinger->deleteTextureAsync(mTextureName);
246 }
247 const int32_t layerId = getSequence();
248 mFlinger->mTimeStats->onDestroy(layerId);
249 mFlinger->mFrameTracer->onDestroy(layerId);
250
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000251 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700252 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700253
254 if (mDrawingState.sidebandStream != nullptr) {
255 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
256 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700257 if (mHadClonedChild) {
258 mFlinger->mNumClones--;
259 }
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
311 traverse(LayerVector::StateSet::Current, [&](Layer* layer) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700312 layer->removeFromCurrentState();
313 layer->removeRelativeZ(layersInTree);
chaviw68d4dab2020-06-08 15:07:32 -0700314 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700315}
316
chaviw61626f22018-11-15 16:26:27 -0800317void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700318 if (mRemovedFromDrawingState) {
319 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700320 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700321 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700322 }
chaviw61626f22018-11-15 16:26:27 -0800323
324 for (const auto& child : mCurrentChildren) {
325 child->addToCurrentState();
326 }
327}
328
Mathias Agopian13127d82013-03-05 17:47:11 -0800329// ---------------------------------------------------------------------------
330// set-up
331// ---------------------------------------------------------------------------
332
chaviw13fdc492017-06-27 12:40:18 -0700333bool Layer::getPremultipledAlpha() const {
334 return mPremultipliedAlpha;
335}
336
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700337sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800338 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700339 if (mGetHandleCalled) {
340 ALOGE("Get handle called twice" );
341 return nullptr;
342 }
343 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700344 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000345 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800346}
347
348// ---------------------------------------------------------------------------
349// h/w composer set-up
350// ---------------------------------------------------------------------------
351
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700352static Rect reduce(const Rect& win, const Region& exclude) {
353 if (CC_LIKELY(exclude.isEmpty())) {
354 return win;
355 }
356 if (exclude.isRect()) {
357 return win.reduce(exclude.getBounds());
358 }
359 return Region(win).subtract(exclude).getBounds();
360}
361
Dan Stoza80d61162017-12-20 15:57:52 -0800362static FloatRect reduce(const FloatRect& win, const Region& exclude) {
363 if (CC_LIKELY(exclude.isEmpty())) {
364 return win;
365 }
366 // Convert through Rect (by rounding) for lack of FloatRegion
367 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
368}
369
Vishnu Nair4351ad52019-02-11 14:13:02 -0800370Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800371 if (!reduceTransparentRegion) {
372 return Rect{mScreenBounds};
373 }
374
375 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800376 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800377 // Transform to screen space.
378 bounds = t.transform(bounds);
379 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700380}
381
Vishnu Nair4351ad52019-02-11 14:13:02 -0800382FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000383 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800384 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700385}
386
Vishnu Nairf0c28512019-02-08 12:40:28 -0800387FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
388 // Subtract the transparent region and snap to the bounds.
389 return reduce(mBounds, activeTransparentRegion);
390}
391
Chavi Weingarten076acac2023-01-19 17:20:43 +0000392// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000393void Layer::updateTrustedPresentationState(const DisplayDevice* display,
394 const frontend::LayerSnapshot* snapshot,
395 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000396 if (!hasTrustedPresentationListener()) {
397 return;
398 }
399 const bool lastState = mLastComputedTrustedPresentationState;
400 mLastComputedTrustedPresentationState = false;
401
402 if (!leaveState) {
403 const auto outputLayer = findOutputLayerForDisplay(display);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000404 if (outputLayer != nullptr) {
405 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
406 Region coveredRegion =
407 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
408 mLastComputedTrustedPresentationState =
409 computeTrustedPresentationState(snapshot->geomLayerBounds,
410 snapshot->sourceBounds(), coveredRegion,
411 snapshot->transformedBounds,
412 snapshot->alpha,
413 snapshot->geomLayerTransform,
414 mTrustedPresentationThresholds);
415 } else {
416 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
417 "TrustedPresentationState",
418 getDebugName());
419 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000420 }
421 }
422 const bool newState = mLastComputedTrustedPresentationState;
423 if (lastState && !newState) {
424 // We were in the trusted presentation state, but now we left it,
425 // emit the callback if needed
426 if (mLastReportedTrustedPresentationState) {
427 mLastReportedTrustedPresentationState = false;
428 mTrustedPresentationListener.invoke(false);
429 }
430 // Reset the timer
431 mEnteredTrustedPresentationStateTime = -1;
432 } else if (!lastState && newState) {
433 // We were not in the trusted presentation state, but we entered it, begin the timer
434 // and make sure this gets called at least once more!
435 mEnteredTrustedPresentationStateTime = time_in_ms;
436 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
437 }
438
439 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
440 if (!mLastReportedTrustedPresentationState && newState &&
441 (time_in_ms - mEnteredTrustedPresentationStateTime >
442 mTrustedPresentationThresholds.stabilityRequirementMs)) {
443 mLastReportedTrustedPresentationState = true;
444 mTrustedPresentationListener.invoke(true);
445 }
446}
447
448/**
449 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
450 * of how the parameters and thresholds are interpreted. The general spirit is
451 * to produce an upper bound on the amount of the buffer which was presented.
452 */
453bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
454 const Region& coveredRegion,
455 const FloatRect& screenBounds, float alpha,
456 const ui::Transform& effectiveTransform,
457 const TrustedPresentationThresholds& thresholds) {
458 if (alpha < thresholds.minAlpha) {
459 return false;
460 }
461 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
462 return false;
463 }
464 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
465 return false;
466 }
467
468 const float sx = effectiveTransform.dsdx();
469 const float sy = effectiveTransform.dsdy();
470 float fractionRendered = std::min(sx * sy, 1.0f);
471
472 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
473 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
474 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
475
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000476 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
477 // Compute the size of all the rects since they may be disconnected.
478 float coveredSize = 0;
479 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
480 float size = rect->width() * rect->height();
481 coveredSize += size;
482 }
483
484 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000485
486 if (fractionRendered < thresholds.minFractionRendered) {
487 return false;
488 }
489
490 return true;
491}
492
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700493void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
494 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800495 const State& s(getDrawingState());
496
497 // Calculate effective layer transform
498 mEffectiveTransform = parentTransform * getActiveTransform(s);
499
Garfield Tan2c1782c2022-02-16 15:25:05 -0800500 if (CC_UNLIKELY(!isTransformValid())) {
501 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
502 getDebugName());
503 return;
504 }
505
Vishnu Nair4351ad52019-02-11 14:13:02 -0800506 // Transform parent bounds to layer space
507 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
508
Vishnu Nairc652ff82019-03-15 12:48:54 -0700509 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800510 mSourceBounds = computeSourceBounds(parentBounds);
511
512 // Calculate bounds by croping diplay frame with layer crop and parent bounds
513 FloatRect bounds = mSourceBounds;
514 const Rect layerCrop = getCrop(s);
515 if (!layerCrop.isEmpty()) {
516 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
517 }
518 bounds = bounds.intersect(parentBounds);
519
520 mBounds = bounds;
521 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700522
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700523 // Use the layer's own shadow radius if set. Otherwise get the radius from
524 // parent.
525 if (s.shadowRadius > 0.f) {
526 mEffectiveShadowRadius = s.shadowRadius;
527 } else {
528 mEffectiveShadowRadius = parentShadowRadius;
529 }
530
531 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
532 // don't pass it to its children.
533 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
534
Vishnu Nair4351ad52019-02-11 14:13:02 -0800535 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700536 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800537 }
Vishnu Nairba354102022-08-01 00:14:18 +0000538
539 if (mPotentialCursor) {
540 prepareCursorCompositionState();
541 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800542}
543
Vishnu Nair60356342018-11-13 13:00:45 -0800544Rect Layer::getCroppedBufferSize(const State& s) const {
545 Rect size = getBufferSize(s);
546 Rect crop = getCrop(s);
547 if (!crop.isEmpty() && size.isValid()) {
548 size.intersect(crop, &size);
549 } else if (!crop.isEmpty()) {
550 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700551 }
Vishnu Nair60356342018-11-13 13:00:45 -0800552 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800553}
554
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700555void Layer::setupRoundedCornersCropCoordinates(Rect win,
556 const FloatRect& roundedCornersCrop) const {
557 // Translate win by the rounded corners rect coordinates, to have all values in
558 // layer coordinate space.
559 win.left -= roundedCornersCrop.left;
560 win.right -= roundedCornersCrop.left;
561 win.top -= roundedCornersCrop.top;
562 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700563}
564
Lloyd Piquede196652020-01-22 17:29:58 -0800565void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800566 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800567 const auto alpha = static_cast<float>(getAlpha());
568 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700569 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800570
571 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
572 if (!opaque || alpha != 1.0f) {
573 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
574 : Hwc2::IComposerClient::BlendMode::COVERAGE;
575 }
576
Alec Mourif4af03e2023-02-11 00:25:24 +0000577 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000578 auto* snapshot = editLayerSnapshot();
579 snapshot->outputFilter = getOutputFilter();
580 snapshot->isVisible = isVisible();
581 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
582 snapshot->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800583
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000584 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800585 contentDirty = false;
586
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000587 snapshot->geomLayerBounds = mBounds;
588 snapshot->geomLayerTransform = getTransform();
589 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
590 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000591 snapshot->localTransform = getActiveTransform(drawingState);
592 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000593 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
594 snapshot->alpha = alpha;
595 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
596 snapshot->blurRegions = drawingState.blurRegions;
597 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800598}
599
Lloyd Piquede196652020-01-22 17:29:58 -0800600void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800601 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000602 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700603
Alec Mourif4af03e2023-02-11 00:25:24 +0000604 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000605 snapshot->geomBufferSize = getBufferSize(drawingState);
606 snapshot->geomContentCrop = getBufferCrop();
607 snapshot->geomCrop = getCrop(drawingState);
608 snapshot->geomBufferTransform = getBufferTransform();
609 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
610 snapshot->geomUsesSourceCrop = usesSourceCrop();
611 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800612
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000613 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800614 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
615 for (const auto& [key, mandatory] : supportedMetadata) {
616 const auto& genericLayerMetadataCompatibilityMap =
617 mFlinger->getGenericLayerMetadataKeyMap();
618 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
619 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
620 continue;
621 }
622 const uint32_t id = compatIter->second;
623
624 auto it = drawingState.metadata.mMap.find(id);
625 if (it == std::end(drawingState.metadata.mMap)) {
626 continue;
627 }
628
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000629 snapshot->metadata.emplace(key,
630 compositionengine::GenericLayerMetadataEntry{mandatory,
631 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800632 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800633}
David Sodmanba340492018-08-05 21:51:33 -0700634
Lloyd Piquede196652020-01-22 17:29:58 -0800635void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800636 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000637 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000638 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800639
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000640 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800641
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000642 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
643 snapshot->dataspace = getDataSpace();
644 snapshot->colorTransform = getColorTransform();
645 snapshot->colorTransformIsIdentity = !hasColorTransform();
646 snapshot->surfaceDamage = surfaceDamageRegion;
647 snapshot->hasProtectedContent = isProtected();
648 snapshot->dimmingEnabled = isDimmingEnabled();
Sally Qi963049b2023-03-23 14:06:21 -0700649 snapshot->currentHdrSdrRatio = getCurrentHdrSdrRatio();
650 snapshot->desiredHdrSdrRatio = getDesiredHdrSdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000651 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800652
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700653 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700654
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000655 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800656
657 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400658 // Rounded corners no longer force client composition, since we may use a
659 // hole punch so that the layer will appear to have rounded corners.
660 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000661 snapshot->stretchEffect.hasEffect()) {
662 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800663 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700664 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000665 snapshot->blurRegions = drawingState.blurRegions;
666 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400667
668 // Layer framerate is used in caching decisions.
669 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
670 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000671 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000672
673 if (hasBufferOrSidebandStream()) {
674 preparePerFrameBufferCompositionState();
675 } else {
676 preparePerFrameEffectsCompositionState();
677 }
678}
679
680void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000681 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000682 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000683 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000684 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
685 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000686 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
687 return;
688 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000689 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000690 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800691 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
692 snapshot->compositionType =
693 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000694 } else {
695 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000696 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
697 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000698 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
699 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
700 }
701
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000702 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000703 snapshot->acquireFence = mBufferInfo.mFence;
704 snapshot->frameNumber = mBufferInfo.mFrameNumber;
705 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000706}
707
708void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000709 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000710 auto* snapshot = editLayerSnapshot();
711 snapshot->color = getColor();
712 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000713 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800714}
715
Lloyd Piquede196652020-01-22 17:29:58 -0800716void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800717 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000718 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000719 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800720
721 // Apply the layer's transform, followed by the display's global transform
722 // Here we're guaranteed that the layer's transform preserves rects
723 Rect win = getCroppedBufferSize(drawingState);
724 // Subtract the transparent region and snap to the bounds
725 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
726 Rect frame(getTransform().transform(bounds));
727
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000728 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800729}
730
Lloyd Piquea83776c2019-01-29 18:42:32 -0800731const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700732 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800733}
734
Mathias Agopian13127d82013-03-05 17:47:11 -0800735// ---------------------------------------------------------------------------
736// drawing...
737// ---------------------------------------------------------------------------
738
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500739aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
740 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700741 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800742 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500743 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800744 }
745 if (outputLayer->getState().hwc) {
746 return (*outputLayer->getState().hwc).hwcCompositionType;
747 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500748 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800749 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800750}
751
Mathias Agopian13127d82013-03-05 17:47:11 -0800752// ----------------------------------------------------------------------------
753// local state
754// ----------------------------------------------------------------------------
755
David Sodman41fdfc92017-11-06 16:09:56 -0800756bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800757 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700758 if (s.flags & layer_state_t::eLayerSecure) {
759 return true;
760 }
761
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000762 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700763 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700764}
765
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100766void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
767 std::vector<JankData>& jankData) {
768 if (mPendingJankClassifications.empty() ||
769 !mPendingJankClassifications.front()->getJankType()) {
770 return;
771 }
772
773 bool includeJankData = false;
774 for (const auto& handle : handles) {
775 for (const auto& cb : handle->callbackIds) {
776 if (cb.includeJankData) {
777 includeJankData = true;
778 break;
779 }
780 }
781
782 if (includeJankData) {
783 jankData.reserve(mPendingJankClassifications.size());
784 break;
785 }
786 }
787
788 while (!mPendingJankClassifications.empty() &&
789 mPendingJankClassifications.front()->getJankType()) {
790 if (includeJankData) {
791 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
792 mPendingJankClassifications.front();
793 jankData.emplace_back(
794 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
795 }
796 mPendingJankClassifications.pop_front();
797 }
798}
799
Mathias Agopian13127d82013-03-05 17:47:11 -0800800// ----------------------------------------------------------------------------
801// transaction
802// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800803
Vishnu Naira156f482023-02-22 00:23:38 +0000804uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700805 ATRACE_CALL();
806
Robert Carr0758e5d2021-03-11 22:15:04 -0800807 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700808 mDrawingStateModified = mDrawingState.modified;
809 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700810
Alec Mourib416efd2018-09-06 21:01:59 +0000811 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700812
Robert Carr6a160312021-05-17 12:08:20 -0700813 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800814 // invalidate and recompute the visible regions if needed
815 flags |= Layer::eVisibleRegion;
816 }
817
Robert Carr6a160312021-05-17 12:08:20 -0700818 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800819 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000820 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800821 flags |= eVisibleRegion;
822 this->contentDirty = true;
823
824 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700825 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800826 }
827
Arthur Hung9ed43392022-05-27 06:31:57 +0000828 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
829 mFlinger->mUpdateInputInfo = true;
830 }
831
Vishnu Naira156f482023-02-22 00:23:38 +0000832 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800833
Mathias Agopian13127d82013-03-05 17:47:11 -0800834 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800835}
836
Vishnu Naira156f482023-02-22 00:23:38 +0000837void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000838 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
839 // bufferSurfaceFrameTX will be presented in latchBuffer.
840 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
841 if (surfaceFrame->getPresentState() != PresentState::Presented) {
842 // With applyPendingStates, we could end up having presented surfaceframes from previous
843 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800844 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000845 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
846 }
847 }
Robert Carr6a160312021-05-17 12:08:20 -0700848 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700849}
850
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700851uint32_t Layer::clearTransactionFlags(uint32_t mask) {
852 const auto flags = mTransactionFlags & mask;
853 mTransactionFlags &= ~mask;
854 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800855}
856
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700857void Layer::setTransactionFlags(uint32_t mask) {
858 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800859}
860
Robert Carr1f0a16a2016-10-24 16:27:39 -0700861bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
862 ssize_t idx = mCurrentChildren.indexOf(childLayer);
863 if (idx < 0) {
864 return false;
865 }
866 if (childLayer->setLayer(z)) {
867 mCurrentChildren.removeAt(idx);
868 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800869 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700870 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800871 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700872}
873
Robert Carr503c7042017-09-27 15:06:08 -0700874bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
875 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
876 ssize_t idx = mCurrentChildren.indexOf(childLayer);
877 if (idx < 0) {
878 return false;
879 }
880 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
881 mCurrentChildren.removeAt(idx);
882 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800883 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700884 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800885 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700886}
887
Robert Carrae060832016-11-28 10:51:00 -0800888bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700889 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
890 mDrawingState.sequence++;
891 mDrawingState.z = z;
892 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700893
Robert Carra70e91c2021-06-11 13:59:52 -0700894 mFlinger->mSomeChildrenChanged = true;
895
Robert Carrdb66e622017-04-10 16:55:57 -0700896 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700897 if (mDrawingState.zOrderRelativeOf != nullptr) {
898 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700899 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700900 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700901 }
chaviw606e5cf2019-03-01 10:12:10 -0800902 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700903 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800904 setTransactionFlags(eTransactionNeeded);
905 return true;
906}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700907
Robert Carrdb66e622017-04-10 16:55:57 -0700908void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700909 mDrawingState.zOrderRelatives.remove(relative);
910 mDrawingState.sequence++;
911 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700912 setTransactionFlags(eTransactionNeeded);
913}
914
915void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700916 mDrawingState.zOrderRelatives.add(relative);
917 mDrawingState.modified = true;
918 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700919 setTransactionFlags(eTransactionNeeded);
920}
921
chaviw606e5cf2019-03-01 10:12:10 -0800922void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700923 mDrawingState.zOrderRelativeOf = relativeOf;
924 mDrawingState.sequence++;
925 mDrawingState.modified = true;
926 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700927
chaviw606e5cf2019-03-01 10:12:10 -0800928 setTransactionFlags(eTransactionNeeded);
929}
930
Robert Carr503d2bd2017-12-04 15:49:47 -0800931bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000932 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700933 if (relative == nullptr) {
934 return false;
935 }
936
Robert Carr6a160312021-05-17 12:08:20 -0700937 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
938 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800939 return false;
940 }
941
Robert Carr88b85e12022-03-21 15:47:35 -0700942 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
943 (relative->mDrawingState.zOrderRelativeOf == this)) {
944 ALOGE("Detected relative layer loop between %s and %s",
945 mName.c_str(), relative->mName.c_str());
946 ALOGE("Ignoring new call to set relative layer");
947 return false;
948 }
949
Robert Carra70e91c2021-06-11 13:59:52 -0700950 mFlinger->mSomeChildrenChanged = true;
951
Robert Carr6a160312021-05-17 12:08:20 -0700952 mDrawingState.sequence++;
953 mDrawingState.modified = true;
954 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700955
Robert Carr6a160312021-05-17 12:08:20 -0700956 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700957 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700958 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700959 }
chaviw606e5cf2019-03-01 10:12:10 -0800960 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700961 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700962
963 setTransactionFlags(eTransactionNeeded);
964
965 return true;
966}
967
Winson Chunga30f7c92021-06-29 15:42:56 -0700968bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
969 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
970 mDrawingState.isTrustedOverlay = isTrustedOverlay;
971 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000972 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700973 setTransactionFlags(eTransactionNeeded);
974 return true;
975}
976
977bool Layer::isTrustedOverlay() const {
978 if (getDrawingState().isTrustedOverlay) {
979 return true;
980 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000981 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700982 return (p != nullptr) && p->isTrustedOverlay();
983}
984
Dan Stoza9e56aa02015-11-02 13:00:03 -0800985bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700986 if (mDrawingState.color.a == alpha) return false;
987 mDrawingState.sequence++;
988 mDrawingState.color.a = alpha;
989 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800990 setTransactionFlags(eTransactionNeeded);
991 return true;
992}
chaviw13fdc492017-06-27 12:40:18 -0700993
Valerie Haudd0b7572019-01-29 14:59:27 -0800994bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700995 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700996 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800997 }
Robert Carr6a160312021-05-17 12:08:20 -0700998 mDrawingState.sequence++;
999 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -08001000 setTransactionFlags(eTransactionNeeded);
1001
Robert Carr6a160312021-05-17 12:08:20 -07001002 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001003 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001004 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001005 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001006 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08001007 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001008 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001009
Valerie Haudd0b7572019-01-29 14:59:27 -08001010 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001011 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001012 mFlinger->mLayersAdded = true;
1013 // set up SF to handle added color layer
1014 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -07001015 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001016 }
1017 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001018 } else if (mDrawingState.bgColorLayer && alpha == 0) {
1019 mDrawingState.bgColorLayer->reparent(nullptr);
1020 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001021 return true;
1022 }
1023
Robert Carr6a160312021-05-17 12:08:20 -07001024 mDrawingState.bgColorLayer->setColor(color);
1025 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1026 mDrawingState.bgColorLayer->setAlpha(alpha);
1027 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001028
chaviw13fdc492017-06-27 12:40:18 -07001029 return true;
1030}
1031
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001032bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001033 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001034
Robert Carr6a160312021-05-17 12:08:20 -07001035 mDrawingState.sequence++;
1036 mDrawingState.cornerRadius = cornerRadius;
1037 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001038 setTransactionFlags(eTransactionNeeded);
1039 return true;
1040}
1041
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001042bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001043 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001044 // If we start or stop drawing blur then the layer's visibility state may change so increment
1045 // the magic sequence number.
1046 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1047 mDrawingState.sequence++;
1048 }
Robert Carr6a160312021-05-17 12:08:20 -07001049 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1050 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001051 setTransactionFlags(eTransactionNeeded);
1052 return true;
1053}
Marissa Wall61c58622018-07-18 10:12:20 -07001054
Mathias Agopian13127d82013-03-05 17:47:11 -08001055bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001056 mDrawingState.sequence++;
1057 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001058 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001059 setTransactionFlags(eTransactionNeeded);
1060 return true;
1061}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001062
Lucas Dupinc3800b82020-10-02 16:24:48 -07001063bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001064 // If we start or stop drawing blur then the layer's visibility state may change so increment
1065 // the magic sequence number.
1066 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1067 mDrawingState.sequence++;
1068 }
Robert Carr6a160312021-05-17 12:08:20 -07001069 mDrawingState.blurRegions = blurRegions;
1070 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001071 setTransactionFlags(eTransactionNeeded);
1072 return true;
1073}
1074
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001075bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001076 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1077 if (mDrawingState.flags == newFlags) return false;
1078 mDrawingState.sequence++;
1079 mDrawingState.flags = newFlags;
1080 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001081 setTransactionFlags(eTransactionNeeded);
1082 return true;
1083}
Robert Carr99e27f02016-06-16 15:18:02 -07001084
chaviw25714502021-02-11 10:01:08 -08001085bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001086 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001087 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001088 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001089
Robert Carr6a160312021-05-17 12:08:20 -07001090 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001091 setTransactionFlags(eTransactionNeeded);
1092 return true;
1093}
Robert Carr8d5227b2017-03-16 15:41:03 -07001094
Evan Roskyef876c92019-01-25 17:46:06 -08001095bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001096 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1097 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001098 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001099 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001100}
1101
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001102bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001103 if (mDrawingState.layerStack == layerStack) return false;
1104 mDrawingState.sequence++;
1105 mDrawingState.layerStack = layerStack;
1106 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001107 setTransactionFlags(eTransactionNeeded);
1108 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001109}
1110
Peiyong Linc502cb72019-03-01 15:00:23 -08001111bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001112 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001113 return false;
1114 }
Robert Carr6a160312021-05-17 12:08:20 -07001115 mDrawingState.sequence++;
1116 mDrawingState.colorSpaceAgnostic = agnostic;
1117 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001118 setTransactionFlags(eTransactionNeeded);
1119 return true;
1120}
1121
Sally Qi81d95e62022-03-21 19:41:33 -07001122bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1123 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1124
1125 mDrawingState.sequence++;
1126 mDrawingState.dimmingEnabled = dimmingEnabled;
1127 mDrawingState.modified = true;
1128 setTransactionFlags(eTransactionNeeded);
1129 return true;
1130}
1131
Ana Krulecc84d09b2019-11-02 23:10:29 +01001132bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001133 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1134 mDrawingState.frameRateSelectionPriority = priority;
1135 mDrawingState.sequence++;
1136 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001137 setTransactionFlags(eTransactionNeeded);
1138 return true;
1139}
1140
1141int32_t Layer::getFrameRateSelectionPriority() const {
1142 // Check if layer has priority set.
1143 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1144 return mDrawingState.frameRateSelectionPriority;
1145 }
1146 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001147 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001148 if (parent != nullptr) {
1149 return parent->getFrameRateSelectionPriority();
1150 }
1151
1152 return Layer::PRIORITY_UNSET;
1153}
1154
Andy Labrada096227e2022-06-15 16:58:11 +00001155bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1156 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1157 mDrawingState.defaultFrameRateCompatibility = compatibility;
1158 mDrawingState.modified = true;
1159 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1160 setTransactionFlags(eTransactionNeeded);
1161 return true;
1162}
1163
1164scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1165 return mDrawingState.defaultFrameRateCompatibility;
1166}
1167
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001168bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1169 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1170};
1171
Vishnu Nair73908d12022-10-24 21:46:42 -07001172ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1173 bool useDrawing = state == LayerVector::StateSet::Drawing;
1174 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1175 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001176 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001177 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001178 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001179}
1180
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001181bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001182 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001183 return false;
1184 }
1185
Robert Carr6a160312021-05-17 12:08:20 -07001186 mDrawingState.sequence++;
1187 mDrawingState.shadowRadius = shadowRadius;
1188 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001189 setTransactionFlags(eTransactionNeeded);
1190 return true;
1191}
1192
Vishnu Nair6213bd92020-05-08 17:42:25 -07001193bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001194 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001195 return false;
1196 }
1197
Robert Carr6a160312021-05-17 12:08:20 -07001198 mDrawingState.sequence++;
1199 mDrawingState.fixedTransformHint = fixedTransformHint;
1200 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001201 setTransactionFlags(eTransactionNeeded);
1202 return true;
1203}
1204
John Reckcdb4ed72021-02-04 13:39:33 -05001205bool Layer::setStretchEffect(const StretchEffect& effect) {
1206 StretchEffect temp = effect;
1207 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001208 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001209 return false;
1210 }
Robert Carr6a160312021-05-17 12:08:20 -07001211 mDrawingState.sequence++;
1212 mDrawingState.stretchEffect = temp;
1213 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001214 setTransactionFlags(eTransactionNeeded);
1215 return true;
1216}
1217
John Reckc00c6692021-02-16 11:37:33 -05001218StretchEffect Layer::getStretchEffect() const {
1219 if (mDrawingState.stretchEffect.hasEffect()) {
1220 return mDrawingState.stretchEffect;
1221 }
1222
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001223 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001224 if (parent != nullptr) {
1225 auto effect = parent->getStretchEffect();
1226 if (effect.hasEffect()) {
1227 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1228 return effect;
1229 }
1230 }
1231 return StretchEffect{};
1232}
1233
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001234bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1235 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001236 return false;
1237 }
1238 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001239 mBorderWidth = width;
1240 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001241 return true;
1242}
1243
1244bool Layer::isBorderEnabled() {
1245 return mBorderEnabled;
1246}
1247
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001248float Layer::getBorderWidth() {
1249 return mBorderWidth;
1250}
1251
1252const half4& Layer::getBorderColor() {
1253 return mBorderColor;
1254}
1255
Ady Abrahama850c182021-08-04 13:04:37 -07001256bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1257 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1258 const auto frameRate = [&] {
1259 if (mDrawingState.frameRate.rate.isValid() ||
1260 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1261 return mDrawingState.frameRate;
1262 }
1263
1264 return parentFrameRate;
1265 }();
1266
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001267 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001268
1269 // The frame rate is propagated to the children
1270 bool childrenHaveFrameRate = false;
1271 for (const sp<Layer>& child : mCurrentChildren) {
1272 childrenHaveFrameRate |=
1273 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1274 }
1275
1276 // If we don't have a valid frame rate, but the children do, we set this
1277 // layer as NoVote to allow the children to control the refresh rate
1278 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1279 childrenHaveFrameRate) {
1280 *transactionNeeded |=
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001281 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001282 }
1283
1284 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1285 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001286 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001287 const auto layerVotedWithDefaultCompatibility =
1288 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1289 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1290 const auto layerVotedWithExactCompatibility =
1291 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1292 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1293 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1294}
1295
Ady Abraham60e42ea2020-03-09 19:17:31 -07001296void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001297 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001298 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001299 while (auto parent = layer->getParent()) {
1300 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001301 }
Ady Abrahama850c182021-08-04 13:04:37 -07001302 return layer;
1303 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001304
Ady Abraham60e42ea2020-03-09 19:17:31 -07001305 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001306 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001307
Ady Abrahama850c182021-08-04 13:04:37 -07001308 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001309 if (transactionNeeded) {
1310 mFlinger->setTransactionFlags(eTraversalNeeded);
1311 }
1312}
1313
Ady Abraham71c437d2020-01-31 15:56:57 -08001314bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001315 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001316 return false;
1317 }
1318
Robert Carr6a160312021-05-17 12:08:20 -07001319 mDrawingState.sequence++;
1320 mDrawingState.frameRate = frameRate;
1321 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001322
1323 updateTreeHasFrameRateVote();
1324
Steven Thomas3172e202020-01-06 19:25:30 -08001325 setTransactionFlags(eTransactionNeeded);
1326 return true;
1327}
1328
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001329void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1330 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001331 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001332
1333 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1334 // there are two transactions with the same token, the first one without a buffer and the
1335 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1336 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001337 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1338 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001339 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001340 mDrawingState.bufferSurfaceFrameTX = it->second;
1341 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1342 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1343 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001344 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001345 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001346 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1347 }
1348}
1349
1350void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1351 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001352 mDrawingState.frameTimelineInfo = info;
1353 mDrawingState.postTime = postTime;
1354 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001355 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001356
Robert Carr6a160312021-05-17 12:08:20 -07001357 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001358 bufferSurfaceFrameTX != nullptr) {
1359 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1360 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1361 // being used for BufferSurfaceFrame, don't create a new one.
1362 return;
1363 }
1364 }
1365 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1366 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1367 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001368 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1369 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001370 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001371 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001372 } else {
1373 if (it->second->getPresentState() == PresentState::Presented) {
1374 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1375 // have been from previous vsync.
1376 it->second = createSurfaceFrameForTransaction(info, postTime);
1377 }
1378 }
1379}
1380
1381void Layer::addSurfaceFrameDroppedForBuffer(
1382 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001383 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001384 surfaceFrame->setPresentState(PresentState::Dropped);
1385 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1386}
1387
1388void Layer::addSurfaceFramePresentedForBuffer(
1389 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1390 nsecs_t currentLatchTime) {
1391 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1392 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1393 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001394 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001395}
1396
1397std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1398 const FrameTimelineInfo& info, nsecs_t postTime) {
1399 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001400 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1401 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001402 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001403 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001404 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001405 // For Transactions, the post time is considered to be both queue and acquire fence time.
1406 surfaceFrame->setActualQueueTime(postTime);
1407 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001408 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1409 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001410 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001411 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001412 onSurfaceFrameCreated(surfaceFrame);
1413 return surfaceFrame;
1414}
1415
1416std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1417 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1418 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001419 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001420 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001421 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001422 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001423 // For buffers, acquire fence time will set during latch.
1424 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001425 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1426 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001427 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001428 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001429 onSurfaceFrameCreated(surfaceFrame);
1430 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001431}
1432
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001433bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001434 if (mDrawingState.frameRateForLayerTree == frameRate) {
1435 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001436 }
1437
Ady Abrahama850c182021-08-04 13:04:37 -07001438 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001439
Ady Abrahama850c182021-08-04 13:04:37 -07001440 // TODO(b/195668952): we probably don't need to dirty visible regions here
1441 // or even store frameRateForLayerTree in mDrawingState
1442 mDrawingState.sequence++;
1443 mDrawingState.modified = true;
1444 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001445
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001446 mFlinger->mScheduler
1447 ->recordLayerHistory(sequence, getLayerProps(), systemTime(),
1448 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1449 return true;
1450}
Ady Abrahama850c182021-08-04 13:04:37 -07001451
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001452bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps) {
1453 if (mDrawingState.frameRateForLayerTree == frameRate) {
1454 return false;
1455 }
1456
1457 mDrawingState.frameRateForLayerTree = frameRate;
1458 mFlinger->mScheduler
1459 ->recordLayerHistory(sequence, layerProps, systemTime(),
1460 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001461 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001462}
1463
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001464Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1465 return getDrawingState().frameRateForLayerTree;
1466}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001467
Robert Carr1f0a16a2016-10-24 16:27:39 -07001468bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001469 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001470 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001471 if (parent != nullptr && parent->isHiddenByPolicy()) {
1472 return true;
1473 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001474 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1475 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1476 if (zOrderRelativeOf != nullptr) {
1477 if (zOrderRelativeOf->isHiddenByPolicy()) {
1478 return true;
1479 }
1480 }
1481 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001482 if (CC_UNLIKELY(!isTransformValid())) {
1483 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1484 return true;
1485 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001486 return s.flags & layer_state_t::eLayerHidden;
1487}
1488
David Sodman41fdfc92017-11-06 16:09:56 -08001489uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001490 // TODO: should we do something special if mSecure is set?
1491 if (mProtectedByApp) {
1492 // need a hardware-protected path to external video sink
1493 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001494 }
Riley Andrews03414a12014-07-01 14:22:59 -07001495 if (mPotentialCursor) {
1496 usage |= GraphicBuffer::USAGE_CURSOR;
1497 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001498 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001499 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001500}
1501
Vishnu Nair71fcf912022-10-18 09:14:20 -07001502void Layer::skipReportingTransformHint() {
1503 mSkipReportingTransformHint = true;
1504}
1505
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001506void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1507 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1508 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001509 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001510
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001511 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001512}
1513
Mathias Agopian13127d82013-03-05 17:47:11 -08001514// ----------------------------------------------------------------------------
1515// debugging
1516// ----------------------------------------------------------------------------
1517
Marissa Wall61c58622018-07-18 10:12:20 -07001518// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001519gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001520 using namespace std::string_literals;
1521
Huihong Luo05539a12022-02-23 10:29:40 -08001522 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001523 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001524 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001525 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001526 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001527 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001528
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001529 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001530 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001531 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001532 info.mX = ds.transform.tx();
1533 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001534 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001535 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001536 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001537 info.mFlags = ds.flags;
1538 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001539 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001540 info.mMatrix[0][0] = ds.transform[0][0];
1541 info.mMatrix[0][1] = ds.transform[0][1];
1542 info.mMatrix[1][0] = ds.transform[1][0];
1543 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001544 {
chaviwd62d3062019-09-04 14:48:02 -07001545 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001546 if (buffer != 0) {
1547 info.mActiveBufferWidth = buffer->getWidth();
1548 info.mActiveBufferHeight = buffer->getHeight();
1549 info.mActiveBufferStride = buffer->getStride();
1550 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001551 } else {
1552 info.mActiveBufferWidth = 0;
1553 info.mActiveBufferHeight = 0;
1554 info.mActiveBufferStride = 0;
1555 info.mActiveBufferFormat = 0;
1556 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001557 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001558 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001559 info.mIsOpaque = isOpaque(ds);
1560 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001561 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001562 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001563}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001564
Yiwei Zhang5434a782018-12-05 18:06:32 -08001565void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001566 result.append(kDumpTableRowLength, '-');
1567 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001568 result.append(" Layer name\n");
1569 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001570 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001571 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001572 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001573 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001574 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001575 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1576 result.append(kDumpTableRowLength, '-');
1577 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001578}
1579
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001580void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1581 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001582 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001583 return;
1584 }
1585
Yiwei Zhang5434a782018-12-05 18:06:32 -08001586 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001587 if (mName.length() > 77) {
1588 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001589 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001590 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001591 shortened.append(mName, mName.length() - 36);
1592 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001593 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001594 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001595 }
1596
Yiwei Zhang5434a782018-12-05 18:06:32 -08001597 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001598
Alec Mourib416efd2018-09-06 21:01:59 +00001599 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001600 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001601
Chia-I Wu1e043612018-03-01 09:45:09 -08001602 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001603 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001604 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001605 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001606 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001607 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001608 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001609 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1610 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001611 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001612 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001613 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001614 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001615 const auto frameRate = getFrameRateForLayerTree();
1616 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1617 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001618 ftl::enum_string(frameRate.type).c_str(),
1619 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001620 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001621 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001622 }
Dan Stozae22aec72016-08-01 13:20:59 -07001623
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001624 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1625 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1626
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001627 result.append(kDumpTableRowLength, '-');
1628 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001629}
Dan Stozae22aec72016-08-01 13:20:59 -07001630
Yiwei Zhang5434a782018-12-05 18:06:32 -08001631void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001632 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001633}
1634
Svetoslavd85084b2014-03-20 10:28:31 -07001635void Layer::clearFrameStats() {
1636 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001637}
1638
Jamie Gennis6547ff42013-07-16 20:12:42 -07001639void Layer::logFrameStats() {
1640 mFrameTracker.logAndResetStats(mName);
1641}
1642
Svetoslavd85084b2014-03-20 10:28:31 -07001643void Layer::getFrameStats(FrameStats* outStats) const {
1644 mFrameTracker.getStats(outStats);
1645}
1646
Vishnu Nair76554eb2022-12-09 03:38:36 +00001647void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1648 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
1649 StringAppendF(&result, "Layer %s%s pid:%d uid:%d\n", getName().c_str(), hasBuffer.c_str(),
Vishnu Naircb8be502022-10-12 19:03:23 +00001650 mOwnerPid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001651}
1652
Brian Anderson5ea5e592016-12-01 16:54:33 -08001653void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001654 const int32_t layerId = getSequence();
1655 mFlinger->mTimeStats->onDestroy(layerId);
1656 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001657}
1658
Vishnu Nair787aa782023-03-17 13:46:46 -07001659size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001660 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001661 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001662 count += 1 + child->getChildrenCount();
1663 }
1664 return count;
1665}
1666
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001667void Layer::setGameModeForTree(GameMode gameMode) {
1668 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001669 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1670 gameMode =
1671 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001672 }
1673 setGameMode(gameMode);
1674 for (const sp<Layer>& child : mCurrentChildren) {
1675 child->setGameModeForTree(gameMode);
1676 }
1677}
1678
Robert Carr1f0a16a2016-10-24 16:27:39 -07001679void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001680 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001681 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001682
Robert Carr1f0a16a2016-10-24 16:27:39 -07001683 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001684 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001685 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001686 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001687}
1688
1689ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001690 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001691 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001692
Robert Carr1323c952019-01-28 18:13:27 -08001693 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001694 const auto removeResult = mCurrentChildren.remove(layer);
1695
1696 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001697 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001698 layer->updateTreeHasFrameRateVote();
1699
1700 return removeResult;
1701}
1702
Robert Carr15eae092018-03-23 13:43:53 -07001703void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001704 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001705 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001706 const float parentShadowRadius =
1707 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001708 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001709 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001710 }
1711}
1712
chaviwf1961f72017-09-18 16:41:07 -07001713bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001714 sp<Layer> newParent;
1715 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001716 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001717 if (newParent == nullptr) {
1718 ALOGE("Unable to promote Layer handle");
1719 return false;
1720 }
1721 if (newParent == this) {
1722 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1723 return false;
1724 }
1725 }
1726
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001727 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001728 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001729 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001730 }
1731
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001732 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001733 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001734 if (!newParent->isRemovedFromCurrentState()) {
1735 addToCurrentState();
1736 } else {
1737 onRemovedFromCurrentState();
1738 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001739 } else {
1740 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001741 }
1742
chaviw06178942017-07-27 10:25:59 -07001743 return true;
1744}
1745
Peiyong Lind3788632018-09-18 16:01:31 -07001746bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001747 static const mat4 identityMatrix = mat4();
1748
Robert Carr6a160312021-05-17 12:08:20 -07001749 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001750 return false;
1751 }
Robert Carr6a160312021-05-17 12:08:20 -07001752 ++mDrawingState.sequence;
1753 mDrawingState.colorTransform = matrix;
1754 mDrawingState.hasColorTransform = matrix != identityMatrix;
1755 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001756 setTransactionFlags(eTransactionNeeded);
1757 return true;
1758}
1759
chaviwf66724d2018-11-28 16:35:21 -08001760mat4 Layer::getColorTransform() const {
1761 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001762 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001763 colorTransform = parent->getColorTransform() * colorTransform;
1764 }
1765 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001766}
1767
1768bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001769 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001770 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001771 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1772 }
1773 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001774}
1775
Chia-I Wu11481472018-05-04 10:43:19 -07001776bool Layer::isLegacyDataSpace() const {
1777 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001778 return !(getDataSpace() &
1779 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1780 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001781}
1782
Robert Carr1f0a16a2016-10-24 16:27:39 -07001783void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001784 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001785}
1786
Robert Carr6a160312021-05-17 12:08:20 -07001787int32_t Layer::getZ(LayerVector::StateSet) const {
1788 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001789}
1790
Robert Carr1c5481e2019-07-01 14:42:27 -07001791bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001792 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001793 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001794 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001795}
1796
David Sodman41fdfc92017-11-06 16:09:56 -08001797__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001798 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001799 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1800 "makeTraversalList received invalid stateSet");
1801 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1802 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001803 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001804
Robert Carr29abff82017-12-04 13:51:20 -08001805 if (state.zOrderRelatives.size() == 0) {
1806 *outSkipRelativeZUsers = true;
1807 return children;
1808 }
1809
chaviwfd462612018-05-31 16:11:27 -07001810 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001811 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001812 sp<Layer> strongRelative = weakRelative.promote();
1813 if (strongRelative != nullptr) {
1814 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001815 }
1816 }
1817
Dan Stoza412903f2017-04-27 13:42:17 -07001818 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001819 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001820 continue;
1821 }
Robert Carrdb66e622017-04-10 16:55:57 -07001822 traverse.add(child);
1823 }
1824
1825 return traverse;
1826}
1827
Robert Carr1f0a16a2016-10-24 16:27:39 -07001828/**
Robert Carrdb66e622017-04-10 16:55:57 -07001829 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001830 */
Dan Stoza412903f2017-04-27 13:42:17 -07001831void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001832 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1833 // produce a new list for traversing, including our relatives, and not including our children
1834 // who are relatives of another surface. In the case that there are no relative Z,
1835 // makeTraversalList returns our children directly to avoid significant overhead.
1836 // However in this case we need to take the responsibility for filtering children which
1837 // are relatives of another surface here.
1838 bool skipRelativeZUsers = false;
1839 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001840
Robert Carr1f0a16a2016-10-24 16:27:39 -07001841 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001842 for (; i < list.size(); i++) {
1843 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001844 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1845 continue;
1846 }
1847
chaviw301b1d82019-11-06 13:15:09 -08001848 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001849 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001850 }
Dan Stoza412903f2017-04-27 13:42:17 -07001851 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001852 }
Robert Carr29abff82017-12-04 13:51:20 -08001853
Dan Stoza412903f2017-04-27 13:42:17 -07001854 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001855 for (; i < list.size(); i++) {
1856 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001857
Robert Carr29abff82017-12-04 13:51:20 -08001858 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1859 continue;
1860 }
Dan Stoza412903f2017-04-27 13:42:17 -07001861 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001862 }
1863}
1864
1865/**
Robert Carrdb66e622017-04-10 16:55:57 -07001866 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001867 */
Dan Stoza412903f2017-04-27 13:42:17 -07001868void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1869 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001870 // See traverseInZOrder for documentation.
1871 bool skipRelativeZUsers = false;
1872 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001873
Robert Carr1f0a16a2016-10-24 16:27:39 -07001874 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001875 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001876 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001877
1878 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1879 continue;
1880 }
1881
chaviw301b1d82019-11-06 13:15:09 -08001882 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001883 break;
1884 }
Dan Stoza412903f2017-04-27 13:42:17 -07001885 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001886 }
Dan Stoza412903f2017-04-27 13:42:17 -07001887 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001888 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001889 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001890
1891 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1892 continue;
1893 }
1894
Dan Stoza412903f2017-04-27 13:42:17 -07001895 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001896 }
1897}
1898
Edgar Arriaga844fa672020-01-16 14:21:42 -08001899void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1900 visitor(this);
1901 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001902 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001903 for (const sp<Layer>& child : children) {
1904 child->traverse(state, visitor);
1905 }
1906}
1907
Vishnu Nair787aa782023-03-17 13:46:46 -07001908void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
1909 for (const sp<Layer>& child : mDrawingChildren) {
1910 visitor(child.get());
1911 }
1912}
1913
chaviw4b129c22018-04-09 16:19:43 -07001914LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1915 const std::vector<Layer*>& layersInTree) {
1916 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1917 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001918 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1919 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001920 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001921
chaviwfd462612018-05-31 16:11:27 -07001922 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001923 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1924 sp<Layer> strongRelative = weakRelative.promote();
1925 // Only add relative layers that are also descendents of the top most parent of the tree.
1926 // If a relative layer is not a descendent, then it should be ignored.
1927 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1928 traverse.add(strongRelative);
1929 }
1930 }
1931
1932 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001933 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001934 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1935 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1936 // the child here since it won't be added later as a relative.
1937 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1938 childState.zOrderRelativeOf.promote().get())) {
1939 continue;
1940 }
1941 traverse.add(child);
1942 }
1943
1944 return traverse;
1945}
1946
1947void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1948 LayerVector::StateSet stateSet,
1949 const LayerVector::Visitor& visitor) {
1950 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001951
1952 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001953 for (; i < list.size(); i++) {
1954 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001955 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001956 break;
1957 }
chaviw4b129c22018-04-09 16:19:43 -07001958 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001959 }
chaviw4b129c22018-04-09 16:19:43 -07001960
chaviwa76b2712017-09-20 12:02:26 -07001961 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001962 for (; i < list.size(); i++) {
1963 const auto& relative = list[i];
1964 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001965 }
1966}
1967
chaviw4b129c22018-04-09 16:19:43 -07001968std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1969 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1970 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1971
1972 std::vector<Layer*> layersInTree = {this};
1973 for (size_t i = 0; i < children.size(); i++) {
1974 const auto& child = children[i];
1975 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1976 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1977 }
1978
1979 return layersInTree;
1980}
1981
1982void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1983 const LayerVector::Visitor& visitor) {
1984 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1985 std::sort(layersInTree.begin(), layersInTree.end());
1986 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1987}
1988
Peiyong Linefefaac2018-08-17 12:27:51 -07001989ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001990 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001991}
1992
Garfield Tan2c1782c2022-02-16 15:25:05 -08001993bool Layer::isTransformValid() const {
1994 float transformDet = getTransform().det();
1995 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1996}
1997
chaviw13fdc492017-06-27 12:40:18 -07001998half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001999 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002000
chaviw13fdc492017-06-27 12:40:18 -07002001 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2002 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002003}
Robert Carr6452f122017-03-21 10:41:29 -07002004
Vishnu Nair6213bd92020-05-08 17:42:25 -07002005ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002006 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002007 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2008 return fixedTransformHint;
2009 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002010 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002011 if (!p) return fixedTransformHint;
2012 return p->getFixedTransformHint();
2013}
2014
chaviw13fdc492017-06-27 12:40:18 -07002015half4 Layer::getColor() const {
2016 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002017 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002018}
Robert Carr6452f122017-03-21 10:41:29 -07002019
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002020int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002021 if (getDrawingState().backgroundBlurRadius == 0) {
2022 return 0;
2023 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002024
Vishnu Nair29810f72022-07-01 16:38:41 +00002025 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002026 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2027 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002028}
2029
Galia Peychevae0acf382021-04-12 21:22:34 +02002030const std::vector<BlurRegion> Layer::getBlurRegions() const {
2031 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002032 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002033 for (auto& region : regionsCopy) {
2034 region.alpha = region.alpha * layerAlpha;
2035 }
2036 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002037}
2038
Vishnu Naire14c6b32022-08-06 04:20:15 +00002039RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002040 // Get parent settings
2041 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002042 const auto& parent = mDrawingParent.promote();
2043 if (parent != nullptr) {
2044 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002045 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002046 ui::Transform t = getActiveTransform(getDrawingState());
2047 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002048 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002049 parentSettings.radius.x *= t.getScaleX();
2050 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002051 }
2052 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002053
2054 // Get layer settings
2055 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002056 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002057 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002058 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002059
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002060 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002061 // If the parent and the layer have rounded corner settings, use the parent settings if the
2062 // parent crop is entirely inside the layer crop.
2063 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2064 if (parentSettings.cropRect.left > layerCropRect.left &&
2065 parentSettings.cropRect.top > layerCropRect.top &&
2066 parentSettings.cropRect.right < layerCropRect.right &&
2067 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2068 return parentSettings;
2069 } else {
2070 return layerSettings;
2071 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002072 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002073 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002074 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002075 return parentSettings;
2076 }
2077 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002078}
2079
Robert Carr88b85e12022-03-21 15:47:35 -07002080bool Layer::findInHierarchy(const sp<Layer>& l) {
2081 if (l == this) {
2082 return true;
2083 }
2084 for (auto& child : mDrawingChildren) {
2085 if (child->findInHierarchy(l)) {
2086 return true;
2087 }
2088 }
2089 return false;
2090}
2091
Robert Carr1f0a16a2016-10-24 16:27:39 -07002092void Layer::commitChildList() {
2093 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2094 const auto& child = mCurrentChildren[i];
2095 child->commitChildList();
2096 }
2097 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002098 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002099 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2100 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2101 if (zOrderRelativeOf == nullptr) return;
2102 if (findInHierarchy(zOrderRelativeOf)) {
2103 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2104 zOrderRelativeOf->mName.c_str());
2105 ALOGE("Severing rel Z loop, potentially dangerous");
2106 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002107 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002108 }
2109 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002110}
2111
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002112
chaviw3277faf2021-05-19 16:45:23 -05002113void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002114 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002115 mDrawingState.touchableRegionCrop =
2116 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002117 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002118 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002119 setTransactionFlags(eTransactionNeeded);
2120}
2121
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002122LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002123 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002124 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002125 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2126
Vishnu Nair00b90132021-11-05 14:03:40 -07002127 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002128 writeCompositionStateToProto(layerProto);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002129 }
2130
chaviw08f3cb22020-01-13 13:17:21 -08002131 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002132 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002133 }
chaviw6d89e2d2020-01-14 14:42:01 -08002134
2135 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002136}
2137
Vishnu Nairea6ff812023-02-27 17:41:39 +00002138void Layer::writeCompositionStateToProto(LayerProto* layerProto) {
2139 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2140
2141 // Only populate for the primary display.
2142 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
2143 const auto compositionType = getCompositionType(*display);
2144 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
2145 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2146 [&]() { return layerProto->mutable_visible_region(); });
2147 }
2148}
2149
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002150void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002151 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002152 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002153 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002154 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002155 [&]() { return layerInfo->mutable_active_buffer(); });
2156 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2157 layerInfo->mutable_buffer_transform());
2158 }
2159 layerInfo->set_invalidate(contentDirty);
2160 layerInfo->set_is_protected(isProtected());
2161 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2162 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002163 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002164 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002165 layerInfo->set_corner_radius(
2166 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002167 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2168 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2169 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2170 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2171 [&]() { return layerInfo->mutable_position(); });
2172 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002173 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2174 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002175
Vishnu Nair00b90132021-11-05 14:03:40 -07002176 if (hasColorTransform()) {
2177 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002178 }
2179
Vishnu Nair60db8c02020-04-02 11:55:16 -07002180 LayerProtoHelper::writeToProto(mSourceBounds,
2181 [&]() { return layerInfo->mutable_source_bounds(); });
2182 LayerProtoHelper::writeToProto(mScreenBounds,
2183 [&]() { return layerInfo->mutable_screen_bounds(); });
2184 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2185 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2186 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002187}
2188
2189void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002190 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002191 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2192 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002193 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002194
chaviw766c9c52021-02-10 17:36:47 -08002195 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002196
Vishnu Nair00b90132021-11-05 14:03:40 -07002197 layerInfo->set_id(sequence);
2198 layerInfo->set_name(getName().c_str());
2199 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002200
Vishnu Nair00b90132021-11-05 14:03:40 -07002201 for (const auto& child : children) {
2202 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002203 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002204
Vishnu Nair00b90132021-11-05 14:03:40 -07002205 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2206 sp<Layer> strongRelative = weakRelative.promote();
2207 if (strongRelative != nullptr) {
2208 layerInfo->add_relatives(strongRelative->sequence);
2209 }
2210 }
2211
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002212 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002213 [&]() { return layerInfo->mutable_transparent_region(); });
2214
2215 layerInfo->set_layer_stack(getLayerStack().id);
2216 layerInfo->set_z(state.z);
2217
2218 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2219 return layerInfo->mutable_requested_position();
2220 });
2221
Vishnu Nair00b90132021-11-05 14:03:40 -07002222 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2223
2224 layerInfo->set_is_opaque(isOpaque(state));
2225
2226 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2227 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2228 LayerProtoHelper::writeToProto(state.color,
2229 [&]() { return layerInfo->mutable_requested_color(); });
2230 layerInfo->set_flags(state.flags);
2231
2232 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2233 layerInfo->mutable_requested_transform());
2234
2235 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2236 if (parent != nullptr) {
2237 layerInfo->set_parent(parent->sequence);
2238 } else {
2239 layerInfo->set_parent(-1);
2240 }
2241
2242 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2243 if (zOrderRelativeOf != nullptr) {
2244 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2245 } else {
2246 layerInfo->set_z_order_relative_of(-1);
2247 }
2248
2249 layerInfo->set_is_relative_of(state.isRelativeOf);
2250
2251 layerInfo->set_owner_uid(mOwnerUid);
2252
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002253 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002254 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002255 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002256 info = fillInputInfo(
2257 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002258 } else {
2259 info = state.inputInfo;
2260 }
2261
2262 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002263 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002264 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002265
Vishnu Nair00b90132021-11-05 14:03:40 -07002266 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002267 auto protoMap = layerInfo->mutable_metadata();
2268 for (const auto& entry : state.metadata.mMap) {
2269 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2270 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002271 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002272
2273 LayerProtoHelper::writeToProto(state.destinationFrame,
2274 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002275}
2276
Robert Carr2e102c92018-10-23 12:11:15 -07002277bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002278 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002279}
2280
Prabir Pradhan33da9462022-06-14 14:55:57 +00002281// Applies the given transform to the region, while protecting against overflows caused by any
2282// offsets. If applying the offset in the transform to any of the Rects in the region would result
2283// in an overflow, they are not added to the output Region.
2284static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2285 const std::string& debugWindowName) {
2286 // Round the translation using the same rounding strategy used by ui::Transform.
2287 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2288 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2289
2290 ui::Transform transformWithoutOffset = t;
2291 transformWithoutOffset.set(0.f, 0.f);
2292
2293 const Region transformed = transformWithoutOffset.transform(r);
2294
2295 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2296 Region ret;
2297 for (const auto& rect : transformed) {
2298 Rect newRect;
2299 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2300 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2301 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2302 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2303 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2304 debugWindowName.c_str());
2305 continue;
2306 }
2307 ret.orSelf(newRect);
2308 }
2309 return ret;
2310}
2311
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002312void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002313 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2314 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002315 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002316 }
2317
Vishnu Nairfed7c122023-03-18 01:54:43 +00002318 const Rect roundedFrameInDisplay = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002319 info.frameLeft = roundedFrameInDisplay.left;
2320 info.frameTop = roundedFrameInDisplay.top;
2321 info.frameRight = roundedFrameInDisplay.right;
2322 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002323
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002324 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002325 inputToLayer.set(inputBounds.left, inputBounds.top);
2326 const ui::Transform layerToScreen = getInputTransform();
2327 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002328
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002329 // InputDispatcher expects a display-to-input transform.
2330 info.transform = inputToDisplay.inverse();
2331
2332 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002333 info.touchableRegion =
2334 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002335}
2336
chaviw3277faf2021-05-19 16:45:23 -05002337void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002338 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002339 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002340 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002341 }
2342 if (p != nullptr) {
2343 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2344 }
2345}
2346
Vishnu Naira066d902021-09-13 18:40:17 -07002347gui::DropInputMode Layer::getDropInputMode() const {
2348 gui::DropInputMode mode = mDrawingState.dropInputMode;
2349 if (mode == gui::DropInputMode::ALL) {
2350 return mode;
2351 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002352 sp<Layer> parent = mDrawingParent.promote();
2353 if (parent) {
2354 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002355 if (parentMode != gui::DropInputMode::NONE) {
2356 return parentMode;
2357 }
2358 }
2359 return mode;
2360}
2361
2362void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002363 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002364 return;
2365 }
2366
2367 // Check if we need to drop input unconditionally
2368 gui::DropInputMode dropInputMode = getDropInputMode();
2369 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002370 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002371 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2372 return;
2373 }
2374
2375 // Check if we need to check if the window is obscured by parent
2376 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2377 return;
2378 }
2379
2380 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002381 sp<Layer> parent = mDrawingParent.promote();
2382 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002383 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002384 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2385 static_cast<float>(getAlpha()));
2386 }
2387
2388 // Check if the parent has cropped the buffer
2389 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2390 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002391 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002392 return;
2393 }
2394
2395 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2396 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2397 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2398 // match then the layer has not been cropped by its parents.
2399 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2400 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2401
2402 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002403 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002404 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2405 getDebugName());
2406 } else {
2407 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2408 // input if the window is obscured. This check should be done in surfaceflinger but the
2409 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2410 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002411 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002412 }
2413}
2414
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002415WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002416 if (!hasInputInfo()) {
2417 mDrawingState.inputInfo.name = getName();
2418 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2419 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002420 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002421 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002422 }
2423
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002424 const ui::Transform& displayTransform =
2425 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2426
chaviw3277faf2021-05-19 16:45:23 -05002427 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002428 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002429 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002430
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002431 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002432
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002433 if (displayArgs.transform == nullptr) {
2434 // Do not let the window receive touches if it is not associated with a valid display
2435 // transform. We still allow the window to receive keys and prevent ANRs.
2436 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2437 }
2438
Robert Carr5dc426e2020-06-10 14:29:14 -07002439 // For compatibility reasons we let layers which can receive input
2440 // receive input before they have actually submitted a buffer. Because
2441 // of this we use canReceiveInput instead of isVisible to check the
2442 // policy-visibility, ignoring the buffer state. However for layers with
2443 // hasInputInfo()==false we can use the real visibility state.
2444 // We are just using these layers for occlusion detection in
2445 // InputDispatcher, and obviously if they aren't visible they can't occlude
2446 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002447 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2448 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2449
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002450 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002451 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002452 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002453
Vishnu Nair16a938f2021-09-24 07:14:54 -07002454 // If the window will be blacked out on a display because the display does not have the secure
2455 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002456 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002457 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002458 }
2459
Vishnu Nairfed7c122023-03-18 01:54:43 +00002460 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002461 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002462 Rect inputBoundsInDisplaySpace;
2463 if (!cropLayer) {
2464 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2465 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2466 } else {
2467 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2468 inputBoundsInDisplaySpace =
2469 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2470 }
2471 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002472 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002473 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2474 Rect inputBoundsInDisplaySpace =
2475 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2476 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002477 }
2478
Winson Chunga30f7c92021-06-29 15:42:56 -07002479 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2480 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002481 if (isTrustedOverlay()) {
2482 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2483 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002484
chaviwaf87b3e2019-10-01 16:59:28 -07002485 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2486 // touches from going outside the cloned area.
2487 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002488 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002489 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2490 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002491 info.touchableRegion = info.touchableRegion.intersect(rect);
2492 }
2493 }
2494
Robert Carr720e5062018-07-30 17:45:14 -07002495 return info;
2496}
2497
Vishnu Nairfed7c122023-03-18 01:54:43 +00002498Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2499 const ui::Transform& screenToDisplay) {
2500 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2501 // frame and transform used for the layer, which determines the bounds and the coordinate space
2502 // within which the layer will receive input.
2503
2504 // Coordinate space definitions:
2505 // - display: The display device's coordinate space. Correlates to pixels on the display.
2506 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2507 // - layer: The coordinate space of this layer.
2508 // - input: The coordinate space in which this layer will receive input events. This could be
2509 // different than layer space if a surfaceInset is used, which changes the origin
2510 // of the input space.
2511
2512 // Crop the input bounds to ensure it is within the parent's bounds.
2513 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2514 const ui::Transform layerToScreen = getInputTransform();
2515 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2516 return Rect{layerToDisplay.transform(croppedInputBounds)};
2517}
2518
chaviwaf87b3e2019-10-01 16:59:28 -07002519sp<Layer> Layer::getClonedRoot() {
2520 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002521 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002522 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002523 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002524 return nullptr;
2525 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002526 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002527}
2528
Robert Carredd13602020-04-13 17:24:34 -07002529bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002530 return mDrawingState.inputInfo.token != nullptr ||
2531 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002532}
2533
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002534compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002535 const DisplayDevice* display) const {
2536 if (!display) return nullptr;
Vishnu Naird47bcee2023-02-24 18:08:51 +00002537 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2538 return display->getCompositionDisplay()->getOutputLayerForLayer(
2539 getCompositionEngineLayerFE());
2540 }
2541 sp<LayerFE> layerFE;
2542 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2543 for (auto& [p, layer] : mLayerFEs) {
2544 if (p == path) {
2545 layerFE = layer;
2546 }
2547 }
2548
2549 if (!layerFE) return nullptr;
2550 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002551}
2552
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002553Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2554 const auto outputLayer = findOutputLayerForDisplay(display);
2555 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002556}
2557
chaviwb4c6e582019-08-16 14:35:07 -07002558void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002559 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002560 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002561 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2562 mPotentialCursor = clonedFrom->mPotentialCursor;
2563 mProtectedByApp = clonedFrom->mProtectedByApp;
2564 updateCloneBufferInfo();
2565}
2566
2567void Layer::updateCloneBufferInfo() {
2568 if (!isClone() || !isClonedFromAlive()) {
2569 return;
2570 }
2571
2572 sp<Layer> clonedFrom = getClonedFrom();
2573 mBufferInfo = clonedFrom->mBufferInfo;
2574 mSidebandStream = clonedFrom->mSidebandStream;
2575 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2576 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2577 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2578
2579 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2580 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2581 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2582 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2583 // the cloned drawingState again.
2584 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2585 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2586 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2587 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2588
2589 cloneDrawingState(clonedFrom.get());
2590
2591 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2592 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2593 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2594 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002595}
chaviw74b03172019-08-19 11:09:03 -07002596
2597void Layer::updateMirrorInfo() {
2598 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2599 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2600 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2601 // that case, we want to delete the reference to the clone since we want it to get
2602 // destroyed. The root, this layer, will still be around since the client can continue
2603 // to hold a reference, but no cloned layers will be displayed.
2604 mClonedChild = nullptr;
2605 return;
2606 }
2607
2608 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2609 // If the real layer exists and is in current state, add the clone as a child of the root.
2610 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2611 // copied to drawingState for the root layer. So the clonedChild is always removed from
2612 // drawingState and then needs to be added back each traversal.
2613 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2614 addChildToDrawing(mClonedChild);
2615 }
2616
2617 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002618 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002619 mClonedChild->updateClonedRelatives(clonedLayersMap);
2620}
2621
2622void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2623 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2624 // to the clone. If the real layer is no longer alive, continue traversing the children
2625 // since we may be able to pull out other children that are still alive.
2626 if (isClonedFromAlive()) {
2627 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002628 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002629 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002630 }
2631
2632 // The clone layer may have children in drawingState since they may have been created and
2633 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2634 // that already exist, since we can just re-use them.
2635 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2636 // not updated in the regular traversal. They are skipped since the root will lose the
2637 // reference to them when it copies its currentChildren to drawing.
2638 for (sp<Layer>& child : mDrawingChildren) {
2639 child->updateClonedDrawingState(clonedLayersMap);
2640 }
2641}
2642
2643void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2644 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2645 mDrawingChildren.clear();
2646
2647 if (!isClonedFromAlive()) {
2648 return;
2649 }
2650
2651 sp<Layer> clonedFrom = getClonedFrom();
2652 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2653 if (child == mirrorRoot) {
2654 // This is to avoid cyclical mirroring.
2655 continue;
2656 }
2657 sp<Layer> clonedChild = clonedLayersMap[child];
2658 if (clonedChild == nullptr) {
2659 clonedChild = child->createClone();
2660 clonedLayersMap[child] = clonedChild;
2661 }
2662 addChildToDrawing(clonedChild);
2663 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2664 }
2665}
2666
chaviwaf87b3e2019-10-01 16:59:28 -07002667void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2668 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2669 if (cropLayer != nullptr) {
2670 if (clonedLayersMap.count(cropLayer) == 0) {
2671 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2672 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002673 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002674 } else {
2675 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2676 mDrawingState.touchableRegionCrop = clonedCropLayer;
2677 }
2678 }
2679 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2680 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002681 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002682}
2683
2684void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002685 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002686 mDrawingState.zOrderRelatives.clear();
2687
2688 if (!isClonedFromAlive()) {
2689 return;
2690 }
2691
chaviwaf87b3e2019-10-01 16:59:28 -07002692 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002693 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002694 const sp<Layer>& relative = relativeWeak.promote();
2695 if (clonedLayersMap.count(relative) > 0) {
2696 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002697 mDrawingState.zOrderRelatives.add(clonedRelative);
2698 }
2699 }
2700
2701 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2702 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2703 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2704 // still traverse the children, but the layer with the missing relativeOf will not be shown
2705 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002706 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2707 if (clonedLayersMap.count(relativeOf) > 0) {
2708 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002709 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2710 }
2711
chaviwaf87b3e2019-10-01 16:59:28 -07002712 updateClonedInputInfo(clonedLayersMap);
2713
chaviw74b03172019-08-19 11:09:03 -07002714 for (sp<Layer>& child : mDrawingChildren) {
2715 child->updateClonedRelatives(clonedLayersMap);
2716 }
2717}
2718
2719void Layer::addChildToDrawing(const sp<Layer>& layer) {
2720 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002721 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002722}
2723
Steven Thomas62a4cf82020-01-31 12:04:03 -08002724Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2725 switch (compatibility) {
2726 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2727 return FrameRateCompatibility::Default;
2728 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2729 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002730 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2731 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002732 case ANATIVEWINDOW_FRAME_RATE_MIN:
2733 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002734 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2735 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002736 default:
2737 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2738 return FrameRateCompatibility::Default;
2739 }
2740}
2741
Marin Shalamanovc5986772021-03-16 16:09:49 +01002742scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2743 switch (strategy) {
2744 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2745 return Seamlessness::OnlySeamless;
2746 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2747 return Seamlessness::SeamedAndSeamless;
2748 default:
2749 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2750 return Seamlessness::Default;
2751 }
2752}
2753
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002754bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002755 const State& s(mDrawingState);
2756 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2757 return true;
2758 }
2759
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002760 sp<Layer> parent = mDrawingParent.promote();
2761 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002762}
2763
Robert Carr6a0382d2021-07-01 15:57:17 -07002764void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2765 mClonedChild = clonedChild;
2766 mHadClonedChild = true;
2767 mFlinger->mNumClones++;
2768}
2769
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002770bool Layer::setDropInputMode(gui::DropInputMode mode) {
2771 if (mDrawingState.dropInputMode == mode) {
2772 return false;
2773 }
2774 mDrawingState.dropInputMode = mode;
2775 return true;
2776}
2777
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002778void Layer::cloneDrawingState(const Layer* from) {
2779 mDrawingState = from->mDrawingState;
2780 // Skip callback info since they are not applicable for cloned layers.
2781 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002782 // TODO (b/238781169) currently broken for mirror layers because we do not
2783 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002784 mDrawingState.callbackHandles = {};
2785}
2786
Patrick Williamsbb25f802022-08-30 23:02:34 +00002787void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2788 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002789 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002790 if (!listener) {
2791 return;
2792 }
2793 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002794 uint32_t currentMaxAcquiredBufferCount =
2795 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002796 listener->onReleaseBuffer({buffer->getId(), framenumber},
2797 releaseFence ? releaseFence : Fence::NO_FENCE,
2798 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002799}
2800
2801void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2802 // If we are displayed on multiple displays in a single composition cycle then we would
2803 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2804 // For example we can only use it if all the displays are client comp, and we need
2805 // to merge all the client comp fences. We could do this, but for now we just
2806 // disable the optimization when a layer is composed on multiple displays.
2807 if (mClearClientCompositionFenceOnLayerDisplayed) {
2808 mLastClientCompositionFence = nullptr;
2809 } else {
2810 mClearClientCompositionFenceOnLayerDisplayed = true;
2811 }
2812
2813 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2814 // buffer that was presented on this layer. The first transaction that came in this frame that
2815 // replaced the previous buffer on this layer needs this release fence, because the fence will
2816 // let the client know when that previous buffer is removed from the screen.
2817 //
2818 // Every other transaction on this layer does not need a release fence because no other
2819 // Transactions that were set on this layer this frame are going to have their preceding buffer
2820 // removed from the display this frame.
2821 //
2822 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2823 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2824 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2825 // the previous buffer will be released this frame. The third transaction also contains a
2826 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2827 // transaction will now no longer be presented so it is released immediately and the third
2828 // transaction doesn't need a previous release fence.
2829 sp<CallbackHandle> ch;
2830 for (auto& handle : mDrawingState.callbackHandles) {
2831 if (handle->releasePreviousBuffer &&
2832 mDrawingState.releaseBufferEndpoint == handle->listener) {
2833 ch = handle;
2834 break;
2835 }
2836 }
2837
2838 // Prevent tracing the same release multiple times.
2839 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2840 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2841 }
2842
2843 if (ch != nullptr) {
2844 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2845 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2846 ch->name = mName;
2847 }
2848}
2849
2850void Layer::onSurfaceFrameCreated(
2851 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2852 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2853 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2854 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2855 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002856 if (hasBufferOrSidebandStreamInDrawing()) {
2857 // Only log for layers with a buffer, since we expect the jank data to be drained for
2858 // these, while there may be no jank listeners for bufferless layers.
2859 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2860 mName.c_str());
2861 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2862 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2863 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002864 mPendingJankClassifications.pop_front();
2865 }
2866 mPendingJankClassifications.emplace_back(surfaceFrame);
2867}
2868
2869void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2870 for (const auto& handle : mDrawingState.callbackHandles) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -07002871 if (mFlinger->mLayerLifecycleManagerEnabled) {
2872 handle->transformHint = mTransformHint;
2873 } else {
2874 handle->transformHint = mSkipReportingTransformHint
2875 ? std::nullopt
2876 : std::make_optional<uint32_t>(mTransformHintLegacy);
2877 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002878 handle->dequeueReadyTime = dequeueReadyTime;
2879 handle->currentMaxAcquiredBufferCount =
2880 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2881 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2882 handle->previousReleaseCallbackId.framenumber);
2883 }
2884
2885 for (auto& handle : mDrawingState.callbackHandles) {
2886 if (handle->releasePreviousBuffer &&
2887 mDrawingState.releaseBufferEndpoint == handle->listener) {
2888 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2889 break;
2890 }
2891 }
2892
2893 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002894 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002895 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2896 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002897 mDrawingState.callbackHandles = {};
2898}
2899
2900bool Layer::willPresentCurrentTransaction() const {
2901 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2902 return (getSidebandStreamChanged() || getAutoRefresh() ||
2903 (mDrawingState.modified &&
2904 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2905}
2906
2907bool Layer::setTransform(uint32_t transform) {
2908 if (mDrawingState.bufferTransform == transform) return false;
2909 mDrawingState.bufferTransform = transform;
2910 mDrawingState.modified = true;
2911 setTransactionFlags(eTransactionNeeded);
2912 return true;
2913}
2914
2915bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2916 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2917 mDrawingState.sequence++;
2918 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2919 mDrawingState.modified = true;
2920 setTransactionFlags(eTransactionNeeded);
2921 return true;
2922}
2923
2924bool Layer::setBufferCrop(const Rect& bufferCrop) {
2925 if (mDrawingState.bufferCrop == bufferCrop) return false;
2926
2927 mDrawingState.sequence++;
2928 mDrawingState.bufferCrop = bufferCrop;
2929
2930 mDrawingState.modified = true;
2931 setTransactionFlags(eTransactionNeeded);
2932 return true;
2933}
2934
2935bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2936 if (mDrawingState.destinationFrame == destinationFrame) return false;
2937
2938 mDrawingState.sequence++;
2939 mDrawingState.destinationFrame = destinationFrame;
2940
2941 mDrawingState.modified = true;
2942 setTransactionFlags(eTransactionNeeded);
2943 return true;
2944}
2945
2946// Translate destination frame into scale and position. If a destination frame is not set, use the
2947// provided scale and position
2948bool Layer::updateGeometry() {
2949 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2950 mDrawingState.destinationFrame.isEmpty()) {
2951 // If destination frame is not set, use the requested transform set via
2952 // Layer::setPosition and Layer::setMatrix.
2953 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2954 }
2955
2956 Rect destRect = mDrawingState.destinationFrame;
2957 int32_t destW = destRect.width();
2958 int32_t destH = destRect.height();
2959 if (destRect.left < 0) {
2960 destRect.left = 0;
2961 destRect.right = destW;
2962 }
2963 if (destRect.top < 0) {
2964 destRect.top = 0;
2965 destRect.bottom = destH;
2966 }
2967
2968 if (!mDrawingState.buffer) {
2969 ui::Transform t;
2970 t.set(destRect.left, destRect.top);
2971 return assignTransform(&mDrawingState.transform, t);
2972 }
2973
2974 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2975 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2976 // Undo any transformations on the buffer.
2977 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2978 std::swap(bufferWidth, bufferHeight);
2979 }
2980 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
2981 if (mDrawingState.transformToDisplayInverse) {
2982 if (invTransform & ui::Transform::ROT_90) {
2983 std::swap(bufferWidth, bufferHeight);
2984 }
2985 }
2986
2987 float sx = destW / static_cast<float>(bufferWidth);
2988 float sy = destH / static_cast<float>(bufferHeight);
2989 ui::Transform t;
2990 t.set(sx, 0, 0, sy);
2991 t.set(destRect.left, destRect.top);
2992 return assignTransform(&mDrawingState.transform, t);
2993}
2994
2995bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
2996 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
2997 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
2998 return false;
2999 }
3000
3001 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3002
3003 mDrawingState.sequence++;
3004 mDrawingState.modified = true;
3005 setTransactionFlags(eTransactionNeeded);
3006
3007 return true;
3008}
3009
3010bool Layer::setPosition(float x, float y) {
3011 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3012 return false;
3013 }
3014
3015 mRequestedTransform.set(x, y);
3016
3017 mDrawingState.sequence++;
3018 mDrawingState.modified = true;
3019 setTransactionFlags(eTransactionNeeded);
3020
3021 return true;
3022}
3023
3024bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3025 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3026 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003027 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003028 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003029 if (!buffer) {
3030 return false;
3031 }
3032
3033 const bool frameNumberChanged =
3034 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3035 const uint64_t frameNumber =
3036 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003037 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003038
3039 if (mDrawingState.buffer) {
3040 mReleasePreviousBuffer = true;
3041 if (!mBufferInfo.mBuffer ||
3042 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3043 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3044 // If mDrawingState has a buffer, and we are about to update again
3045 // before swapping to drawing state, then the first buffer will be
3046 // dropped and we should decrement the pending buffer count and
3047 // call any release buffer callbacks if set.
3048 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3049 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003050 mDrawingState.acquireFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003051 decrementPendingBufferCount();
3052 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3053 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3054 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
3055 mDrawingState.bufferSurfaceFrameTX.reset();
3056 }
3057 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3058 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3059 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003060 mLastClientCompositionFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003061 mLastClientCompositionFence = nullptr;
3062 }
Vishnu Nairc09c0232023-03-02 03:22:35 +00003063 } else {
3064 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3065 // we don't want to incorrectly classify a frame if we miss the desired present time.
3066 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003067 }
3068
liulijuneb489f62022-10-17 22:02:14 +08003069 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -07003070 mDrawingState.barrierProducerId =
3071 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003072 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -07003073 mDrawingState.barrierFrameNumber =
3074 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
3075
3076 // TODO(b/277265947) log and flush transaction trace when we detect out of order updates
Patrick Williamsbb25f802022-08-30 23:02:34 +00003077 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3078 mDrawingState.buffer = std::move(buffer);
3079 mDrawingState.clientCacheId = bufferData.cachedBuffer;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003080 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3081 ? bufferData.acquireFence
3082 : Fence::NO_FENCE;
3083 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3084 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3085 // We latched this buffer unsiganled, so we need to pass the acquire fence
3086 // on the callback instead of just the acquire time, since it's unknown at
3087 // this point.
3088 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3089 } else {
3090 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3091 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003092 mDrawingState.latchedVsyncId = info.vsyncId;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003093 mDrawingState.modified = true;
3094 setTransactionFlags(eTransactionNeeded);
3095
3096 const int32_t layerId = getSequence();
3097 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3098 mOwnerUid, postTime, getGameMode());
3099 mDrawingState.desiredPresentTime = desiredPresentTime;
3100 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3101
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003102 if (mFlinger->mLegacyFrontEndEnabled) {
3103 recordLayerHistoryBufferUpdate(getLayerProps());
3104 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003105
3106 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3107
3108 if (dequeueTime && *dequeueTime != 0) {
3109 const uint64_t bufferId = mDrawingState.buffer->getId();
3110 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3111 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3112 FrameTracer::FrameEvent::DEQUEUE);
3113 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3114 FrameTracer::FrameEvent::QUEUE);
3115 }
3116
3117 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3118 return true;
3119}
3120
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003121void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3122 mDrawingState.desiredPresentTime = desiredPresentTime;
3123 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3124}
3125
3126void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps) {
3127 const nsecs_t presentTime = [&] {
3128 if (!mDrawingState.isAutoTimestamp) return mDrawingState.desiredPresentTime;
3129
3130 const auto prediction = mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3131 mDrawingState.latchedVsyncId);
3132 if (prediction.has_value()) return prediction->presentTime;
3133
3134 return static_cast<nsecs_t>(0);
3135 }();
3136 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3137 scheduler::LayerHistory::LayerUpdateType::Buffer);
3138}
3139
3140void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps) {
3141 const nsecs_t presentTime =
3142 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
3143 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3144 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3145}
3146
Patrick Williamsbb25f802022-08-30 23:02:34 +00003147bool Layer::setDataspace(ui::Dataspace dataspace) {
3148 mDrawingState.dataspaceRequested = true;
3149 if (mDrawingState.dataspace == dataspace) return false;
3150 mDrawingState.dataspace = dataspace;
3151 mDrawingState.modified = true;
3152 setTransactionFlags(eTransactionNeeded);
3153 return true;
3154}
3155
John Reck68796592023-01-25 13:47:12 -05003156bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07003157 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3158 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05003159 return false;
Sally Qi963049b2023-03-23 14:06:21 -07003160 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3161 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05003162 mDrawingState.modified = true;
3163 setTransactionFlags(eTransactionNeeded);
3164 return true;
3165}
3166
Alec Mourif4af03e2023-02-11 00:25:24 +00003167bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3168 if (mDrawingState.cachingHint == cachingHint) return false;
3169 mDrawingState.cachingHint = cachingHint;
3170 mDrawingState.modified = true;
3171 setTransactionFlags(eTransactionNeeded);
3172 return true;
3173}
3174
Patrick Williamsbb25f802022-08-30 23:02:34 +00003175bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3176 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3177 mDrawingState.hdrMetadata = hdrMetadata;
3178 mDrawingState.modified = true;
3179 setTransactionFlags(eTransactionNeeded);
3180 return true;
3181}
3182
3183bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003184 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003185 mDrawingState.surfaceDamageRegion = surfaceDamage;
3186 mDrawingState.modified = true;
3187 setTransactionFlags(eTransactionNeeded);
3188 return true;
3189}
3190
3191bool Layer::setApi(int32_t api) {
3192 if (mDrawingState.api == api) return false;
3193 mDrawingState.api = api;
3194 mDrawingState.modified = true;
3195 setTransactionFlags(eTransactionNeeded);
3196 return true;
3197}
3198
3199bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3200 if (mDrawingState.sidebandStream == sidebandStream) return false;
3201
3202 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3203 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3204 } else if (sidebandStream != nullptr) {
3205 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3206 }
3207
3208 mDrawingState.sidebandStream = sidebandStream;
3209 mDrawingState.modified = true;
3210 setTransactionFlags(eTransactionNeeded);
3211 if (!mSidebandStreamChanged.exchange(true)) {
3212 // mSidebandStreamChanged was false
3213 mFlinger->onLayerUpdate();
3214 }
3215 return true;
3216}
3217
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003218bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3219 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003220 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3221 if (handles.empty()) {
3222 mReleasePreviousBuffer = false;
3223 return false;
3224 }
3225
Pascal Muetschard81cef292023-02-06 12:18:52 +01003226 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003227 for (const auto& handle : handles) {
3228 // If this transaction set a buffer on this layer, release its previous buffer
3229 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3230
3231 // If this layer will be presented in this frame
3232 if (willPresent) {
3233 // If this transaction set an acquire fence on this layer, set its acquire time
3234 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3235 handle->frameNumber = mDrawingState.frameNumber;
3236
3237 // Store so latched time and release fence can be set
3238 mDrawingState.callbackHandles.push_back(handle);
3239
3240 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003241 // Queue this handle to be notified below.
3242 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003243 }
3244 }
3245
Pascal Muetschard81cef292023-02-06 12:18:52 +01003246 if (!remainingHandles.empty()) {
3247 // Notify the transaction completed threads these handles are done. These are only the
3248 // handles that were not added to the mDrawingState, which will be notified later.
3249 std::vector<JankData> jankData;
3250 transferAvailableJankData(remainingHandles, jankData);
3251 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3252 }
3253
Patrick Williamsbb25f802022-08-30 23:02:34 +00003254 mReleasePreviousBuffer = false;
3255 mCallbackHandleAcquireTimeOrFence = -1;
3256
3257 return willPresent;
3258}
3259
3260Rect Layer::getBufferSize(const State& /*s*/) const {
3261 // for buffer state layers we use the display frame size as the buffer size.
3262
3263 if (mBufferInfo.mBuffer == nullptr) {
3264 return Rect::INVALID_RECT;
3265 }
3266
3267 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3268 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3269
3270 // Undo any transformations on the buffer and return the result.
3271 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3272 std::swap(bufWidth, bufHeight);
3273 }
3274
3275 if (getTransformToDisplayInverse()) {
3276 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3277 if (invTransform & ui::Transform::ROT_90) {
3278 std::swap(bufWidth, bufHeight);
3279 }
3280 }
3281
3282 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3283}
3284
3285FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3286 if (mBufferInfo.mBuffer == nullptr) {
3287 return parentBounds;
3288 }
3289
3290 return getBufferSize(getDrawingState()).toFloatRect();
3291}
3292
3293bool Layer::fenceHasSignaled() const {
3294 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3295 return true;
3296 }
3297
3298 const bool fenceSignaled =
3299 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3300 if (!fenceSignaled) {
3301 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3302 TimeStats::LatchSkipReason::LateAcquire);
3303 }
3304
3305 return fenceSignaled;
3306}
3307
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003308void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003309 for (const auto& handle : mDrawingState.callbackHandles) {
3310 handle->refreshStartTime = refreshStartTime;
3311 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003312}
3313
3314void Layer::setAutoRefresh(bool autoRefresh) {
3315 mDrawingState.autoRefresh = autoRefresh;
3316}
3317
3318bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3319 // 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 +00003320 auto* snapshot = editLayerSnapshot();
3321 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003322
3323 if (mSidebandStreamChanged.exchange(false)) {
3324 const State& s(getDrawingState());
3325 // mSidebandStreamChanged was true
3326 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003327 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003328 if (mSidebandStream != nullptr) {
3329 setTransactionFlags(eTransactionNeeded);
3330 mFlinger->setTransactionFlags(eTraversalNeeded);
3331 }
3332 recomputeVisibleRegions = true;
3333
3334 return true;
3335 }
3336 return false;
3337}
3338
3339bool Layer::hasFrameUpdate() const {
3340 const State& c(getDrawingState());
3341 return (mDrawingStateModified || mDrawingState.modified) &&
3342 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3343}
3344
Vishnu Naird47bcee2023-02-24 18:08:51 +00003345void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003346 const State& s(getDrawingState());
3347
3348 if (!s.buffer) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003349 if (bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003350 for (auto& handle : mDrawingState.callbackHandles) {
3351 handle->latchTime = latchTime;
3352 }
3353 }
3354 return;
3355 }
3356
3357 for (auto& handle : mDrawingState.callbackHandles) {
3358 if (handle->frameNumber == mDrawingState.frameNumber) {
3359 handle->latchTime = latchTime;
3360 }
3361 }
3362
3363 const int32_t layerId = getSequence();
3364 const uint64_t bufferId = mDrawingState.buffer->getId();
3365 const uint64_t frameNumber = mDrawingState.frameNumber;
3366 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3367 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3368 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3369
3370 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3371 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3372 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3373 FrameTracer::FrameEvent::LATCH);
3374
3375 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3376 if (bufferSurfaceFrame != nullptr &&
3377 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3378 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3379 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3380 // are processing the next state.
3381 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3382 mDrawingState.acquireFenceTime->getSignalTime(),
3383 latchTime);
3384 mDrawingState.bufferSurfaceFrameTX.reset();
3385 }
3386
3387 std::deque<sp<CallbackHandle>> remainingHandles;
3388 mFlinger->getTransactionCallbackInvoker()
3389 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3390 mDrawingState.callbackHandles = remainingHandles;
3391
3392 mDrawingStateModified = false;
3393}
3394
3395void Layer::gatherBufferInfo() {
3396 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3397 decrementPendingBufferCount();
3398 }
3399
3400 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3401 mBufferInfo.mBuffer = mDrawingState.buffer;
3402 mBufferInfo.mFence = mDrawingState.acquireFence;
3403 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3404 mBufferInfo.mPixelFormat =
3405 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3406 mBufferInfo.mFrameLatencyNeeded = true;
3407 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3408 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3409 mBufferInfo.mFence = mDrawingState.acquireFence;
3410 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3411 auto lastDataspace = mBufferInfo.mDataspace;
3412 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3413 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003414 mFlinger->mHdrLayerInfoChanged = true;
3415 }
Sally Qi963049b2023-03-23 14:06:21 -07003416 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3417 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05003418 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003419 }
3420 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3421 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3422 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3423 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3424 mBufferInfo.mApi = mDrawingState.api;
3425 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003426}
3427
3428Rect Layer::computeBufferCrop(const State& s) {
3429 if (s.buffer && !s.bufferCrop.isEmpty()) {
3430 Rect bufferCrop;
3431 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3432 return bufferCrop;
3433 } else if (s.buffer) {
3434 return s.buffer->getBounds();
3435 } else {
3436 return s.bufferCrop;
3437 }
3438}
3439
3440sp<Layer> Layer::createClone() {
3441 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3442 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003443 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003444 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3445 return layer;
3446}
3447
Patrick Williamsbb25f802022-08-30 23:02:34 +00003448void Layer::decrementPendingBufferCount() {
3449 int32_t pendingBuffers = --mPendingBufferTransactions;
3450 tracePendingBufferCount(pendingBuffers);
3451}
3452
3453void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3454 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3455}
3456
3457/*
3458 * We don't want to send the layer's transform to input, but rather the
3459 * parent's transform. This is because Layer's transform is
3460 * information about how the buffer is placed on screen. The parent's
3461 * transform makes more sense to send since it's information about how the
3462 * layer is placed on screen. This transform is used by input to determine
3463 * how to go from screen space back to window space.
3464 */
3465ui::Transform Layer::getInputTransform() const {
3466 if (!hasBufferOrSidebandStream()) {
3467 return getTransform();
3468 }
3469 sp<Layer> parent = mDrawingParent.promote();
3470 if (parent == nullptr) {
3471 return ui::Transform();
3472 }
3473
3474 return parent->getTransform();
3475}
3476
3477/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003478 * Returns the bounds used to fill the input frame and the touchable region.
3479 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003480 * Similar to getInputTransform, we need to update the bounds to include the transform.
3481 * This is because bounds don't include the buffer transform, where the input assumes
3482 * that's already included.
3483 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003484std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3485 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3486 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3487 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3488 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3489 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003490 }
3491
Vishnu Nairfed7c122023-03-18 01:54:43 +00003492 bool inputBoundsValid = croppedBufferSize.isValid();
3493 if (!inputBoundsValid) {
3494 /**
3495 * Input bounds are based on the layer crop or buffer size. But if we are using
3496 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3497 * we can use the parent bounds as the input bounds if the layer does not have buffer
3498 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3499 * use the parent bounds. A layer without a buffer can get input. So when a window is
3500 * initially added, its touchable region can fill its parent layer bounds and that can
3501 * have negative consequences.
3502 */
3503 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003504 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003505
3506 // Clamp surface inset to the input bounds.
3507 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3508 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3509 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3510
3511 // Apply the insets to the input bounds.
3512 inputBounds.left += xSurfaceInset;
3513 inputBounds.top += ySurfaceInset;
3514 inputBounds.right -= xSurfaceInset;
3515 inputBounds.bottom -= ySurfaceInset;
3516
3517 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003518}
3519
3520bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3521 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3522
3523 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3524 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3525 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3526 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3527 layer_state_t::eReparent;
3528
3529 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3530 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3531 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3532 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3533 layer_state_t::eInputInfoChanged;
3534
3535 if ((s.what & requiredFlags) != requiredFlags) {
3536 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3537 (s.what | requiredFlags) & ~s.what);
3538 return false;
3539 }
3540
3541 if (s.what & deniedFlags) {
3542 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3543 return false;
3544 }
3545
3546 if (s.what & allowedFlags) {
3547 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3548 }
3549
3550 if (s.what & layer_state_t::ePositionChanged) {
3551 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3552 ALOGV("%s: false [ePositionChanged changed]", __func__);
3553 return false;
3554 }
3555 }
3556
3557 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003558 if (mDrawingState.color.a != s.color.a) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003559 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3560 return false;
3561 }
3562 }
3563
3564 if (s.what & layer_state_t::eColorTransformChanged) {
3565 if (mDrawingState.colorTransform != s.colorTransform) {
3566 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3567 return false;
3568 }
3569 }
3570
3571 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003572 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003573 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3574 return false;
3575 }
3576 }
3577
3578 if (s.what & layer_state_t::eMatrixChanged) {
3579 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3580 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3581 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3582 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3583 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3584 return false;
3585 }
3586 }
3587
3588 if (s.what & layer_state_t::eCornerRadiusChanged) {
3589 if (mDrawingState.cornerRadius != s.cornerRadius) {
3590 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3591 return false;
3592 }
3593 }
3594
3595 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3596 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3597 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3598 return false;
3599 }
3600 }
3601
Vishnu Nairbbceb462022-10-10 04:52:13 +00003602 if (s.what & layer_state_t::eBufferTransformChanged) {
3603 if (mDrawingState.bufferTransform != s.bufferTransform) {
3604 ALOGV("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003605 return false;
3606 }
3607 }
3608
3609 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3610 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3611 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3612 return false;
3613 }
3614 }
3615
3616 if (s.what & layer_state_t::eCropChanged) {
3617 if (mDrawingState.crop != s.crop) {
3618 ALOGV("%s: false [eCropChanged changed]", __func__);
3619 return false;
3620 }
3621 }
3622
3623 if (s.what & layer_state_t::eDataspaceChanged) {
3624 if (mDrawingState.dataspace != s.dataspace) {
3625 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3626 return false;
3627 }
3628 }
3629
3630 if (s.what & layer_state_t::eHdrMetadataChanged) {
3631 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3632 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3633 return false;
3634 }
3635 }
3636
3637 if (s.what & layer_state_t::eSidebandStreamChanged) {
3638 if (mDrawingState.sidebandStream != s.sidebandStream) {
3639 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3640 return false;
3641 }
3642 }
3643
3644 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3645 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3646 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3647 return false;
3648 }
3649 }
3650
3651 if (s.what & layer_state_t::eShadowRadiusChanged) {
3652 if (mDrawingState.shadowRadius != s.shadowRadius) {
3653 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3654 return false;
3655 }
3656 }
3657
3658 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3659 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3660 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3661 return false;
3662 }
3663 }
3664
3665 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3666 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3667 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3668 return false;
3669 }
3670 }
3671
3672 if (s.what & layer_state_t::eStretchChanged) {
3673 StretchEffect temp = s.stretchEffect;
3674 temp.sanitize();
3675 if (mDrawingState.stretchEffect != temp) {
3676 ALOGV("%s: false [eStretchChanged changed]", __func__);
3677 return false;
3678 }
3679 }
3680
3681 if (s.what & layer_state_t::eBufferCropChanged) {
3682 if (mDrawingState.bufferCrop != s.bufferCrop) {
3683 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3684 return false;
3685 }
3686 }
3687
3688 if (s.what & layer_state_t::eDestinationFrameChanged) {
3689 if (mDrawingState.destinationFrame != s.destinationFrame) {
3690 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3691 return false;
3692 }
3693 }
3694
3695 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3696 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3697 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3698 return false;
3699 }
3700 }
3701
John Reck68796592023-01-25 13:47:12 -05003702 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07003703 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
3704 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
3705 ALOGV("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05003706 return false;
3707 }
3708 }
3709
Patrick Williamsbb25f802022-08-30 23:02:34 +00003710 ALOGV("%s: true", __func__);
3711 return true;
3712}
3713
3714bool Layer::isHdrY410() const {
3715 // pixel format is HDR Y410 masquerading as RGBA_1010102
3716 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3717 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3718 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3719}
3720
Vishnu Naire14c6b32022-08-06 04:20:15 +00003721sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003722 // 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 +00003723 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003724}
3725
Vishnu Naire14c6b32022-08-06 04:20:15 +00003726const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003727 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003728}
3729
Vishnu Naire14c6b32022-08-06 04:20:15 +00003730LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003731 return mSnapshot.get();
3732}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003733
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003734std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3735 return std::move(mSnapshot);
3736}
3737
3738void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3739 mSnapshot = std::move(snapshot);
3740}
3741
Patrick Williamsbb25f802022-08-30 23:02:34 +00003742const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003743 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003744}
3745
Patrick Williams7584c6a2022-10-29 02:10:58 +00003746sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003747 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003748 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3749 return result;
3750}
3751
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003752sp<LayerFE> Layer::getCompositionEngineLayerFE(
3753 const frontend::LayerHierarchy::TraversalPath& path) {
3754 for (auto& [p, layerFE] : mLayerFEs) {
3755 if (p == path) {
3756 return layerFE;
3757 }
3758 }
3759 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3760 mLayerFEs.emplace_back(path, layerFE);
3761 return layerFE;
3762}
3763
Patrick Williamsbb25f802022-08-30 23:02:34 +00003764void Layer::useSurfaceDamage() {
3765 if (mFlinger->mForceFullDamage) {
3766 surfaceDamageRegion = Region::INVALID_REGION;
3767 } else {
3768 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3769 }
3770}
3771
3772void Layer::useEmptyDamage() {
3773 surfaceDamageRegion.clear();
3774}
3775
3776bool Layer::isOpaque(const Layer::State& s) const {
3777 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3778 // layer's opaque flag.
3779 if (!hasSomethingToDraw()) {
3780 return false;
3781 }
3782
3783 // if the layer has the opaque flag, then we're always opaque
3784 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3785 return true;
3786 }
3787
3788 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003789 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003790 return true;
3791 }
3792
3793 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3794 return fillsColor() && getAlpha() == 1.0_hf;
3795}
3796
3797bool Layer::canReceiveInput() const {
3798 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3799}
3800
3801bool Layer::isVisible() const {
3802 if (!hasSomethingToDraw()) {
3803 return false;
3804 }
3805
3806 if (isHiddenByPolicy()) {
3807 return false;
3808 }
3809
3810 return getAlpha() > 0.0f || hasBlur();
3811}
3812
3813void Layer::onPostComposition(const DisplayDevice* display,
3814 const std::shared_ptr<FenceTime>& glDoneFence,
3815 const std::shared_ptr<FenceTime>& presentFence,
3816 const CompositorTiming& compositorTiming) {
3817 // mFrameLatencyNeeded is true when a new frame was latched for the
3818 // composition.
3819 if (!mBufferInfo.mFrameLatencyNeeded) return;
3820
3821 for (const auto& handle : mDrawingState.callbackHandles) {
3822 handle->gpuCompositionDoneFence = glDoneFence;
3823 handle->compositorTiming = compositorTiming;
3824 }
3825
3826 // Update mFrameTracker.
3827 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3828 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3829
3830 const int32_t layerId = getSequence();
3831 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3832
3833 const auto outputLayer = findOutputLayerForDisplay(display);
3834 if (outputLayer && outputLayer->requiresClientComposition()) {
3835 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3836 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3837 clientCompositionTimestamp,
3838 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3839 // Update the SurfaceFrames in the drawing state
3840 if (mDrawingState.bufferSurfaceFrameTX) {
3841 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3842 }
3843 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3844 surfaceFrame->setGpuComposition();
3845 }
3846 }
3847
3848 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3849 if (frameReadyFence->isValid()) {
3850 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3851 } else {
3852 // There was no fence for this frame, so assume that it was ready
3853 // to be presented at the desired present time.
3854 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3855 }
3856
3857 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08003858 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003859 const std::optional<Fps> renderRate =
3860 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3861
3862 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3863 const auto gameMode = getGameMode();
3864
3865 if (presentFence->isValid()) {
3866 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3867 refreshRate, renderRate, vote, gameMode);
3868 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3869 presentFence,
3870 FrameTracer::FrameEvent::PRESENT_FENCE);
3871 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3872 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3873 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003874 // The HWC doesn't support present fences, so use the present timestamp instead.
3875 const nsecs_t presentTimestamp =
3876 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3877
3878 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3879 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3880 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3881
Patrick Williamsbb25f802022-08-30 23:02:34 +00003882 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3883 refreshRate, renderRate, vote, gameMode);
3884 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3885 mCurrentFrameNumber, actualPresentTime,
3886 FrameTracer::FrameEvent::PRESENT_FENCE);
3887 mFrameTracker.setActualPresentTime(actualPresentTime);
3888 }
3889 }
3890
3891 mFrameTracker.advanceFrame();
3892 mBufferInfo.mFrameLatencyNeeded = false;
3893}
3894
3895bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003896 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
3897 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
3898}
3899
3900bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003901 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3902 getDrawingState().frameNumber);
3903
3904 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3905
3906 if (refreshRequired) {
3907 return refreshRequired;
3908 }
3909
3910 // If the head buffer's acquire fence hasn't signaled yet, return and
3911 // try again later
3912 if (!fenceHasSignaled()) {
3913 ATRACE_NAME("!fenceHasSignaled()");
3914 mFlinger->onLayerUpdate();
3915 return false;
3916 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00003917 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003918 if (mDrawingState.buffer == nullptr) {
3919 return false;
3920 }
3921
3922 // Capture the old state of the layer for comparisons later
3923 BufferInfo oldBufferInfo = mBufferInfo;
3924 const bool oldOpacity = isOpaque(mDrawingState);
3925 mPreviousFrameNumber = mCurrentFrameNumber;
3926 mCurrentFrameNumber = mDrawingState.frameNumber;
3927 gatherBufferInfo();
3928
3929 if (oldBufferInfo.mBuffer == nullptr) {
3930 // the first time we receive a buffer, we need to trigger a
3931 // geometry invalidation.
3932 recomputeVisibleRegions = true;
3933 }
3934
3935 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3936 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3937 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3938 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3939 recomputeVisibleRegions = true;
3940 }
3941
3942 if (oldBufferInfo.mBuffer != nullptr) {
3943 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3944 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3945 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3946 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3947 recomputeVisibleRegions = true;
3948 }
3949 }
3950
3951 if (oldOpacity != isOpaque(mDrawingState)) {
3952 recomputeVisibleRegions = true;
3953 }
3954
3955 return true;
3956}
3957
3958bool Layer::hasReadyFrame() const {
3959 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
3960}
3961
3962bool Layer::isProtected() const {
3963 return (mBufferInfo.mBuffer != nullptr) &&
3964 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
3965}
3966
Patrick Williamsbb25f802022-08-30 23:02:34 +00003967void Layer::latchAndReleaseBuffer() {
3968 if (hasReadyFrame()) {
3969 bool ignored = false;
3970 latchBuffer(ignored, systemTime());
3971 }
3972 releasePendingBuffer(systemTime());
3973}
3974
3975PixelFormat Layer::getPixelFormat() const {
3976 return mBufferInfo.mPixelFormat;
3977}
3978
3979bool Layer::getTransformToDisplayInverse() const {
3980 return mBufferInfo.mTransformToDisplayInverse;
3981}
3982
3983Rect Layer::getBufferCrop() const {
3984 // this is the crop rectangle that applies to the buffer
3985 // itself (as opposed to the window)
3986 if (!mBufferInfo.mCrop.isEmpty()) {
3987 // if the buffer crop is defined, we use that
3988 return mBufferInfo.mCrop;
3989 } else if (mBufferInfo.mBuffer != nullptr) {
3990 // otherwise we use the whole buffer
3991 return mBufferInfo.mBuffer->getBounds();
3992 } else {
3993 // if we don't have a buffer yet, we use an empty/invalid crop
3994 return Rect();
3995 }
3996}
3997
3998uint32_t Layer::getBufferTransform() const {
3999 return mBufferInfo.mTransform;
4000}
4001
4002ui::Dataspace Layer::getDataSpace() const {
4003 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
4004}
4005
4006ui::Dataspace Layer::getRequestedDataSpace() const {
4007 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4008}
4009
4010ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4011 ui::Dataspace updatedDataspace = dataspace;
4012 // translate legacy dataspaces to modern dataspaces
4013 switch (dataspace) {
4014 case ui::Dataspace::SRGB:
4015 updatedDataspace = ui::Dataspace::V0_SRGB;
4016 break;
4017 case ui::Dataspace::SRGB_LINEAR:
4018 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4019 break;
4020 case ui::Dataspace::JFIF:
4021 updatedDataspace = ui::Dataspace::V0_JFIF;
4022 break;
4023 case ui::Dataspace::BT601_625:
4024 updatedDataspace = ui::Dataspace::V0_BT601_625;
4025 break;
4026 case ui::Dataspace::BT601_525:
4027 updatedDataspace = ui::Dataspace::V0_BT601_525;
4028 break;
4029 case ui::Dataspace::BT709:
4030 updatedDataspace = ui::Dataspace::V0_BT709;
4031 break;
4032 default:
4033 break;
4034 }
4035
4036 return updatedDataspace;
4037}
4038
4039sp<GraphicBuffer> Layer::getBuffer() const {
4040 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4041}
4042
Vishnu Nairb76d99a2023-03-19 18:22:31 -07004043void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4044 mTransformHintLegacy = getFixedTransformHint();
4045 if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4046 mTransformHintLegacy = displayTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004047 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004048 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004049}
4050
4051const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4052 return mBufferInfo.mBuffer;
4053}
4054
4055bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004056 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004057 return false;
4058 }
4059
4060 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004061 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004062 mDrawingState.modified = true;
4063 setTransactionFlags(eTransactionNeeded);
4064 return true;
4065}
4066
4067bool Layer::fillsColor() const {
4068 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4069 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4070}
4071
4072bool Layer::hasBlur() const {
4073 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4074}
4075
Vishnu Nairba354102022-08-01 00:14:18 +00004076void Layer::updateSnapshot(bool updateGeometry) {
4077 if (!getCompositionEngineLayerFE()) {
4078 return;
4079 }
4080
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004081 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004082 if (updateGeometry) {
4083 prepareBasicGeometryCompositionState();
4084 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004085 snapshot->roundedCorner = getRoundedCornerState();
4086 snapshot->stretchEffect = getStretchEffect();
4087 snapshot->transformedBounds = mScreenBounds;
4088 if (mEffectiveShadowRadius > 0.f) {
4089 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4090
4091 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4092 // it if transparent regions are present. This may not be necessary since shadows are
4093 // typically cast by layers without transparent regions.
4094 snapshot->shadowSettings.boundaries = mBounds;
4095
4096 const float casterAlpha = snapshot->alpha;
4097 const bool casterIsOpaque =
4098 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4099
4100 // If the casting layer is translucent, we need to fill in the shadow underneath the
4101 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4102 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4103 snapshot->shadowSettings.ambientColor *= casterAlpha;
4104 snapshot->shadowSettings.spotColor *= casterAlpha;
4105 }
4106 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004107 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004108 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004109 snapshot->layerOpaqueFlagSet =
4110 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004111 snapshot->isHdrY410 = isHdrY410();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004112 sp<Layer> p = mDrawingParent.promote();
4113 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004114 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004115 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004116 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004117 }
4118 snapshot->bufferSize = getBufferSize(mDrawingState);
4119 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004120 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004121 preparePerFrameCompositionState();
4122}
4123
Vishnu Naire14c6b32022-08-06 04:20:15 +00004124void Layer::updateChildrenSnapshots(bool updateGeometry) {
4125 for (const sp<Layer>& child : mDrawingChildren) {
4126 child->updateSnapshot(updateGeometry);
4127 child->updateChildrenSnapshots(updateGeometry);
4128 }
4129}
4130
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004131void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4132 mSnapshot->layerMetadata = parentMetadata;
4133 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4134 for (const sp<Layer>& child : mDrawingChildren) {
4135 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4136 }
4137}
4138
4139void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4140 std::unordered_set<Layer*>& visited) {
4141 if (visited.find(this) != visited.end()) {
4142 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4143 return;
4144 }
4145 visited.insert(this);
4146
4147 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4148
4149 if (mDrawingState.zOrderRelatives.empty()) {
4150 return;
4151 }
4152 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4153 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4154 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4155 sp<Layer> relative = weakRelative.promote();
4156 if (!relative) {
4157 continue;
4158 }
4159 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4160 }
4161}
4162
Chavi Weingarten328a8312023-01-26 21:17:52 +00004163bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004164 TrustedPresentationListener const& listener) {
4165 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4166 mTrustedPresentationListener = listener;
4167 mTrustedPresentationThresholds = thresholds;
4168 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4169 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4170 mFlinger->mNumTrustedPresentationListeners++;
4171 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4172 mFlinger->mNumTrustedPresentationListeners--;
4173 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004174
4175 // Reset trusted presentation states to ensure we start the time again.
4176 mEnteredTrustedPresentationStateTime = -1;
4177 mLastReportedTrustedPresentationState = false;
4178 mLastComputedTrustedPresentationState = false;
4179
4180 // If there's a new trusted presentation listener, the code needs to go through the composite
4181 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4182 // we're already in the requested state.
4183 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004184}
4185
Vishnu Naira156f482023-02-22 00:23:38 +00004186void Layer::updateLastLatchTime(nsecs_t latchTime) {
4187 mLastLatchTime = latchTime;
4188}
4189
Mathias Agopian13127d82013-03-05 17:47:11 -08004190// ---------------------------------------------------------------------------
4191
Marin Shalamanov46084422020-10-13 12:33:42 +02004192std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004193 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4194 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004195}
4196
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004197} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004198
4199#if defined(__gl_h_)
4200#error "don't include gl/gl.h in this file"
4201#endif
4202
4203#if defined(__gl2_h_)
4204#error "don't include gl2/gl2.h in this file"
4205#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004206
4207// TODO(b/129481165): remove the #pragma below and fix conversion issues
4208#pragma clang diagnostic pop // ignored "-Wconversion"