blob: 8dec57bf3ce88997e6531c7ed41978f09bf77dc2 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Dan Stoza9e56aa02015-11-02 13:00:03 -080021//#define LOG_NDEBUG 0
22#undef LOG_TAG
23#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080024#define ATRACE_TAG ATRACE_TAG_GRAPHICS
25
Alec Mourie60041e2019-06-14 18:59:51 -070026#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080027
[1;3C2b9fc252021-02-04 16:16:50 -080028#include <android-base/properties.h>
Yiwei Zhang5434a782018-12-05 18:06:32 -080029#include <android-base/stringprintf.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080030#include <android/native_window.h>
Vishnu Nair0f085c62019-08-30 08:49:12 -070031#include <binder/IPCThreadState.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000032#include <compositionengine/CompositionEngine.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080033#include <compositionengine/Display.h>
Lloyd Piquea83776c2019-01-29 18:42:32 -080034#include <compositionengine/LayerFECompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080035#include <compositionengine/OutputLayer.h>
36#include <compositionengine/impl/OutputLayerCompositionState.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070037#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070038#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070039#include <cutils/properties.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070040#include <ftl/enum.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080041#include <ftl/fake_guard.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080042#include <gui/BufferItem.h>
43#include <gui/LayerDebugInfo.h>
44#include <gui/Surface.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000045#include <gui/TraceUtils.h>
Alec Mourie60041e2019-06-14 18:59:51 -070046#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070047#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070049#include <stdint.h>
50#include <stdlib.h>
51#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000052#include <system/graphics-base-v1.0.h>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070053#include <ui/DataspaceUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080054#include <ui/DebugUtils.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000055#include <ui/FloatRect.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080056#include <ui/GraphicBuffer.h>
57#include <ui/PixelFormat.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000058#include <ui/Rect.h>
59#include <ui/Transform.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060#include <utils/Errors.h>
61#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080062#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080064#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065
Alec Mourie60041e2019-06-14 18:59:51 -070066#include <algorithm>
67#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070068#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070069#include <sstream>
70
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070071#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080072#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070073#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070074#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +000075#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000076#include "FrontEnd/LayerHandle.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080077#include "LayerProtoHelper.h"
Josh Gao194ff392022-09-08 16:19:29 -070078#include "MutexUtils.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080080#include "TimeStats/TimeStats.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070081#include "TunnelModeEnabledReporter.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070082
David Sodman41fdfc92017-11-06 16:09:56 -080083#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000084#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086namespace android {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010087namespace {
88constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000089
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000090const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000091
Patrick Williamsbb25f802022-08-30 23:02:34 +000092bool assignTransform(ui::Transform* dst, ui::Transform& from) {
93 if (*dst == from) {
94 return false;
95 }
96 *dst = from;
97 return true;
98}
99
100TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
101 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
102 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
103 const auto frameRateCompatibility = [frameRate] {
104 switch (frameRate.type) {
105 case Layer::FrameRateCompatibility::Default:
106 return FrameRateCompatibility::Default;
107 case Layer::FrameRateCompatibility::ExactOrMultiple:
108 return FrameRateCompatibility::ExactOrMultiple;
109 default:
110 return FrameRateCompatibility::Undefined;
111 }
112 }();
113
114 const auto seamlessness = [frameRate] {
115 switch (frameRate.seamlessness) {
116 case scheduler::Seamlessness::OnlySeamless:
117 return Seamlessness::ShouldBeSeamless;
118 case scheduler::Seamlessness::SeamedAndSeamless:
119 return Seamlessness::NotRequired;
120 default:
121 return Seamlessness::Undefined;
122 }
123 }();
124
125 return TimeStats::SetFrameRateVote{.frameRate = frameRate.rate.getValue(),
126 .frameRateCompatibility = frameRateCompatibility,
127 .seamlessness = seamlessness};
128}
129
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100130} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800131
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700132using namespace ftl::flag_operators;
133
Yiwei Zhang5434a782018-12-05 18:06:32 -0800134using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000135using frontend::LayerSnapshot;
136using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800137using gui::GameMode;
138using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500139using gui::WindowInfo;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800140
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700141using PresentState = frametimeline::SurfaceFrame::PresentState;
142
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700143Layer::Layer(const LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000144 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700145 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000146 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700147 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800148 mWindowType(static_cast<WindowInfo::Type>(
149 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000150 mLayerCreationFlags(args.flags),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000151 mBorderEnabled(false),
152 mTextureName(args.textureName),
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000153 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000154 ALOGV("Creating Layer %s", getDebugName());
155
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700156 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700157 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
158 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
159 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700160 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
161 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700162 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700163 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700164 mDrawingState.z = 0;
165 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700166 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700167 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700168 mDrawingState.transform.set(0, 0);
169 mDrawingState.frameNumber = 0;
170 mDrawingState.bufferTransform = 0;
171 mDrawingState.transformToDisplayInverse = false;
172 mDrawingState.crop.makeInvalid();
173 mDrawingState.acquireFence = sp<Fence>::make(-1);
174 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
175 mDrawingState.dataspace = ui::Dataspace::UNKNOWN;
Vishnu Nairbc4ee5c2022-08-16 03:19:37 +0000176 mDrawingState.dataspaceRequested = false;
Robert Carr6a160312021-05-17 12:08:20 -0700177 mDrawingState.hdrMetadata.validTypes = 0;
178 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
179 mDrawingState.cornerRadius = 0.0f;
180 mDrawingState.backgroundBlurRadius = 0;
181 mDrawingState.api = -1;
182 mDrawingState.hasColorTransform = false;
183 mDrawingState.colorSpaceAgnostic = false;
184 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
185 mDrawingState.metadata = args.metadata;
186 mDrawingState.shadowRadius = 0.f;
187 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
188 mDrawingState.frameTimelineInfo = {};
189 mDrawingState.postTime = -1;
190 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000191 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700192 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700193 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000194 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700195
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700196 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
197 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700198 mDrawingState.color.r = -1.0_hf;
199 mDrawingState.color.g = -1.0_hf;
200 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700201 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700202
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500203 mFrameTracker.setDisplayRefreshPeriod(
204 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700205
Vishnu Naircb8be502022-10-12 19:03:23 +0000206 mOwnerUid = args.ownerUid;
207 mOwnerPid = args.ownerPid;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000208
209 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
210 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
211 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
212 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000213
214 mSnapshot->sequence = sequence;
215 mSnapshot->name = getDebugName();
216 mSnapshot->textureName = mTextureName;
217 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000218 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800219}
220
221void Layer::onFirstRef() {
222 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700223}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700224
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700225Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000226 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
227 "Layer destructor called off the main thread.");
228
Patrick Williamsbb25f802022-08-30 23:02:34 +0000229 // The original layer and the clone layer share the same texture and buffer. Therefore, only
230 // one of the layers, in this case the original layer, needs to handle the deletion. The
231 // original layer and the clone should be removed at the same time so there shouldn't be any
232 // issue with the clone layer trying to use the texture.
233 if (mBufferInfo.mBuffer != nullptr) {
234 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
235 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800236 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000237 }
238 if (!isClone()) {
239 // The original layer and the clone layer share the same texture. Therefore, only one of
240 // the layers, in this case the original layer, needs to handle the deletion. The original
241 // layer and the clone should be removed at the same time so there shouldn't be any issue
242 // with the clone layer trying to use the deleted texture.
243 mFlinger->deleteTextureAsync(mTextureName);
244 }
245 const int32_t layerId = getSequence();
246 mFlinger->mTimeStats->onDestroy(layerId);
247 mFlinger->mFrameTracer->onDestroy(layerId);
248
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000249 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700250 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700251
252 if (mDrawingState.sidebandStream != nullptr) {
253 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
254 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700255 if (mHadClonedChild) {
256 mFlinger->mNumClones--;
257 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000258 if (hasTrustedPresentationListener()) {
259 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000260 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000261 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700262}
263
Mathias Agopian13127d82013-03-05 17:47:11 -0800264// ---------------------------------------------------------------------------
265// callbacks
266// ---------------------------------------------------------------------------
267
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700268void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700269 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700270 return;
271 }
Robert Carr2e102c92018-10-23 12:11:15 -0700272
Robert Carr6a160312021-05-17 12:08:20 -0700273 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700274 if (strongRelative == nullptr) {
275 setZOrderRelativeOf(nullptr);
276 return;
277 }
278
279 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700280 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700281 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800282 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700283 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700284}
285
286void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700287 if (!mRemovedFromDrawingState) {
288 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700289 mFlinger->mScheduler->deregisterLayer(this);
290 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000291 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000292
Ady Abrahamd11bade2022-08-01 16:18:03 -0700293 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700294}
Chia-I Wu38512252017-05-17 14:36:16 -0700295
chaviw68d4dab2020-06-08 15:07:32 -0700296sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000297 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700298 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700299 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700300 }
301 return parent->getRootLayer();
302}
303
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700304void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700305 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
306 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700307 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700308
Josh Gao194ff392022-09-08 16:19:29 -0700309 REQUIRE_MUTEX(mFlinger->mStateLock);
310 traverse(LayerVector::StateSet::Current,
311 [&](Layer* layer) REQUIRES(layer->mFlinger->mStateLock) {
312 layer->removeFromCurrentState();
313 layer->removeRelativeZ(layersInTree);
314 });
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()) {
Josh Gao194ff392022-09-08 16:19:29 -07001015 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001016 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001017 }
1018 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001019 } else if (mDrawingState.bgColorLayer && alpha == 0) {
Josh Gao194ff392022-09-08 16:19:29 -07001020 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001021 mDrawingState.bgColorLayer->reparent(nullptr);
1022 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001023 return true;
1024 }
1025
Robert Carr6a160312021-05-17 12:08:20 -07001026 mDrawingState.bgColorLayer->setColor(color);
1027 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1028 mDrawingState.bgColorLayer->setAlpha(alpha);
1029 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001030
chaviw13fdc492017-06-27 12:40:18 -07001031 return true;
1032}
1033
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001034bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001035 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001036
Robert Carr6a160312021-05-17 12:08:20 -07001037 mDrawingState.sequence++;
1038 mDrawingState.cornerRadius = cornerRadius;
1039 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001040 setTransactionFlags(eTransactionNeeded);
1041 return true;
1042}
1043
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001044bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001045 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001046 // If we start or stop drawing blur then the layer's visibility state may change so increment
1047 // the magic sequence number.
1048 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1049 mDrawingState.sequence++;
1050 }
Robert Carr6a160312021-05-17 12:08:20 -07001051 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1052 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001053 setTransactionFlags(eTransactionNeeded);
1054 return true;
1055}
Marissa Wall61c58622018-07-18 10:12:20 -07001056
Mathias Agopian13127d82013-03-05 17:47:11 -08001057bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001058 mDrawingState.sequence++;
1059 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001060 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001061 setTransactionFlags(eTransactionNeeded);
1062 return true;
1063}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001064
Lucas Dupinc3800b82020-10-02 16:24:48 -07001065bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001066 // If we start or stop drawing blur then the layer's visibility state may change so increment
1067 // the magic sequence number.
1068 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1069 mDrawingState.sequence++;
1070 }
Robert Carr6a160312021-05-17 12:08:20 -07001071 mDrawingState.blurRegions = blurRegions;
1072 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001073 setTransactionFlags(eTransactionNeeded);
1074 return true;
1075}
1076
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001077bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001078 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1079 if (mDrawingState.flags == newFlags) return false;
1080 mDrawingState.sequence++;
1081 mDrawingState.flags = newFlags;
1082 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001083 setTransactionFlags(eTransactionNeeded);
1084 return true;
1085}
Robert Carr99e27f02016-06-16 15:18:02 -07001086
chaviw25714502021-02-11 10:01:08 -08001087bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001088 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001089 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001090 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001091
Robert Carr6a160312021-05-17 12:08:20 -07001092 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001093 setTransactionFlags(eTransactionNeeded);
1094 return true;
1095}
Robert Carr8d5227b2017-03-16 15:41:03 -07001096
Evan Roskyef876c92019-01-25 17:46:06 -08001097bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001098 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1099 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001100 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001101 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001102}
1103
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001104bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001105 if (mDrawingState.layerStack == layerStack) return false;
1106 mDrawingState.sequence++;
1107 mDrawingState.layerStack = layerStack;
1108 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001109 setTransactionFlags(eTransactionNeeded);
1110 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001111}
1112
Peiyong Linc502cb72019-03-01 15:00:23 -08001113bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001114 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001115 return false;
1116 }
Robert Carr6a160312021-05-17 12:08:20 -07001117 mDrawingState.sequence++;
1118 mDrawingState.colorSpaceAgnostic = agnostic;
1119 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001120 setTransactionFlags(eTransactionNeeded);
1121 return true;
1122}
1123
Sally Qi81d95e62022-03-21 19:41:33 -07001124bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1125 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1126
1127 mDrawingState.sequence++;
1128 mDrawingState.dimmingEnabled = dimmingEnabled;
1129 mDrawingState.modified = true;
1130 setTransactionFlags(eTransactionNeeded);
1131 return true;
1132}
1133
Ana Krulecc84d09b2019-11-02 23:10:29 +01001134bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001135 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1136 mDrawingState.frameRateSelectionPriority = priority;
1137 mDrawingState.sequence++;
1138 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001139 setTransactionFlags(eTransactionNeeded);
1140 return true;
1141}
1142
1143int32_t Layer::getFrameRateSelectionPriority() const {
1144 // Check if layer has priority set.
1145 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1146 return mDrawingState.frameRateSelectionPriority;
1147 }
1148 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001149 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001150 if (parent != nullptr) {
1151 return parent->getFrameRateSelectionPriority();
1152 }
1153
1154 return Layer::PRIORITY_UNSET;
1155}
1156
Andy Labrada096227e2022-06-15 16:58:11 +00001157bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1158 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1159 mDrawingState.defaultFrameRateCompatibility = compatibility;
1160 mDrawingState.modified = true;
1161 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1162 setTransactionFlags(eTransactionNeeded);
1163 return true;
1164}
1165
1166scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1167 return mDrawingState.defaultFrameRateCompatibility;
1168}
1169
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001170bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1171 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1172};
1173
Vishnu Nair73908d12022-10-24 21:46:42 -07001174ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1175 bool useDrawing = state == LayerVector::StateSet::Drawing;
1176 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1177 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001178 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001179 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001180 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001181}
1182
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001183bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001184 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001185 return false;
1186 }
1187
Robert Carr6a160312021-05-17 12:08:20 -07001188 mDrawingState.sequence++;
1189 mDrawingState.shadowRadius = shadowRadius;
1190 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001191 setTransactionFlags(eTransactionNeeded);
1192 return true;
1193}
1194
Vishnu Nair6213bd92020-05-08 17:42:25 -07001195bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001196 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001197 return false;
1198 }
1199
Robert Carr6a160312021-05-17 12:08:20 -07001200 mDrawingState.sequence++;
1201 mDrawingState.fixedTransformHint = fixedTransformHint;
1202 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001203 setTransactionFlags(eTransactionNeeded);
1204 return true;
1205}
1206
John Reckcdb4ed72021-02-04 13:39:33 -05001207bool Layer::setStretchEffect(const StretchEffect& effect) {
1208 StretchEffect temp = effect;
1209 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001210 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001211 return false;
1212 }
Robert Carr6a160312021-05-17 12:08:20 -07001213 mDrawingState.sequence++;
1214 mDrawingState.stretchEffect = temp;
1215 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001216 setTransactionFlags(eTransactionNeeded);
1217 return true;
1218}
1219
John Reckc00c6692021-02-16 11:37:33 -05001220StretchEffect Layer::getStretchEffect() const {
1221 if (mDrawingState.stretchEffect.hasEffect()) {
1222 return mDrawingState.stretchEffect;
1223 }
1224
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001225 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001226 if (parent != nullptr) {
1227 auto effect = parent->getStretchEffect();
1228 if (effect.hasEffect()) {
1229 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1230 return effect;
1231 }
1232 }
1233 return StretchEffect{};
1234}
1235
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001236bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1237 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001238 return false;
1239 }
1240 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001241 mBorderWidth = width;
1242 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001243 return true;
1244}
1245
1246bool Layer::isBorderEnabled() {
1247 return mBorderEnabled;
1248}
1249
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001250float Layer::getBorderWidth() {
1251 return mBorderWidth;
1252}
1253
1254const half4& Layer::getBorderColor() {
1255 return mBorderColor;
1256}
1257
Ady Abrahama850c182021-08-04 13:04:37 -07001258bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1259 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1260 const auto frameRate = [&] {
1261 if (mDrawingState.frameRate.rate.isValid() ||
1262 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1263 return mDrawingState.frameRate;
1264 }
1265
1266 return parentFrameRate;
1267 }();
1268
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001269 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001270
1271 // The frame rate is propagated to the children
1272 bool childrenHaveFrameRate = false;
1273 for (const sp<Layer>& child : mCurrentChildren) {
1274 childrenHaveFrameRate |=
1275 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1276 }
1277
1278 // If we don't have a valid frame rate, but the children do, we set this
1279 // layer as NoVote to allow the children to control the refresh rate
1280 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1281 childrenHaveFrameRate) {
1282 *transactionNeeded |=
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001283 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001284 }
1285
1286 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1287 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001288 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001289 const auto layerVotedWithDefaultCompatibility =
1290 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1291 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1292 const auto layerVotedWithExactCompatibility =
1293 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1294 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1295 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1296}
1297
Ady Abraham60e42ea2020-03-09 19:17:31 -07001298void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001299 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001300 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001301 while (auto parent = layer->getParent()) {
1302 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001303 }
Ady Abrahama850c182021-08-04 13:04:37 -07001304 return layer;
1305 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001306
Ady Abraham60e42ea2020-03-09 19:17:31 -07001307 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001308 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001309
Ady Abrahama850c182021-08-04 13:04:37 -07001310 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001311 if (transactionNeeded) {
1312 mFlinger->setTransactionFlags(eTraversalNeeded);
1313 }
1314}
1315
Ady Abraham71c437d2020-01-31 15:56:57 -08001316bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001317 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001318 return false;
1319 }
1320
Robert Carr6a160312021-05-17 12:08:20 -07001321 mDrawingState.sequence++;
1322 mDrawingState.frameRate = frameRate;
1323 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001324
1325 updateTreeHasFrameRateVote();
1326
Steven Thomas3172e202020-01-06 19:25:30 -08001327 setTransactionFlags(eTransactionNeeded);
1328 return true;
1329}
1330
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001331void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1332 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001333 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001334
1335 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1336 // there are two transactions with the same token, the first one without a buffer and the
1337 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1338 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001339 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1340 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001341 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001342 mDrawingState.bufferSurfaceFrameTX = it->second;
1343 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1344 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1345 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001346 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001347 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001348 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1349 }
1350}
1351
1352void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1353 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001354 mDrawingState.frameTimelineInfo = info;
1355 mDrawingState.postTime = postTime;
1356 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001357 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001358
Robert Carr6a160312021-05-17 12:08:20 -07001359 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001360 bufferSurfaceFrameTX != nullptr) {
1361 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1362 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1363 // being used for BufferSurfaceFrame, don't create a new one.
1364 return;
1365 }
1366 }
1367 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1368 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1369 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001370 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1371 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001372 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001373 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001374 } else {
1375 if (it->second->getPresentState() == PresentState::Presented) {
1376 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1377 // have been from previous vsync.
1378 it->second = createSurfaceFrameForTransaction(info, postTime);
1379 }
1380 }
1381}
1382
1383void Layer::addSurfaceFrameDroppedForBuffer(
1384 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001385 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001386 surfaceFrame->setPresentState(PresentState::Dropped);
1387 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1388}
1389
1390void Layer::addSurfaceFramePresentedForBuffer(
1391 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1392 nsecs_t currentLatchTime) {
1393 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1394 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1395 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001396 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001397}
1398
1399std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1400 const FrameTimelineInfo& info, nsecs_t postTime) {
1401 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001402 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1403 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001404 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001405 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001406 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001407 // For Transactions, the post time is considered to be both queue and acquire fence time.
1408 surfaceFrame->setActualQueueTime(postTime);
1409 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001410 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1411 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001412 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001413 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001414 onSurfaceFrameCreated(surfaceFrame);
1415 return surfaceFrame;
1416}
1417
1418std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1419 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1420 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001421 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001422 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001423 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001424 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001425 // For buffers, acquire fence time will set during latch.
1426 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001427 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1428 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001429 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001430 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001431 onSurfaceFrameCreated(surfaceFrame);
1432 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001433}
1434
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001435bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001436 if (mDrawingState.frameRateForLayerTree == frameRate) {
1437 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001438 }
1439
Ady Abrahama850c182021-08-04 13:04:37 -07001440 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001441
Ady Abrahama850c182021-08-04 13:04:37 -07001442 // TODO(b/195668952): we probably don't need to dirty visible regions here
1443 // or even store frameRateForLayerTree in mDrawingState
1444 mDrawingState.sequence++;
1445 mDrawingState.modified = true;
1446 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001447
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001448 mFlinger->mScheduler
1449 ->recordLayerHistory(sequence, getLayerProps(), systemTime(),
1450 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1451 return true;
1452}
Ady Abrahama850c182021-08-04 13:04:37 -07001453
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001454bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps) {
1455 if (mDrawingState.frameRateForLayerTree == frameRate) {
1456 return false;
1457 }
1458
1459 mDrawingState.frameRateForLayerTree = frameRate;
1460 mFlinger->mScheduler
1461 ->recordLayerHistory(sequence, layerProps, systemTime(),
1462 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001463 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001464}
1465
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001466Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1467 return getDrawingState().frameRateForLayerTree;
1468}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001469
Robert Carr1f0a16a2016-10-24 16:27:39 -07001470bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001471 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001472 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001473 if (parent != nullptr && parent->isHiddenByPolicy()) {
1474 return true;
1475 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001476 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1477 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1478 if (zOrderRelativeOf != nullptr) {
1479 if (zOrderRelativeOf->isHiddenByPolicy()) {
1480 return true;
1481 }
1482 }
1483 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001484 if (CC_UNLIKELY(!isTransformValid())) {
1485 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1486 return true;
1487 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001488 return s.flags & layer_state_t::eLayerHidden;
1489}
1490
David Sodman41fdfc92017-11-06 16:09:56 -08001491uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001492 // TODO: should we do something special if mSecure is set?
1493 if (mProtectedByApp) {
1494 // need a hardware-protected path to external video sink
1495 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001496 }
Riley Andrews03414a12014-07-01 14:22:59 -07001497 if (mPotentialCursor) {
1498 usage |= GraphicBuffer::USAGE_CURSOR;
1499 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001500 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001501 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001502}
1503
Vishnu Nair71fcf912022-10-18 09:14:20 -07001504void Layer::skipReportingTransformHint() {
1505 mSkipReportingTransformHint = true;
1506}
1507
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001508void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1509 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1510 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001511 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001512
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001513 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001514}
1515
Mathias Agopian13127d82013-03-05 17:47:11 -08001516// ----------------------------------------------------------------------------
1517// debugging
1518// ----------------------------------------------------------------------------
1519
Marissa Wall61c58622018-07-18 10:12:20 -07001520// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001521gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001522 using namespace std::string_literals;
1523
Huihong Luo05539a12022-02-23 10:29:40 -08001524 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001525 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001526 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001527 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001528 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001529 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001530
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001531 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001532 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001533 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001534 info.mX = ds.transform.tx();
1535 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001536 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001537 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001538 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001539 info.mFlags = ds.flags;
1540 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001541 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001542 info.mMatrix[0][0] = ds.transform[0][0];
1543 info.mMatrix[0][1] = ds.transform[0][1];
1544 info.mMatrix[1][0] = ds.transform[1][0];
1545 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001546 {
chaviwd62d3062019-09-04 14:48:02 -07001547 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001548 if (buffer != 0) {
1549 info.mActiveBufferWidth = buffer->getWidth();
1550 info.mActiveBufferHeight = buffer->getHeight();
1551 info.mActiveBufferStride = buffer->getStride();
1552 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001553 } else {
1554 info.mActiveBufferWidth = 0;
1555 info.mActiveBufferHeight = 0;
1556 info.mActiveBufferStride = 0;
1557 info.mActiveBufferFormat = 0;
1558 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001559 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001560 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001561 info.mIsOpaque = isOpaque(ds);
1562 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001563 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001564 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001565}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001566
Yiwei Zhang5434a782018-12-05 18:06:32 -08001567void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001568 result.append(kDumpTableRowLength, '-');
1569 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001570 result.append(" Layer name\n");
1571 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001572 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001573 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001574 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001575 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001576 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001577 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1578 result.append(kDumpTableRowLength, '-');
1579 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001580}
1581
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001582void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1583 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001584 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001585 return;
1586 }
1587
Yiwei Zhang5434a782018-12-05 18:06:32 -08001588 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001589 if (mName.length() > 77) {
1590 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001591 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001592 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001593 shortened.append(mName, mName.length() - 36);
1594 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001595 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001596 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001597 }
1598
Yiwei Zhang5434a782018-12-05 18:06:32 -08001599 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001600
Alec Mourib416efd2018-09-06 21:01:59 +00001601 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001602 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001603
Chia-I Wu1e043612018-03-01 09:45:09 -08001604 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001605 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001606 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001607 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001608 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001609 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001610 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001611 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1612 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001613 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001614 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001615 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001616 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001617 const auto frameRate = getFrameRateForLayerTree();
1618 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1619 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001620 ftl::enum_string(frameRate.type).c_str(),
1621 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001622 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001623 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001624 }
Dan Stozae22aec72016-08-01 13:20:59 -07001625
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001626 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1627 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1628
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001629 result.append(kDumpTableRowLength, '-');
1630 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001631}
Dan Stozae22aec72016-08-01 13:20:59 -07001632
Yiwei Zhang5434a782018-12-05 18:06:32 -08001633void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001634 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001635}
1636
Svetoslavd85084b2014-03-20 10:28:31 -07001637void Layer::clearFrameStats() {
1638 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001639}
1640
Jamie Gennis6547ff42013-07-16 20:12:42 -07001641void Layer::logFrameStats() {
1642 mFrameTracker.logAndResetStats(mName);
1643}
1644
Svetoslavd85084b2014-03-20 10:28:31 -07001645void Layer::getFrameStats(FrameStats* outStats) const {
1646 mFrameTracker.getStats(outStats);
1647}
1648
Vishnu Nair76554eb2022-12-09 03:38:36 +00001649void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1650 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
1651 StringAppendF(&result, "Layer %s%s pid:%d uid:%d\n", getName().c_str(), hasBuffer.c_str(),
Vishnu Naircb8be502022-10-12 19:03:23 +00001652 mOwnerPid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001653}
1654
Brian Anderson5ea5e592016-12-01 16:54:33 -08001655void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001656 const int32_t layerId = getSequence();
1657 mFlinger->mTimeStats->onDestroy(layerId);
1658 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001659}
1660
Vishnu Nair787aa782023-03-17 13:46:46 -07001661size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001662 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001663 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001664 count += 1 + child->getChildrenCount();
1665 }
1666 return count;
1667}
1668
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001669void Layer::setGameModeForTree(GameMode gameMode) {
1670 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001671 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1672 gameMode =
1673 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001674 }
1675 setGameMode(gameMode);
1676 for (const sp<Layer>& child : mCurrentChildren) {
1677 child->setGameModeForTree(gameMode);
1678 }
1679}
1680
Robert Carr1f0a16a2016-10-24 16:27:39 -07001681void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001682 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001683 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001684
Robert Carr1f0a16a2016-10-24 16:27:39 -07001685 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001686 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001687 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001688 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001689}
1690
1691ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001692 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001693 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001694
Robert Carr1323c952019-01-28 18:13:27 -08001695 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001696 const auto removeResult = mCurrentChildren.remove(layer);
1697
1698 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001699 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001700 layer->updateTreeHasFrameRateVote();
1701
1702 return removeResult;
1703}
1704
Robert Carr15eae092018-03-23 13:43:53 -07001705void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001706 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001707 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001708 const float parentShadowRadius =
1709 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001710 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001711 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001712 }
1713}
1714
chaviwf1961f72017-09-18 16:41:07 -07001715bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001716 sp<Layer> newParent;
1717 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001718 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001719 if (newParent == nullptr) {
1720 ALOGE("Unable to promote Layer handle");
1721 return false;
1722 }
1723 if (newParent == this) {
1724 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1725 return false;
1726 }
1727 }
1728
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001729 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001730 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001731 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001732 }
1733
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001734 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001735 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001736 if (!newParent->isRemovedFromCurrentState()) {
1737 addToCurrentState();
1738 } else {
1739 onRemovedFromCurrentState();
1740 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001741 } else {
1742 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001743 }
1744
chaviw06178942017-07-27 10:25:59 -07001745 return true;
1746}
1747
Peiyong Lind3788632018-09-18 16:01:31 -07001748bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001749 static const mat4 identityMatrix = mat4();
1750
Robert Carr6a160312021-05-17 12:08:20 -07001751 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001752 return false;
1753 }
Robert Carr6a160312021-05-17 12:08:20 -07001754 ++mDrawingState.sequence;
1755 mDrawingState.colorTransform = matrix;
1756 mDrawingState.hasColorTransform = matrix != identityMatrix;
1757 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001758 setTransactionFlags(eTransactionNeeded);
1759 return true;
1760}
1761
chaviwf66724d2018-11-28 16:35:21 -08001762mat4 Layer::getColorTransform() const {
1763 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001764 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001765 colorTransform = parent->getColorTransform() * colorTransform;
1766 }
1767 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001768}
1769
1770bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001771 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001772 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001773 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1774 }
1775 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001776}
1777
Chia-I Wu11481472018-05-04 10:43:19 -07001778bool Layer::isLegacyDataSpace() const {
1779 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001780 return !(getDataSpace() &
1781 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1782 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001783}
1784
Robert Carr1f0a16a2016-10-24 16:27:39 -07001785void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001786 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001787}
1788
Robert Carr6a160312021-05-17 12:08:20 -07001789int32_t Layer::getZ(LayerVector::StateSet) const {
1790 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001791}
1792
Robert Carr1c5481e2019-07-01 14:42:27 -07001793bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001794 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001795 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001796 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001797}
1798
David Sodman41fdfc92017-11-06 16:09:56 -08001799__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001800 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001801 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1802 "makeTraversalList received invalid stateSet");
1803 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1804 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001805 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001806
Robert Carr29abff82017-12-04 13:51:20 -08001807 if (state.zOrderRelatives.size() == 0) {
1808 *outSkipRelativeZUsers = true;
1809 return children;
1810 }
1811
chaviwfd462612018-05-31 16:11:27 -07001812 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001813 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001814 sp<Layer> strongRelative = weakRelative.promote();
1815 if (strongRelative != nullptr) {
1816 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001817 }
1818 }
1819
Dan Stoza412903f2017-04-27 13:42:17 -07001820 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001821 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001822 continue;
1823 }
Robert Carrdb66e622017-04-10 16:55:57 -07001824 traverse.add(child);
1825 }
1826
1827 return traverse;
1828}
1829
Robert Carr1f0a16a2016-10-24 16:27:39 -07001830/**
Robert Carrdb66e622017-04-10 16:55:57 -07001831 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001832 */
Dan Stoza412903f2017-04-27 13:42:17 -07001833void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001834 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1835 // produce a new list for traversing, including our relatives, and not including our children
1836 // who are relatives of another surface. In the case that there are no relative Z,
1837 // makeTraversalList returns our children directly to avoid significant overhead.
1838 // However in this case we need to take the responsibility for filtering children which
1839 // are relatives of another surface here.
1840 bool skipRelativeZUsers = false;
1841 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001842
Robert Carr1f0a16a2016-10-24 16:27:39 -07001843 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001844 for (; i < list.size(); i++) {
1845 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001846 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1847 continue;
1848 }
1849
chaviw301b1d82019-11-06 13:15:09 -08001850 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001851 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001852 }
Dan Stoza412903f2017-04-27 13:42:17 -07001853 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001854 }
Robert Carr29abff82017-12-04 13:51:20 -08001855
Dan Stoza412903f2017-04-27 13:42:17 -07001856 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001857 for (; i < list.size(); i++) {
1858 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001859
Robert Carr29abff82017-12-04 13:51:20 -08001860 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1861 continue;
1862 }
Dan Stoza412903f2017-04-27 13:42:17 -07001863 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001864 }
1865}
1866
1867/**
Robert Carrdb66e622017-04-10 16:55:57 -07001868 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001869 */
Dan Stoza412903f2017-04-27 13:42:17 -07001870void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1871 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001872 // See traverseInZOrder for documentation.
1873 bool skipRelativeZUsers = false;
1874 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001875
Robert Carr1f0a16a2016-10-24 16:27:39 -07001876 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001877 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001878 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001879
1880 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1881 continue;
1882 }
1883
chaviw301b1d82019-11-06 13:15:09 -08001884 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001885 break;
1886 }
Dan Stoza412903f2017-04-27 13:42:17 -07001887 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001888 }
Dan Stoza412903f2017-04-27 13:42:17 -07001889 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001890 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001891 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001892
1893 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1894 continue;
1895 }
1896
Dan Stoza412903f2017-04-27 13:42:17 -07001897 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001898 }
1899}
1900
Edgar Arriaga844fa672020-01-16 14:21:42 -08001901void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1902 visitor(this);
1903 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001904 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001905 for (const sp<Layer>& child : children) {
1906 child->traverse(state, visitor);
1907 }
1908}
1909
Vishnu Nair787aa782023-03-17 13:46:46 -07001910void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
1911 for (const sp<Layer>& child : mDrawingChildren) {
1912 visitor(child.get());
1913 }
1914}
1915
chaviw4b129c22018-04-09 16:19:43 -07001916LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1917 const std::vector<Layer*>& layersInTree) {
1918 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1919 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001920 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1921 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001922 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001923
chaviwfd462612018-05-31 16:11:27 -07001924 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001925 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1926 sp<Layer> strongRelative = weakRelative.promote();
1927 // Only add relative layers that are also descendents of the top most parent of the tree.
1928 // If a relative layer is not a descendent, then it should be ignored.
1929 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1930 traverse.add(strongRelative);
1931 }
1932 }
1933
1934 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001935 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001936 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1937 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1938 // the child here since it won't be added later as a relative.
1939 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1940 childState.zOrderRelativeOf.promote().get())) {
1941 continue;
1942 }
1943 traverse.add(child);
1944 }
1945
1946 return traverse;
1947}
1948
1949void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1950 LayerVector::StateSet stateSet,
1951 const LayerVector::Visitor& visitor) {
1952 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001953
1954 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001955 for (; i < list.size(); i++) {
1956 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001957 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001958 break;
1959 }
chaviw4b129c22018-04-09 16:19:43 -07001960 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001961 }
chaviw4b129c22018-04-09 16:19:43 -07001962
chaviwa76b2712017-09-20 12:02:26 -07001963 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001964 for (; i < list.size(); i++) {
1965 const auto& relative = list[i];
1966 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001967 }
1968}
1969
chaviw4b129c22018-04-09 16:19:43 -07001970std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1971 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1972 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1973
1974 std::vector<Layer*> layersInTree = {this};
1975 for (size_t i = 0; i < children.size(); i++) {
1976 const auto& child = children[i];
1977 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1978 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1979 }
1980
1981 return layersInTree;
1982}
1983
1984void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1985 const LayerVector::Visitor& visitor) {
1986 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1987 std::sort(layersInTree.begin(), layersInTree.end());
1988 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1989}
1990
Peiyong Linefefaac2018-08-17 12:27:51 -07001991ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001992 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001993}
1994
Garfield Tan2c1782c2022-02-16 15:25:05 -08001995bool Layer::isTransformValid() const {
1996 float transformDet = getTransform().det();
1997 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1998}
1999
chaviw13fdc492017-06-27 12:40:18 -07002000half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002001 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002002
chaviw13fdc492017-06-27 12:40:18 -07002003 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2004 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002005}
Robert Carr6452f122017-03-21 10:41:29 -07002006
Vishnu Nair6213bd92020-05-08 17:42:25 -07002007ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002008 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002009 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2010 return fixedTransformHint;
2011 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002012 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002013 if (!p) return fixedTransformHint;
2014 return p->getFixedTransformHint();
2015}
2016
chaviw13fdc492017-06-27 12:40:18 -07002017half4 Layer::getColor() const {
2018 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002019 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002020}
Robert Carr6452f122017-03-21 10:41:29 -07002021
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002022int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002023 if (getDrawingState().backgroundBlurRadius == 0) {
2024 return 0;
2025 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002026
Vishnu Nair29810f72022-07-01 16:38:41 +00002027 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002028 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2029 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002030}
2031
Galia Peychevae0acf382021-04-12 21:22:34 +02002032const std::vector<BlurRegion> Layer::getBlurRegions() const {
2033 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002034 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002035 for (auto& region : regionsCopy) {
2036 region.alpha = region.alpha * layerAlpha;
2037 }
2038 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002039}
2040
Vishnu Naire14c6b32022-08-06 04:20:15 +00002041RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002042 // Get parent settings
2043 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002044 const auto& parent = mDrawingParent.promote();
2045 if (parent != nullptr) {
2046 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002047 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002048 ui::Transform t = getActiveTransform(getDrawingState());
2049 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002050 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002051 parentSettings.radius.x *= t.getScaleX();
2052 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002053 }
2054 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002055
2056 // Get layer settings
2057 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002058 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002059 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002060 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002061
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002062 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002063 // If the parent and the layer have rounded corner settings, use the parent settings if the
2064 // parent crop is entirely inside the layer crop.
2065 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2066 if (parentSettings.cropRect.left > layerCropRect.left &&
2067 parentSettings.cropRect.top > layerCropRect.top &&
2068 parentSettings.cropRect.right < layerCropRect.right &&
2069 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2070 return parentSettings;
2071 } else {
2072 return layerSettings;
2073 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002074 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002075 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002076 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002077 return parentSettings;
2078 }
2079 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002080}
2081
Robert Carr88b85e12022-03-21 15:47:35 -07002082bool Layer::findInHierarchy(const sp<Layer>& l) {
2083 if (l == this) {
2084 return true;
2085 }
2086 for (auto& child : mDrawingChildren) {
2087 if (child->findInHierarchy(l)) {
2088 return true;
2089 }
2090 }
2091 return false;
2092}
2093
Robert Carr1f0a16a2016-10-24 16:27:39 -07002094void Layer::commitChildList() {
2095 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2096 const auto& child = mCurrentChildren[i];
2097 child->commitChildList();
2098 }
2099 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002100 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002101 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2102 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2103 if (zOrderRelativeOf == nullptr) return;
2104 if (findInHierarchy(zOrderRelativeOf)) {
2105 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2106 zOrderRelativeOf->mName.c_str());
2107 ALOGE("Severing rel Z loop, potentially dangerous");
2108 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002109 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002110 }
2111 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002112}
2113
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002114
chaviw3277faf2021-05-19 16:45:23 -05002115void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002116 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002117 mDrawingState.touchableRegionCrop =
2118 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002119 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002120 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002121 setTransactionFlags(eTransactionNeeded);
2122}
2123
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002124LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002125 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002126 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002127 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2128
Vishnu Nair00b90132021-11-05 14:03:40 -07002129 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002130 writeCompositionStateToProto(layerProto);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002131 }
2132
chaviw08f3cb22020-01-13 13:17:21 -08002133 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002134 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002135 }
chaviw6d89e2d2020-01-14 14:42:01 -08002136
2137 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002138}
2139
Vishnu Nairea6ff812023-02-27 17:41:39 +00002140void Layer::writeCompositionStateToProto(LayerProto* layerProto) {
2141 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2142
2143 // Only populate for the primary display.
2144 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
2145 const auto compositionType = getCompositionType(*display);
2146 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
2147 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2148 [&]() { return layerProto->mutable_visible_region(); });
2149 }
2150}
2151
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002152void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002153 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002154 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002155 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002156 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002157 [&]() { return layerInfo->mutable_active_buffer(); });
2158 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2159 layerInfo->mutable_buffer_transform());
2160 }
2161 layerInfo->set_invalidate(contentDirty);
2162 layerInfo->set_is_protected(isProtected());
2163 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2164 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002165 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002166 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002167 layerInfo->set_corner_radius(
2168 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002169 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2170 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2171 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2172 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2173 [&]() { return layerInfo->mutable_position(); });
2174 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002175 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2176 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002177
Vishnu Nair00b90132021-11-05 14:03:40 -07002178 if (hasColorTransform()) {
2179 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002180 }
2181
Vishnu Nair60db8c02020-04-02 11:55:16 -07002182 LayerProtoHelper::writeToProto(mSourceBounds,
2183 [&]() { return layerInfo->mutable_source_bounds(); });
2184 LayerProtoHelper::writeToProto(mScreenBounds,
2185 [&]() { return layerInfo->mutable_screen_bounds(); });
2186 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2187 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2188 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002189}
2190
2191void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002192 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002193 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2194 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002195 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002196
chaviw766c9c52021-02-10 17:36:47 -08002197 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002198
Vishnu Nair00b90132021-11-05 14:03:40 -07002199 layerInfo->set_id(sequence);
2200 layerInfo->set_name(getName().c_str());
2201 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002202
Vishnu Nair00b90132021-11-05 14:03:40 -07002203 for (const auto& child : children) {
2204 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002205 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002206
Vishnu Nair00b90132021-11-05 14:03:40 -07002207 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2208 sp<Layer> strongRelative = weakRelative.promote();
2209 if (strongRelative != nullptr) {
2210 layerInfo->add_relatives(strongRelative->sequence);
2211 }
2212 }
2213
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002214 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002215 [&]() { return layerInfo->mutable_transparent_region(); });
2216
2217 layerInfo->set_layer_stack(getLayerStack().id);
2218 layerInfo->set_z(state.z);
2219
2220 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2221 return layerInfo->mutable_requested_position();
2222 });
2223
Vishnu Nair00b90132021-11-05 14:03:40 -07002224 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2225
2226 layerInfo->set_is_opaque(isOpaque(state));
2227
2228 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2229 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2230 LayerProtoHelper::writeToProto(state.color,
2231 [&]() { return layerInfo->mutable_requested_color(); });
2232 layerInfo->set_flags(state.flags);
2233
2234 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2235 layerInfo->mutable_requested_transform());
2236
2237 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2238 if (parent != nullptr) {
2239 layerInfo->set_parent(parent->sequence);
2240 } else {
2241 layerInfo->set_parent(-1);
2242 }
2243
2244 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2245 if (zOrderRelativeOf != nullptr) {
2246 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2247 } else {
2248 layerInfo->set_z_order_relative_of(-1);
2249 }
2250
2251 layerInfo->set_is_relative_of(state.isRelativeOf);
2252
2253 layerInfo->set_owner_uid(mOwnerUid);
2254
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002255 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002256 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002257 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002258 info = fillInputInfo(
2259 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002260 } else {
2261 info = state.inputInfo;
2262 }
2263
2264 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002265 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002266 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002267
Vishnu Nair00b90132021-11-05 14:03:40 -07002268 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002269 auto protoMap = layerInfo->mutable_metadata();
2270 for (const auto& entry : state.metadata.mMap) {
2271 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2272 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002273 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002274
2275 LayerProtoHelper::writeToProto(state.destinationFrame,
2276 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002277}
2278
Robert Carr2e102c92018-10-23 12:11:15 -07002279bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002280 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002281}
2282
Prabir Pradhan33da9462022-06-14 14:55:57 +00002283// Applies the given transform to the region, while protecting against overflows caused by any
2284// offsets. If applying the offset in the transform to any of the Rects in the region would result
2285// in an overflow, they are not added to the output Region.
2286static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2287 const std::string& debugWindowName) {
2288 // Round the translation using the same rounding strategy used by ui::Transform.
2289 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2290 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2291
2292 ui::Transform transformWithoutOffset = t;
2293 transformWithoutOffset.set(0.f, 0.f);
2294
2295 const Region transformed = transformWithoutOffset.transform(r);
2296
2297 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2298 Region ret;
2299 for (const auto& rect : transformed) {
2300 Rect newRect;
2301 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2302 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2303 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2304 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2305 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2306 debugWindowName.c_str());
2307 continue;
2308 }
2309 ret.orSelf(newRect);
2310 }
2311 return ret;
2312}
2313
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002314void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002315 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2316 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002317 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002318 }
2319
Vishnu Nairfed7c122023-03-18 01:54:43 +00002320 const Rect roundedFrameInDisplay = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002321 info.frameLeft = roundedFrameInDisplay.left;
2322 info.frameTop = roundedFrameInDisplay.top;
2323 info.frameRight = roundedFrameInDisplay.right;
2324 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002325
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002326 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002327 inputToLayer.set(inputBounds.left, inputBounds.top);
2328 const ui::Transform layerToScreen = getInputTransform();
2329 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002330
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002331 // InputDispatcher expects a display-to-input transform.
2332 info.transform = inputToDisplay.inverse();
2333
2334 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002335 info.touchableRegion =
2336 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002337}
2338
chaviw3277faf2021-05-19 16:45:23 -05002339void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002340 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002341 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002342 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002343 }
2344 if (p != nullptr) {
2345 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2346 }
2347}
2348
Vishnu Naira066d902021-09-13 18:40:17 -07002349gui::DropInputMode Layer::getDropInputMode() const {
2350 gui::DropInputMode mode = mDrawingState.dropInputMode;
2351 if (mode == gui::DropInputMode::ALL) {
2352 return mode;
2353 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002354 sp<Layer> parent = mDrawingParent.promote();
2355 if (parent) {
2356 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002357 if (parentMode != gui::DropInputMode::NONE) {
2358 return parentMode;
2359 }
2360 }
2361 return mode;
2362}
2363
2364void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002365 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002366 return;
2367 }
2368
2369 // Check if we need to drop input unconditionally
2370 gui::DropInputMode dropInputMode = getDropInputMode();
2371 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002372 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002373 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2374 return;
2375 }
2376
2377 // Check if we need to check if the window is obscured by parent
2378 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2379 return;
2380 }
2381
2382 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002383 sp<Layer> parent = mDrawingParent.promote();
2384 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002385 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002386 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2387 static_cast<float>(getAlpha()));
2388 }
2389
2390 // Check if the parent has cropped the buffer
2391 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2392 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002393 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002394 return;
2395 }
2396
2397 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2398 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2399 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2400 // match then the layer has not been cropped by its parents.
2401 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2402 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2403
2404 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002405 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002406 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2407 getDebugName());
2408 } else {
2409 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2410 // input if the window is obscured. This check should be done in surfaceflinger but the
2411 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2412 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002413 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002414 }
2415}
2416
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002417WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002418 if (!hasInputInfo()) {
2419 mDrawingState.inputInfo.name = getName();
2420 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2421 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002422 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002423 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002424 }
2425
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002426 const ui::Transform& displayTransform =
2427 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2428
chaviw3277faf2021-05-19 16:45:23 -05002429 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002430 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002431 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002432
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002433 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002434
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002435 if (displayArgs.transform == nullptr) {
2436 // Do not let the window receive touches if it is not associated with a valid display
2437 // transform. We still allow the window to receive keys and prevent ANRs.
2438 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2439 }
2440
Robert Carr5dc426e2020-06-10 14:29:14 -07002441 // For compatibility reasons we let layers which can receive input
2442 // receive input before they have actually submitted a buffer. Because
2443 // of this we use canReceiveInput instead of isVisible to check the
2444 // policy-visibility, ignoring the buffer state. However for layers with
2445 // hasInputInfo()==false we can use the real visibility state.
2446 // We are just using these layers for occlusion detection in
2447 // InputDispatcher, and obviously if they aren't visible they can't occlude
2448 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002449 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2450 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2451
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002452 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002453 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002454 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002455
Vishnu Nair16a938f2021-09-24 07:14:54 -07002456 // If the window will be blacked out on a display because the display does not have the secure
2457 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002458 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002459 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002460 }
2461
Vishnu Nairfed7c122023-03-18 01:54:43 +00002462 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002463 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002464 Rect inputBoundsInDisplaySpace;
2465 if (!cropLayer) {
2466 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2467 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2468 } else {
2469 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2470 inputBoundsInDisplaySpace =
2471 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2472 }
2473 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002474 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002475 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2476 Rect inputBoundsInDisplaySpace =
2477 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2478 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002479 }
2480
Winson Chunga30f7c92021-06-29 15:42:56 -07002481 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2482 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002483 if (isTrustedOverlay()) {
2484 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2485 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002486
chaviwaf87b3e2019-10-01 16:59:28 -07002487 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2488 // touches from going outside the cloned area.
2489 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002490 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002491 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2492 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002493 info.touchableRegion = info.touchableRegion.intersect(rect);
2494 }
2495 }
2496
Robert Carr720e5062018-07-30 17:45:14 -07002497 return info;
2498}
2499
Vishnu Nairfed7c122023-03-18 01:54:43 +00002500Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2501 const ui::Transform& screenToDisplay) {
2502 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2503 // frame and transform used for the layer, which determines the bounds and the coordinate space
2504 // within which the layer will receive input.
2505
2506 // Coordinate space definitions:
2507 // - display: The display device's coordinate space. Correlates to pixels on the display.
2508 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2509 // - layer: The coordinate space of this layer.
2510 // - input: The coordinate space in which this layer will receive input events. This could be
2511 // different than layer space if a surfaceInset is used, which changes the origin
2512 // of the input space.
2513
2514 // Crop the input bounds to ensure it is within the parent's bounds.
2515 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2516 const ui::Transform layerToScreen = getInputTransform();
2517 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2518 return Rect{layerToDisplay.transform(croppedInputBounds)};
2519}
2520
chaviwaf87b3e2019-10-01 16:59:28 -07002521sp<Layer> Layer::getClonedRoot() {
2522 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002523 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002524 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002525 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002526 return nullptr;
2527 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002528 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002529}
2530
Robert Carredd13602020-04-13 17:24:34 -07002531bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002532 return mDrawingState.inputInfo.token != nullptr ||
2533 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002534}
2535
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002536compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002537 const DisplayDevice* display) const {
2538 if (!display) return nullptr;
Vishnu Naird47bcee2023-02-24 18:08:51 +00002539 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2540 return display->getCompositionDisplay()->getOutputLayerForLayer(
2541 getCompositionEngineLayerFE());
2542 }
2543 sp<LayerFE> layerFE;
2544 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2545 for (auto& [p, layer] : mLayerFEs) {
2546 if (p == path) {
2547 layerFE = layer;
2548 }
2549 }
2550
2551 if (!layerFE) return nullptr;
2552 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002553}
2554
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002555Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2556 const auto outputLayer = findOutputLayerForDisplay(display);
2557 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002558}
2559
chaviwb4c6e582019-08-16 14:35:07 -07002560void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002561 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002562 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002563 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2564 mPotentialCursor = clonedFrom->mPotentialCursor;
2565 mProtectedByApp = clonedFrom->mProtectedByApp;
2566 updateCloneBufferInfo();
2567}
2568
2569void Layer::updateCloneBufferInfo() {
2570 if (!isClone() || !isClonedFromAlive()) {
2571 return;
2572 }
2573
2574 sp<Layer> clonedFrom = getClonedFrom();
2575 mBufferInfo = clonedFrom->mBufferInfo;
2576 mSidebandStream = clonedFrom->mSidebandStream;
2577 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2578 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2579 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2580
2581 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2582 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2583 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2584 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2585 // the cloned drawingState again.
2586 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2587 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2588 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2589 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2590
2591 cloneDrawingState(clonedFrom.get());
2592
2593 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2594 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2595 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2596 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002597}
chaviw74b03172019-08-19 11:09:03 -07002598
2599void Layer::updateMirrorInfo() {
2600 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2601 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2602 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2603 // that case, we want to delete the reference to the clone since we want it to get
2604 // destroyed. The root, this layer, will still be around since the client can continue
2605 // to hold a reference, but no cloned layers will be displayed.
2606 mClonedChild = nullptr;
2607 return;
2608 }
2609
2610 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2611 // If the real layer exists and is in current state, add the clone as a child of the root.
2612 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2613 // copied to drawingState for the root layer. So the clonedChild is always removed from
2614 // drawingState and then needs to be added back each traversal.
2615 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2616 addChildToDrawing(mClonedChild);
2617 }
2618
2619 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002620 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002621 mClonedChild->updateClonedRelatives(clonedLayersMap);
2622}
2623
2624void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2625 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2626 // to the clone. If the real layer is no longer alive, continue traversing the children
2627 // since we may be able to pull out other children that are still alive.
2628 if (isClonedFromAlive()) {
2629 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002630 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002631 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002632 }
2633
2634 // The clone layer may have children in drawingState since they may have been created and
2635 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2636 // that already exist, since we can just re-use them.
2637 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2638 // not updated in the regular traversal. They are skipped since the root will lose the
2639 // reference to them when it copies its currentChildren to drawing.
2640 for (sp<Layer>& child : mDrawingChildren) {
2641 child->updateClonedDrawingState(clonedLayersMap);
2642 }
2643}
2644
2645void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2646 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2647 mDrawingChildren.clear();
2648
2649 if (!isClonedFromAlive()) {
2650 return;
2651 }
2652
2653 sp<Layer> clonedFrom = getClonedFrom();
2654 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2655 if (child == mirrorRoot) {
2656 // This is to avoid cyclical mirroring.
2657 continue;
2658 }
2659 sp<Layer> clonedChild = clonedLayersMap[child];
2660 if (clonedChild == nullptr) {
2661 clonedChild = child->createClone();
2662 clonedLayersMap[child] = clonedChild;
2663 }
2664 addChildToDrawing(clonedChild);
2665 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2666 }
2667}
2668
chaviwaf87b3e2019-10-01 16:59:28 -07002669void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2670 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2671 if (cropLayer != nullptr) {
2672 if (clonedLayersMap.count(cropLayer) == 0) {
2673 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2674 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002675 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002676 } else {
2677 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2678 mDrawingState.touchableRegionCrop = clonedCropLayer;
2679 }
2680 }
2681 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2682 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002683 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002684}
2685
2686void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002687 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002688 mDrawingState.zOrderRelatives.clear();
2689
2690 if (!isClonedFromAlive()) {
2691 return;
2692 }
2693
chaviwaf87b3e2019-10-01 16:59:28 -07002694 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002695 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002696 const sp<Layer>& relative = relativeWeak.promote();
2697 if (clonedLayersMap.count(relative) > 0) {
2698 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002699 mDrawingState.zOrderRelatives.add(clonedRelative);
2700 }
2701 }
2702
2703 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2704 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2705 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2706 // still traverse the children, but the layer with the missing relativeOf will not be shown
2707 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002708 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2709 if (clonedLayersMap.count(relativeOf) > 0) {
2710 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002711 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2712 }
2713
chaviwaf87b3e2019-10-01 16:59:28 -07002714 updateClonedInputInfo(clonedLayersMap);
2715
chaviw74b03172019-08-19 11:09:03 -07002716 for (sp<Layer>& child : mDrawingChildren) {
2717 child->updateClonedRelatives(clonedLayersMap);
2718 }
2719}
2720
2721void Layer::addChildToDrawing(const sp<Layer>& layer) {
2722 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002723 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002724}
2725
Steven Thomas62a4cf82020-01-31 12:04:03 -08002726Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2727 switch (compatibility) {
2728 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2729 return FrameRateCompatibility::Default;
2730 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2731 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002732 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2733 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002734 case ANATIVEWINDOW_FRAME_RATE_MIN:
2735 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002736 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2737 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002738 default:
2739 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2740 return FrameRateCompatibility::Default;
2741 }
2742}
2743
Marin Shalamanovc5986772021-03-16 16:09:49 +01002744scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2745 switch (strategy) {
2746 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2747 return Seamlessness::OnlySeamless;
2748 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2749 return Seamlessness::SeamedAndSeamless;
2750 default:
2751 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2752 return Seamlessness::Default;
2753 }
2754}
2755
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002756bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002757 const State& s(mDrawingState);
2758 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2759 return true;
2760 }
2761
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002762 sp<Layer> parent = mDrawingParent.promote();
2763 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002764}
2765
Robert Carr6a0382d2021-07-01 15:57:17 -07002766void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2767 mClonedChild = clonedChild;
2768 mHadClonedChild = true;
2769 mFlinger->mNumClones++;
2770}
2771
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002772bool Layer::setDropInputMode(gui::DropInputMode mode) {
2773 if (mDrawingState.dropInputMode == mode) {
2774 return false;
2775 }
2776 mDrawingState.dropInputMode = mode;
2777 return true;
2778}
2779
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002780void Layer::cloneDrawingState(const Layer* from) {
2781 mDrawingState = from->mDrawingState;
2782 // Skip callback info since they are not applicable for cloned layers.
2783 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002784 // TODO (b/238781169) currently broken for mirror layers because we do not
2785 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002786 mDrawingState.callbackHandles = {};
2787}
2788
Patrick Williamsbb25f802022-08-30 23:02:34 +00002789void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2790 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002791 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002792 if (!listener) {
2793 return;
2794 }
2795 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002796 uint32_t currentMaxAcquiredBufferCount =
2797 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002798 listener->onReleaseBuffer({buffer->getId(), framenumber},
2799 releaseFence ? releaseFence : Fence::NO_FENCE,
2800 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002801}
2802
2803void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2804 // If we are displayed on multiple displays in a single composition cycle then we would
2805 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2806 // For example we can only use it if all the displays are client comp, and we need
2807 // to merge all the client comp fences. We could do this, but for now we just
2808 // disable the optimization when a layer is composed on multiple displays.
2809 if (mClearClientCompositionFenceOnLayerDisplayed) {
2810 mLastClientCompositionFence = nullptr;
2811 } else {
2812 mClearClientCompositionFenceOnLayerDisplayed = true;
2813 }
2814
2815 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2816 // buffer that was presented on this layer. The first transaction that came in this frame that
2817 // replaced the previous buffer on this layer needs this release fence, because the fence will
2818 // let the client know when that previous buffer is removed from the screen.
2819 //
2820 // Every other transaction on this layer does not need a release fence because no other
2821 // Transactions that were set on this layer this frame are going to have their preceding buffer
2822 // removed from the display this frame.
2823 //
2824 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2825 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2826 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2827 // the previous buffer will be released this frame. The third transaction also contains a
2828 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2829 // transaction will now no longer be presented so it is released immediately and the third
2830 // transaction doesn't need a previous release fence.
2831 sp<CallbackHandle> ch;
2832 for (auto& handle : mDrawingState.callbackHandles) {
2833 if (handle->releasePreviousBuffer &&
2834 mDrawingState.releaseBufferEndpoint == handle->listener) {
2835 ch = handle;
2836 break;
2837 }
2838 }
2839
2840 // Prevent tracing the same release multiple times.
2841 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2842 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2843 }
2844
2845 if (ch != nullptr) {
2846 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2847 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2848 ch->name = mName;
2849 }
2850}
2851
2852void Layer::onSurfaceFrameCreated(
2853 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2854 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2855 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2856 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2857 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002858 if (hasBufferOrSidebandStreamInDrawing()) {
2859 // Only log for layers with a buffer, since we expect the jank data to be drained for
2860 // these, while there may be no jank listeners for bufferless layers.
2861 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2862 mName.c_str());
2863 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2864 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2865 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002866 mPendingJankClassifications.pop_front();
2867 }
2868 mPendingJankClassifications.emplace_back(surfaceFrame);
2869}
2870
2871void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2872 for (const auto& handle : mDrawingState.callbackHandles) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -07002873 if (mFlinger->mLayerLifecycleManagerEnabled) {
2874 handle->transformHint = mTransformHint;
2875 } else {
2876 handle->transformHint = mSkipReportingTransformHint
2877 ? std::nullopt
2878 : std::make_optional<uint32_t>(mTransformHintLegacy);
2879 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002880 handle->dequeueReadyTime = dequeueReadyTime;
2881 handle->currentMaxAcquiredBufferCount =
2882 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2883 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2884 handle->previousReleaseCallbackId.framenumber);
2885 }
2886
2887 for (auto& handle : mDrawingState.callbackHandles) {
2888 if (handle->releasePreviousBuffer &&
2889 mDrawingState.releaseBufferEndpoint == handle->listener) {
2890 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2891 break;
2892 }
2893 }
2894
2895 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002896 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002897 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2898 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002899 mDrawingState.callbackHandles = {};
2900}
2901
2902bool Layer::willPresentCurrentTransaction() const {
2903 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2904 return (getSidebandStreamChanged() || getAutoRefresh() ||
2905 (mDrawingState.modified &&
2906 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2907}
2908
2909bool Layer::setTransform(uint32_t transform) {
2910 if (mDrawingState.bufferTransform == transform) return false;
2911 mDrawingState.bufferTransform = transform;
2912 mDrawingState.modified = true;
2913 setTransactionFlags(eTransactionNeeded);
2914 return true;
2915}
2916
2917bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2918 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2919 mDrawingState.sequence++;
2920 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2921 mDrawingState.modified = true;
2922 setTransactionFlags(eTransactionNeeded);
2923 return true;
2924}
2925
2926bool Layer::setBufferCrop(const Rect& bufferCrop) {
2927 if (mDrawingState.bufferCrop == bufferCrop) return false;
2928
2929 mDrawingState.sequence++;
2930 mDrawingState.bufferCrop = bufferCrop;
2931
2932 mDrawingState.modified = true;
2933 setTransactionFlags(eTransactionNeeded);
2934 return true;
2935}
2936
2937bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2938 if (mDrawingState.destinationFrame == destinationFrame) return false;
2939
2940 mDrawingState.sequence++;
2941 mDrawingState.destinationFrame = destinationFrame;
2942
2943 mDrawingState.modified = true;
2944 setTransactionFlags(eTransactionNeeded);
2945 return true;
2946}
2947
2948// Translate destination frame into scale and position. If a destination frame is not set, use the
2949// provided scale and position
2950bool Layer::updateGeometry() {
2951 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2952 mDrawingState.destinationFrame.isEmpty()) {
2953 // If destination frame is not set, use the requested transform set via
2954 // Layer::setPosition and Layer::setMatrix.
2955 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2956 }
2957
2958 Rect destRect = mDrawingState.destinationFrame;
2959 int32_t destW = destRect.width();
2960 int32_t destH = destRect.height();
2961 if (destRect.left < 0) {
2962 destRect.left = 0;
2963 destRect.right = destW;
2964 }
2965 if (destRect.top < 0) {
2966 destRect.top = 0;
2967 destRect.bottom = destH;
2968 }
2969
2970 if (!mDrawingState.buffer) {
2971 ui::Transform t;
2972 t.set(destRect.left, destRect.top);
2973 return assignTransform(&mDrawingState.transform, t);
2974 }
2975
2976 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2977 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2978 // Undo any transformations on the buffer.
2979 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2980 std::swap(bufferWidth, bufferHeight);
2981 }
2982 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
2983 if (mDrawingState.transformToDisplayInverse) {
2984 if (invTransform & ui::Transform::ROT_90) {
2985 std::swap(bufferWidth, bufferHeight);
2986 }
2987 }
2988
2989 float sx = destW / static_cast<float>(bufferWidth);
2990 float sy = destH / static_cast<float>(bufferHeight);
2991 ui::Transform t;
2992 t.set(sx, 0, 0, sy);
2993 t.set(destRect.left, destRect.top);
2994 return assignTransform(&mDrawingState.transform, t);
2995}
2996
2997bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
2998 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
2999 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3000 return false;
3001 }
3002
3003 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3004
3005 mDrawingState.sequence++;
3006 mDrawingState.modified = true;
3007 setTransactionFlags(eTransactionNeeded);
3008
3009 return true;
3010}
3011
3012bool Layer::setPosition(float x, float y) {
3013 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3014 return false;
3015 }
3016
3017 mRequestedTransform.set(x, y);
3018
3019 mDrawingState.sequence++;
3020 mDrawingState.modified = true;
3021 setTransactionFlags(eTransactionNeeded);
3022
3023 return true;
3024}
3025
3026bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3027 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3028 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003029 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003030 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003031 if (!buffer) {
3032 return false;
3033 }
3034
3035 const bool frameNumberChanged =
3036 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3037 const uint64_t frameNumber =
3038 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003039 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003040
3041 if (mDrawingState.buffer) {
3042 mReleasePreviousBuffer = true;
3043 if (!mBufferInfo.mBuffer ||
3044 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3045 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3046 // If mDrawingState has a buffer, and we are about to update again
3047 // before swapping to drawing state, then the first buffer will be
3048 // dropped and we should decrement the pending buffer count and
3049 // call any release buffer callbacks if set.
3050 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3051 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003052 mDrawingState.acquireFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003053 decrementPendingBufferCount();
3054 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3055 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3056 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
3057 mDrawingState.bufferSurfaceFrameTX.reset();
3058 }
3059 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3060 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3061 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003062 mLastClientCompositionFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003063 mLastClientCompositionFence = nullptr;
3064 }
Vishnu Nairc09c0232023-03-02 03:22:35 +00003065 } else {
3066 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3067 // we don't want to incorrectly classify a frame if we miss the desired present time.
3068 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003069 }
3070
liulijuneb489f62022-10-17 22:02:14 +08003071 mDrawingState.producerId = bufferData.producerId;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003072 mDrawingState.frameNumber = frameNumber;
3073 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3074 mDrawingState.buffer = std::move(buffer);
3075 mDrawingState.clientCacheId = bufferData.cachedBuffer;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003076 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3077 ? bufferData.acquireFence
3078 : Fence::NO_FENCE;
3079 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3080 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3081 // We latched this buffer unsiganled, so we need to pass the acquire fence
3082 // on the callback instead of just the acquire time, since it's unknown at
3083 // this point.
3084 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3085 } else {
3086 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3087 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003088 mDrawingState.latchedVsyncId = info.vsyncId;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003089 mDrawingState.modified = true;
3090 setTransactionFlags(eTransactionNeeded);
3091
3092 const int32_t layerId = getSequence();
3093 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3094 mOwnerUid, postTime, getGameMode());
3095 mDrawingState.desiredPresentTime = desiredPresentTime;
3096 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3097
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003098 if (mFlinger->mLegacyFrontEndEnabled) {
3099 recordLayerHistoryBufferUpdate(getLayerProps());
3100 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003101
3102 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3103
3104 if (dequeueTime && *dequeueTime != 0) {
3105 const uint64_t bufferId = mDrawingState.buffer->getId();
3106 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3107 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3108 FrameTracer::FrameEvent::DEQUEUE);
3109 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3110 FrameTracer::FrameEvent::QUEUE);
3111 }
3112
3113 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3114 return true;
3115}
3116
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003117void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3118 mDrawingState.desiredPresentTime = desiredPresentTime;
3119 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3120}
3121
3122void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps) {
3123 const nsecs_t presentTime = [&] {
3124 if (!mDrawingState.isAutoTimestamp) return mDrawingState.desiredPresentTime;
3125
3126 const auto prediction = mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3127 mDrawingState.latchedVsyncId);
3128 if (prediction.has_value()) return prediction->presentTime;
3129
3130 return static_cast<nsecs_t>(0);
3131 }();
3132 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3133 scheduler::LayerHistory::LayerUpdateType::Buffer);
3134}
3135
3136void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps) {
3137 const nsecs_t presentTime =
3138 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
3139 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3140 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3141}
3142
Patrick Williamsbb25f802022-08-30 23:02:34 +00003143bool Layer::setDataspace(ui::Dataspace dataspace) {
3144 mDrawingState.dataspaceRequested = true;
3145 if (mDrawingState.dataspace == dataspace) return false;
3146 mDrawingState.dataspace = dataspace;
3147 mDrawingState.modified = true;
3148 setTransactionFlags(eTransactionNeeded);
3149 return true;
3150}
3151
John Reck68796592023-01-25 13:47:12 -05003152bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07003153 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3154 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05003155 return false;
Sally Qi963049b2023-03-23 14:06:21 -07003156 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3157 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05003158 mDrawingState.modified = true;
3159 setTransactionFlags(eTransactionNeeded);
3160 return true;
3161}
3162
Alec Mourif4af03e2023-02-11 00:25:24 +00003163bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3164 if (mDrawingState.cachingHint == cachingHint) return false;
3165 mDrawingState.cachingHint = cachingHint;
3166 mDrawingState.modified = true;
3167 setTransactionFlags(eTransactionNeeded);
3168 return true;
3169}
3170
Patrick Williamsbb25f802022-08-30 23:02:34 +00003171bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3172 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3173 mDrawingState.hdrMetadata = hdrMetadata;
3174 mDrawingState.modified = true;
3175 setTransactionFlags(eTransactionNeeded);
3176 return true;
3177}
3178
3179bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003180 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003181 mDrawingState.surfaceDamageRegion = surfaceDamage;
3182 mDrawingState.modified = true;
3183 setTransactionFlags(eTransactionNeeded);
3184 return true;
3185}
3186
3187bool Layer::setApi(int32_t api) {
3188 if (mDrawingState.api == api) return false;
3189 mDrawingState.api = api;
3190 mDrawingState.modified = true;
3191 setTransactionFlags(eTransactionNeeded);
3192 return true;
3193}
3194
3195bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3196 if (mDrawingState.sidebandStream == sidebandStream) return false;
3197
3198 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3199 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3200 } else if (sidebandStream != nullptr) {
3201 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3202 }
3203
3204 mDrawingState.sidebandStream = sidebandStream;
3205 mDrawingState.modified = true;
3206 setTransactionFlags(eTransactionNeeded);
3207 if (!mSidebandStreamChanged.exchange(true)) {
3208 // mSidebandStreamChanged was false
3209 mFlinger->onLayerUpdate();
3210 }
3211 return true;
3212}
3213
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003214bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3215 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003216 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3217 if (handles.empty()) {
3218 mReleasePreviousBuffer = false;
3219 return false;
3220 }
3221
Pascal Muetschard81cef292023-02-06 12:18:52 +01003222 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003223 for (const auto& handle : handles) {
3224 // If this transaction set a buffer on this layer, release its previous buffer
3225 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3226
3227 // If this layer will be presented in this frame
3228 if (willPresent) {
3229 // If this transaction set an acquire fence on this layer, set its acquire time
3230 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3231 handle->frameNumber = mDrawingState.frameNumber;
3232
3233 // Store so latched time and release fence can be set
3234 mDrawingState.callbackHandles.push_back(handle);
3235
3236 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003237 // Queue this handle to be notified below.
3238 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003239 }
3240 }
3241
Pascal Muetschard81cef292023-02-06 12:18:52 +01003242 if (!remainingHandles.empty()) {
3243 // Notify the transaction completed threads these handles are done. These are only the
3244 // handles that were not added to the mDrawingState, which will be notified later.
3245 std::vector<JankData> jankData;
3246 transferAvailableJankData(remainingHandles, jankData);
3247 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3248 }
3249
Patrick Williamsbb25f802022-08-30 23:02:34 +00003250 mReleasePreviousBuffer = false;
3251 mCallbackHandleAcquireTimeOrFence = -1;
3252
3253 return willPresent;
3254}
3255
3256Rect Layer::getBufferSize(const State& /*s*/) const {
3257 // for buffer state layers we use the display frame size as the buffer size.
3258
3259 if (mBufferInfo.mBuffer == nullptr) {
3260 return Rect::INVALID_RECT;
3261 }
3262
3263 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3264 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3265
3266 // Undo any transformations on the buffer and return the result.
3267 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3268 std::swap(bufWidth, bufHeight);
3269 }
3270
3271 if (getTransformToDisplayInverse()) {
3272 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3273 if (invTransform & ui::Transform::ROT_90) {
3274 std::swap(bufWidth, bufHeight);
3275 }
3276 }
3277
3278 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3279}
3280
3281FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3282 if (mBufferInfo.mBuffer == nullptr) {
3283 return parentBounds;
3284 }
3285
3286 return getBufferSize(getDrawingState()).toFloatRect();
3287}
3288
3289bool Layer::fenceHasSignaled() const {
3290 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3291 return true;
3292 }
3293
3294 const bool fenceSignaled =
3295 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3296 if (!fenceSignaled) {
3297 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3298 TimeStats::LatchSkipReason::LateAcquire);
3299 }
3300
3301 return fenceSignaled;
3302}
3303
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003304void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003305 for (const auto& handle : mDrawingState.callbackHandles) {
3306 handle->refreshStartTime = refreshStartTime;
3307 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003308}
3309
3310void Layer::setAutoRefresh(bool autoRefresh) {
3311 mDrawingState.autoRefresh = autoRefresh;
3312}
3313
3314bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3315 // We need to update the sideband stream if the layer has both a buffer and a sideband stream.
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003316 auto* snapshot = editLayerSnapshot();
3317 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003318
3319 if (mSidebandStreamChanged.exchange(false)) {
3320 const State& s(getDrawingState());
3321 // mSidebandStreamChanged was true
3322 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003323 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003324 if (mSidebandStream != nullptr) {
3325 setTransactionFlags(eTransactionNeeded);
3326 mFlinger->setTransactionFlags(eTraversalNeeded);
3327 }
3328 recomputeVisibleRegions = true;
3329
3330 return true;
3331 }
3332 return false;
3333}
3334
3335bool Layer::hasFrameUpdate() const {
3336 const State& c(getDrawingState());
3337 return (mDrawingStateModified || mDrawingState.modified) &&
3338 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3339}
3340
Vishnu Naird47bcee2023-02-24 18:08:51 +00003341void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003342 const State& s(getDrawingState());
3343
3344 if (!s.buffer) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003345 if (bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003346 for (auto& handle : mDrawingState.callbackHandles) {
3347 handle->latchTime = latchTime;
3348 }
3349 }
3350 return;
3351 }
3352
3353 for (auto& handle : mDrawingState.callbackHandles) {
3354 if (handle->frameNumber == mDrawingState.frameNumber) {
3355 handle->latchTime = latchTime;
3356 }
3357 }
3358
3359 const int32_t layerId = getSequence();
3360 const uint64_t bufferId = mDrawingState.buffer->getId();
3361 const uint64_t frameNumber = mDrawingState.frameNumber;
3362 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3363 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3364 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3365
3366 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3367 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3368 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3369 FrameTracer::FrameEvent::LATCH);
3370
3371 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3372 if (bufferSurfaceFrame != nullptr &&
3373 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3374 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3375 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3376 // are processing the next state.
3377 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3378 mDrawingState.acquireFenceTime->getSignalTime(),
3379 latchTime);
3380 mDrawingState.bufferSurfaceFrameTX.reset();
3381 }
3382
3383 std::deque<sp<CallbackHandle>> remainingHandles;
3384 mFlinger->getTransactionCallbackInvoker()
3385 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3386 mDrawingState.callbackHandles = remainingHandles;
3387
3388 mDrawingStateModified = false;
3389}
3390
3391void Layer::gatherBufferInfo() {
3392 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3393 decrementPendingBufferCount();
3394 }
3395
3396 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3397 mBufferInfo.mBuffer = mDrawingState.buffer;
3398 mBufferInfo.mFence = mDrawingState.acquireFence;
3399 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3400 mBufferInfo.mPixelFormat =
3401 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3402 mBufferInfo.mFrameLatencyNeeded = true;
3403 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3404 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3405 mBufferInfo.mFence = mDrawingState.acquireFence;
3406 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3407 auto lastDataspace = mBufferInfo.mDataspace;
3408 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3409 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003410 mFlinger->mHdrLayerInfoChanged = true;
3411 }
Sally Qi963049b2023-03-23 14:06:21 -07003412 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3413 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05003414 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003415 }
3416 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3417 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3418 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3419 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3420 mBufferInfo.mApi = mDrawingState.api;
3421 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003422}
3423
3424Rect Layer::computeBufferCrop(const State& s) {
3425 if (s.buffer && !s.bufferCrop.isEmpty()) {
3426 Rect bufferCrop;
3427 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3428 return bufferCrop;
3429 } else if (s.buffer) {
3430 return s.buffer->getBounds();
3431 } else {
3432 return s.bufferCrop;
3433 }
3434}
3435
3436sp<Layer> Layer::createClone() {
3437 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3438 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003439 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003440 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3441 return layer;
3442}
3443
Patrick Williamsbb25f802022-08-30 23:02:34 +00003444void Layer::decrementPendingBufferCount() {
3445 int32_t pendingBuffers = --mPendingBufferTransactions;
3446 tracePendingBufferCount(pendingBuffers);
3447}
3448
3449void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3450 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3451}
3452
3453/*
3454 * We don't want to send the layer's transform to input, but rather the
3455 * parent's transform. This is because Layer's transform is
3456 * information about how the buffer is placed on screen. The parent's
3457 * transform makes more sense to send since it's information about how the
3458 * layer is placed on screen. This transform is used by input to determine
3459 * how to go from screen space back to window space.
3460 */
3461ui::Transform Layer::getInputTransform() const {
3462 if (!hasBufferOrSidebandStream()) {
3463 return getTransform();
3464 }
3465 sp<Layer> parent = mDrawingParent.promote();
3466 if (parent == nullptr) {
3467 return ui::Transform();
3468 }
3469
3470 return parent->getTransform();
3471}
3472
3473/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003474 * Returns the bounds used to fill the input frame and the touchable region.
3475 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003476 * Similar to getInputTransform, we need to update the bounds to include the transform.
3477 * This is because bounds don't include the buffer transform, where the input assumes
3478 * that's already included.
3479 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003480std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3481 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3482 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3483 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3484 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3485 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003486 }
3487
Vishnu Nairfed7c122023-03-18 01:54:43 +00003488 bool inputBoundsValid = croppedBufferSize.isValid();
3489 if (!inputBoundsValid) {
3490 /**
3491 * Input bounds are based on the layer crop or buffer size. But if we are using
3492 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3493 * we can use the parent bounds as the input bounds if the layer does not have buffer
3494 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3495 * use the parent bounds. A layer without a buffer can get input. So when a window is
3496 * initially added, its touchable region can fill its parent layer bounds and that can
3497 * have negative consequences.
3498 */
3499 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003500 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003501
3502 // Clamp surface inset to the input bounds.
3503 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3504 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3505 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3506
3507 // Apply the insets to the input bounds.
3508 inputBounds.left += xSurfaceInset;
3509 inputBounds.top += ySurfaceInset;
3510 inputBounds.right -= xSurfaceInset;
3511 inputBounds.bottom -= ySurfaceInset;
3512
3513 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003514}
3515
3516bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3517 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3518
3519 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3520 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3521 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3522 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3523 layer_state_t::eReparent;
3524
3525 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3526 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3527 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3528 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3529 layer_state_t::eInputInfoChanged;
3530
3531 if ((s.what & requiredFlags) != requiredFlags) {
3532 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3533 (s.what | requiredFlags) & ~s.what);
3534 return false;
3535 }
3536
3537 if (s.what & deniedFlags) {
3538 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3539 return false;
3540 }
3541
3542 if (s.what & allowedFlags) {
3543 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3544 }
3545
3546 if (s.what & layer_state_t::ePositionChanged) {
3547 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3548 ALOGV("%s: false [ePositionChanged changed]", __func__);
3549 return false;
3550 }
3551 }
3552
3553 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003554 if (mDrawingState.color.a != s.color.a) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003555 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3556 return false;
3557 }
3558 }
3559
3560 if (s.what & layer_state_t::eColorTransformChanged) {
3561 if (mDrawingState.colorTransform != s.colorTransform) {
3562 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3563 return false;
3564 }
3565 }
3566
3567 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003568 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003569 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3570 return false;
3571 }
3572 }
3573
3574 if (s.what & layer_state_t::eMatrixChanged) {
3575 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3576 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3577 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3578 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3579 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3580 return false;
3581 }
3582 }
3583
3584 if (s.what & layer_state_t::eCornerRadiusChanged) {
3585 if (mDrawingState.cornerRadius != s.cornerRadius) {
3586 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3587 return false;
3588 }
3589 }
3590
3591 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3592 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3593 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3594 return false;
3595 }
3596 }
3597
Vishnu Nairbbceb462022-10-10 04:52:13 +00003598 if (s.what & layer_state_t::eBufferTransformChanged) {
3599 if (mDrawingState.bufferTransform != s.bufferTransform) {
3600 ALOGV("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003601 return false;
3602 }
3603 }
3604
3605 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3606 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3607 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3608 return false;
3609 }
3610 }
3611
3612 if (s.what & layer_state_t::eCropChanged) {
3613 if (mDrawingState.crop != s.crop) {
3614 ALOGV("%s: false [eCropChanged changed]", __func__);
3615 return false;
3616 }
3617 }
3618
3619 if (s.what & layer_state_t::eDataspaceChanged) {
3620 if (mDrawingState.dataspace != s.dataspace) {
3621 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3622 return false;
3623 }
3624 }
3625
3626 if (s.what & layer_state_t::eHdrMetadataChanged) {
3627 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3628 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3629 return false;
3630 }
3631 }
3632
3633 if (s.what & layer_state_t::eSidebandStreamChanged) {
3634 if (mDrawingState.sidebandStream != s.sidebandStream) {
3635 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3636 return false;
3637 }
3638 }
3639
3640 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3641 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3642 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3643 return false;
3644 }
3645 }
3646
3647 if (s.what & layer_state_t::eShadowRadiusChanged) {
3648 if (mDrawingState.shadowRadius != s.shadowRadius) {
3649 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3650 return false;
3651 }
3652 }
3653
3654 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3655 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3656 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3657 return false;
3658 }
3659 }
3660
3661 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3662 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3663 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3664 return false;
3665 }
3666 }
3667
3668 if (s.what & layer_state_t::eStretchChanged) {
3669 StretchEffect temp = s.stretchEffect;
3670 temp.sanitize();
3671 if (mDrawingState.stretchEffect != temp) {
3672 ALOGV("%s: false [eStretchChanged changed]", __func__);
3673 return false;
3674 }
3675 }
3676
3677 if (s.what & layer_state_t::eBufferCropChanged) {
3678 if (mDrawingState.bufferCrop != s.bufferCrop) {
3679 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3680 return false;
3681 }
3682 }
3683
3684 if (s.what & layer_state_t::eDestinationFrameChanged) {
3685 if (mDrawingState.destinationFrame != s.destinationFrame) {
3686 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3687 return false;
3688 }
3689 }
3690
3691 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3692 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3693 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3694 return false;
3695 }
3696 }
3697
John Reck68796592023-01-25 13:47:12 -05003698 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07003699 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
3700 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
3701 ALOGV("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05003702 return false;
3703 }
3704 }
3705
Patrick Williamsbb25f802022-08-30 23:02:34 +00003706 ALOGV("%s: true", __func__);
3707 return true;
3708}
3709
3710bool Layer::isHdrY410() const {
3711 // pixel format is HDR Y410 masquerading as RGBA_1010102
3712 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3713 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3714 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3715}
3716
Vishnu Naire14c6b32022-08-06 04:20:15 +00003717sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003718 // 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 +00003719 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003720}
3721
Vishnu Naire14c6b32022-08-06 04:20:15 +00003722const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003723 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003724}
3725
Vishnu Naire14c6b32022-08-06 04:20:15 +00003726LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003727 return mSnapshot.get();
3728}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003729
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003730std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3731 return std::move(mSnapshot);
3732}
3733
3734void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3735 mSnapshot = std::move(snapshot);
3736}
3737
Patrick Williamsbb25f802022-08-30 23:02:34 +00003738const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003739 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003740}
3741
Patrick Williams7584c6a2022-10-29 02:10:58 +00003742sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003743 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003744 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3745 return result;
3746}
3747
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003748sp<LayerFE> Layer::getCompositionEngineLayerFE(
3749 const frontend::LayerHierarchy::TraversalPath& path) {
3750 for (auto& [p, layerFE] : mLayerFEs) {
3751 if (p == path) {
3752 return layerFE;
3753 }
3754 }
3755 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3756 mLayerFEs.emplace_back(path, layerFE);
3757 return layerFE;
3758}
3759
Patrick Williamsbb25f802022-08-30 23:02:34 +00003760void Layer::useSurfaceDamage() {
3761 if (mFlinger->mForceFullDamage) {
3762 surfaceDamageRegion = Region::INVALID_REGION;
3763 } else {
3764 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3765 }
3766}
3767
3768void Layer::useEmptyDamage() {
3769 surfaceDamageRegion.clear();
3770}
3771
3772bool Layer::isOpaque(const Layer::State& s) const {
3773 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3774 // layer's opaque flag.
3775 if (!hasSomethingToDraw()) {
3776 return false;
3777 }
3778
3779 // if the layer has the opaque flag, then we're always opaque
3780 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3781 return true;
3782 }
3783
3784 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003785 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003786 return true;
3787 }
3788
3789 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3790 return fillsColor() && getAlpha() == 1.0_hf;
3791}
3792
3793bool Layer::canReceiveInput() const {
3794 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3795}
3796
3797bool Layer::isVisible() const {
3798 if (!hasSomethingToDraw()) {
3799 return false;
3800 }
3801
3802 if (isHiddenByPolicy()) {
3803 return false;
3804 }
3805
3806 return getAlpha() > 0.0f || hasBlur();
3807}
3808
3809void Layer::onPostComposition(const DisplayDevice* display,
3810 const std::shared_ptr<FenceTime>& glDoneFence,
3811 const std::shared_ptr<FenceTime>& presentFence,
3812 const CompositorTiming& compositorTiming) {
3813 // mFrameLatencyNeeded is true when a new frame was latched for the
3814 // composition.
3815 if (!mBufferInfo.mFrameLatencyNeeded) return;
3816
3817 for (const auto& handle : mDrawingState.callbackHandles) {
3818 handle->gpuCompositionDoneFence = glDoneFence;
3819 handle->compositorTiming = compositorTiming;
3820 }
3821
3822 // Update mFrameTracker.
3823 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3824 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3825
3826 const int32_t layerId = getSequence();
3827 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3828
3829 const auto outputLayer = findOutputLayerForDisplay(display);
3830 if (outputLayer && outputLayer->requiresClientComposition()) {
3831 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3832 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3833 clientCompositionTimestamp,
3834 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3835 // Update the SurfaceFrames in the drawing state
3836 if (mDrawingState.bufferSurfaceFrameTX) {
3837 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3838 }
3839 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3840 surfaceFrame->setGpuComposition();
3841 }
3842 }
3843
3844 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3845 if (frameReadyFence->isValid()) {
3846 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3847 } else {
3848 // There was no fence for this frame, so assume that it was ready
3849 // to be presented at the desired present time.
3850 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3851 }
3852
3853 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08003854 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003855 const std::optional<Fps> renderRate =
3856 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3857
3858 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3859 const auto gameMode = getGameMode();
3860
3861 if (presentFence->isValid()) {
3862 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3863 refreshRate, renderRate, vote, gameMode);
3864 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3865 presentFence,
3866 FrameTracer::FrameEvent::PRESENT_FENCE);
3867 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3868 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3869 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003870 // The HWC doesn't support present fences, so use the present timestamp instead.
3871 const nsecs_t presentTimestamp =
3872 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3873
3874 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3875 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3876 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3877
Patrick Williamsbb25f802022-08-30 23:02:34 +00003878 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3879 refreshRate, renderRate, vote, gameMode);
3880 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3881 mCurrentFrameNumber, actualPresentTime,
3882 FrameTracer::FrameEvent::PRESENT_FENCE);
3883 mFrameTracker.setActualPresentTime(actualPresentTime);
3884 }
3885 }
3886
3887 mFrameTracker.advanceFrame();
3888 mBufferInfo.mFrameLatencyNeeded = false;
3889}
3890
3891bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003892 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
3893 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
3894}
3895
3896bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003897 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3898 getDrawingState().frameNumber);
3899
3900 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3901
3902 if (refreshRequired) {
3903 return refreshRequired;
3904 }
3905
3906 // If the head buffer's acquire fence hasn't signaled yet, return and
3907 // try again later
3908 if (!fenceHasSignaled()) {
3909 ATRACE_NAME("!fenceHasSignaled()");
3910 mFlinger->onLayerUpdate();
3911 return false;
3912 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00003913 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003914 if (mDrawingState.buffer == nullptr) {
3915 return false;
3916 }
3917
3918 // Capture the old state of the layer for comparisons later
3919 BufferInfo oldBufferInfo = mBufferInfo;
3920 const bool oldOpacity = isOpaque(mDrawingState);
3921 mPreviousFrameNumber = mCurrentFrameNumber;
3922 mCurrentFrameNumber = mDrawingState.frameNumber;
3923 gatherBufferInfo();
3924
3925 if (oldBufferInfo.mBuffer == nullptr) {
3926 // the first time we receive a buffer, we need to trigger a
3927 // geometry invalidation.
3928 recomputeVisibleRegions = true;
3929 }
3930
3931 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3932 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3933 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3934 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3935 recomputeVisibleRegions = true;
3936 }
3937
3938 if (oldBufferInfo.mBuffer != nullptr) {
3939 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3940 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3941 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3942 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3943 recomputeVisibleRegions = true;
3944 }
3945 }
3946
3947 if (oldOpacity != isOpaque(mDrawingState)) {
3948 recomputeVisibleRegions = true;
3949 }
3950
3951 return true;
3952}
3953
3954bool Layer::hasReadyFrame() const {
3955 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
3956}
3957
3958bool Layer::isProtected() const {
3959 return (mBufferInfo.mBuffer != nullptr) &&
3960 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
3961}
3962
Patrick Williamsbb25f802022-08-30 23:02:34 +00003963void Layer::latchAndReleaseBuffer() {
3964 if (hasReadyFrame()) {
3965 bool ignored = false;
3966 latchBuffer(ignored, systemTime());
3967 }
3968 releasePendingBuffer(systemTime());
3969}
3970
3971PixelFormat Layer::getPixelFormat() const {
3972 return mBufferInfo.mPixelFormat;
3973}
3974
3975bool Layer::getTransformToDisplayInverse() const {
3976 return mBufferInfo.mTransformToDisplayInverse;
3977}
3978
3979Rect Layer::getBufferCrop() const {
3980 // this is the crop rectangle that applies to the buffer
3981 // itself (as opposed to the window)
3982 if (!mBufferInfo.mCrop.isEmpty()) {
3983 // if the buffer crop is defined, we use that
3984 return mBufferInfo.mCrop;
3985 } else if (mBufferInfo.mBuffer != nullptr) {
3986 // otherwise we use the whole buffer
3987 return mBufferInfo.mBuffer->getBounds();
3988 } else {
3989 // if we don't have a buffer yet, we use an empty/invalid crop
3990 return Rect();
3991 }
3992}
3993
3994uint32_t Layer::getBufferTransform() const {
3995 return mBufferInfo.mTransform;
3996}
3997
3998ui::Dataspace Layer::getDataSpace() const {
3999 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
4000}
4001
4002ui::Dataspace Layer::getRequestedDataSpace() const {
4003 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4004}
4005
4006ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4007 ui::Dataspace updatedDataspace = dataspace;
4008 // translate legacy dataspaces to modern dataspaces
4009 switch (dataspace) {
4010 case ui::Dataspace::SRGB:
4011 updatedDataspace = ui::Dataspace::V0_SRGB;
4012 break;
4013 case ui::Dataspace::SRGB_LINEAR:
4014 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4015 break;
4016 case ui::Dataspace::JFIF:
4017 updatedDataspace = ui::Dataspace::V0_JFIF;
4018 break;
4019 case ui::Dataspace::BT601_625:
4020 updatedDataspace = ui::Dataspace::V0_BT601_625;
4021 break;
4022 case ui::Dataspace::BT601_525:
4023 updatedDataspace = ui::Dataspace::V0_BT601_525;
4024 break;
4025 case ui::Dataspace::BT709:
4026 updatedDataspace = ui::Dataspace::V0_BT709;
4027 break;
4028 default:
4029 break;
4030 }
4031
4032 return updatedDataspace;
4033}
4034
4035sp<GraphicBuffer> Layer::getBuffer() const {
4036 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4037}
4038
Vishnu Nairb76d99a2023-03-19 18:22:31 -07004039void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4040 mTransformHintLegacy = getFixedTransformHint();
4041 if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4042 mTransformHintLegacy = displayTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004043 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004044 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004045}
4046
4047const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4048 return mBufferInfo.mBuffer;
4049}
4050
4051bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004052 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004053 return false;
4054 }
4055
4056 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004057 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004058 mDrawingState.modified = true;
4059 setTransactionFlags(eTransactionNeeded);
4060 return true;
4061}
4062
4063bool Layer::fillsColor() const {
4064 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4065 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4066}
4067
4068bool Layer::hasBlur() const {
4069 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4070}
4071
Vishnu Nairba354102022-08-01 00:14:18 +00004072void Layer::updateSnapshot(bool updateGeometry) {
4073 if (!getCompositionEngineLayerFE()) {
4074 return;
4075 }
4076
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004077 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004078 if (updateGeometry) {
4079 prepareBasicGeometryCompositionState();
4080 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004081 snapshot->roundedCorner = getRoundedCornerState();
4082 snapshot->stretchEffect = getStretchEffect();
4083 snapshot->transformedBounds = mScreenBounds;
4084 if (mEffectiveShadowRadius > 0.f) {
4085 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4086
4087 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4088 // it if transparent regions are present. This may not be necessary since shadows are
4089 // typically cast by layers without transparent regions.
4090 snapshot->shadowSettings.boundaries = mBounds;
4091
4092 const float casterAlpha = snapshot->alpha;
4093 const bool casterIsOpaque =
4094 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4095
4096 // If the casting layer is translucent, we need to fill in the shadow underneath the
4097 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4098 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4099 snapshot->shadowSettings.ambientColor *= casterAlpha;
4100 snapshot->shadowSettings.spotColor *= casterAlpha;
4101 }
4102 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004103 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004104 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004105 snapshot->layerOpaqueFlagSet =
4106 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004107 snapshot->isHdrY410 = isHdrY410();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004108 sp<Layer> p = mDrawingParent.promote();
4109 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004110 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004111 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004112 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004113 }
4114 snapshot->bufferSize = getBufferSize(mDrawingState);
4115 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004116 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004117 preparePerFrameCompositionState();
4118}
4119
Vishnu Naire14c6b32022-08-06 04:20:15 +00004120void Layer::updateChildrenSnapshots(bool updateGeometry) {
4121 for (const sp<Layer>& child : mDrawingChildren) {
4122 child->updateSnapshot(updateGeometry);
4123 child->updateChildrenSnapshots(updateGeometry);
4124 }
4125}
4126
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004127void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4128 mSnapshot->layerMetadata = parentMetadata;
4129 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4130 for (const sp<Layer>& child : mDrawingChildren) {
4131 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4132 }
4133}
4134
4135void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4136 std::unordered_set<Layer*>& visited) {
4137 if (visited.find(this) != visited.end()) {
4138 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4139 return;
4140 }
4141 visited.insert(this);
4142
4143 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4144
4145 if (mDrawingState.zOrderRelatives.empty()) {
4146 return;
4147 }
4148 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4149 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4150 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4151 sp<Layer> relative = weakRelative.promote();
4152 if (!relative) {
4153 continue;
4154 }
4155 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4156 }
4157}
4158
Chavi Weingarten328a8312023-01-26 21:17:52 +00004159bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004160 TrustedPresentationListener const& listener) {
4161 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4162 mTrustedPresentationListener = listener;
4163 mTrustedPresentationThresholds = thresholds;
4164 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4165 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4166 mFlinger->mNumTrustedPresentationListeners++;
4167 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4168 mFlinger->mNumTrustedPresentationListeners--;
4169 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004170
4171 // Reset trusted presentation states to ensure we start the time again.
4172 mEnteredTrustedPresentationStateTime = -1;
4173 mLastReportedTrustedPresentationState = false;
4174 mLastComputedTrustedPresentationState = false;
4175
4176 // If there's a new trusted presentation listener, the code needs to go through the composite
4177 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4178 // we're already in the requested state.
4179 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004180}
4181
Vishnu Naira156f482023-02-22 00:23:38 +00004182void Layer::updateLastLatchTime(nsecs_t latchTime) {
4183 mLastLatchTime = latchTime;
4184}
4185
Mathias Agopian13127d82013-03-05 17:47:11 -08004186// ---------------------------------------------------------------------------
4187
Marin Shalamanov46084422020-10-13 12:33:42 +02004188std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004189 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4190 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004191}
4192
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004193} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004194
4195#if defined(__gl_h_)
4196#error "don't include gl/gl.h in this file"
4197#endif
4198
4199#if defined(__gl2_h_)
4200#error "don't include gl2/gl2.h in this file"
4201#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004202
4203// TODO(b/129481165): remove the #pragma below and fix conversion issues
4204#pragma clang diagnostic pop // ignored "-Wconversion"