blob: 9c5e5e2c87c0fc0cacaa516d44fe9cc9a7f542af [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>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080053#include <ui/DebugUtils.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000054#include <ui/FloatRect.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080055#include <ui/GraphicBuffer.h>
Sally Qia92d6d12023-08-07 15:28:30 -070056#include <ui/HdrRenderTypeUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080057#include <ui/PixelFormat.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000058#include <ui/Rect.h>
59#include <ui/Transform.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060#include <utils/Errors.h>
61#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080062#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080064#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065
Alec Mourie60041e2019-06-14 18:59:51 -070066#include <algorithm>
67#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070068#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070069#include <sstream>
70
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070071#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080072#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070073#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070074#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +000075#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000076#include "FrontEnd/LayerHandle.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080077#include "LayerProtoHelper.h"
Josh Gao194ff392022-09-08 16:19:29 -070078#include "MutexUtils.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080080#include "TimeStats/TimeStats.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070081#include "TunnelModeEnabledReporter.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070082
David Sodman41fdfc92017-11-06 16:09:56 -080083#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000084#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086namespace android {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010087namespace {
88constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000089
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000090const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000091
Patrick Williamsbb25f802022-08-30 23:02:34 +000092bool assignTransform(ui::Transform* dst, ui::Transform& from) {
93 if (*dst == from) {
94 return false;
95 }
96 *dst = from;
97 return true;
98}
99
100TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
101 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
102 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
103 const auto frameRateCompatibility = [frameRate] {
104 switch (frameRate.type) {
105 case Layer::FrameRateCompatibility::Default:
106 return FrameRateCompatibility::Default;
107 case Layer::FrameRateCompatibility::ExactOrMultiple:
108 return FrameRateCompatibility::ExactOrMultiple;
109 default:
110 return FrameRateCompatibility::Undefined;
111 }
112 }();
113
114 const auto seamlessness = [frameRate] {
115 switch (frameRate.seamlessness) {
116 case scheduler::Seamlessness::OnlySeamless:
117 return Seamlessness::ShouldBeSeamless;
118 case scheduler::Seamlessness::SeamedAndSeamless:
119 return Seamlessness::NotRequired;
120 default:
121 return Seamlessness::Undefined;
122 }
123 }();
124
125 return TimeStats::SetFrameRateVote{.frameRate = frameRate.rate.getValue(),
126 .frameRateCompatibility = frameRateCompatibility,
127 .seamlessness = seamlessness};
128}
129
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100130} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800131
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700132using namespace ftl::flag_operators;
133
Yiwei Zhang5434a782018-12-05 18:06:32 -0800134using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000135using frontend::LayerSnapshot;
136using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800137using gui::GameMode;
138using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500139using gui::WindowInfo;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800140
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700141using PresentState = frametimeline::SurfaceFrame::PresentState;
142
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700143Layer::Layer(const LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000144 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700145 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000146 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700147 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800148 mWindowType(static_cast<WindowInfo::Type>(
149 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000150 mLayerCreationFlags(args.flags),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000151 mBorderEnabled(false),
152 mTextureName(args.textureName),
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000153 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000154 ALOGV("Creating Layer %s", getDebugName());
155
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700156 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700157 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
158 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
159 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700160 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
161 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700162 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700163 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700164 mDrawingState.z = 0;
165 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700166 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700167 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700168 mDrawingState.transform.set(0, 0);
169 mDrawingState.frameNumber = 0;
Vishnu Nair63221212023-04-06 15:17:37 -0700170 mDrawingState.barrierFrameNumber = 0;
171 mDrawingState.producerId = 0;
172 mDrawingState.barrierProducerId = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700173 mDrawingState.bufferTransform = 0;
174 mDrawingState.transformToDisplayInverse = false;
Robert Carr6a160312021-05-17 12:08:20 -0700175 mDrawingState.acquireFence = sp<Fence>::make(-1);
176 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
Alec Mouri74c7ae12023-03-26 02:57:47 +0000177 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Robert Carr6a160312021-05-17 12:08:20 -0700178 mDrawingState.hdrMetadata.validTypes = 0;
179 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
180 mDrawingState.cornerRadius = 0.0f;
181 mDrawingState.backgroundBlurRadius = 0;
182 mDrawingState.api = -1;
183 mDrawingState.hasColorTransform = false;
184 mDrawingState.colorSpaceAgnostic = false;
185 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
186 mDrawingState.metadata = args.metadata;
187 mDrawingState.shadowRadius = 0.f;
188 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
189 mDrawingState.frameTimelineInfo = {};
190 mDrawingState.postTime = -1;
191 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000192 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700193 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700194 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000195 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700196
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700197 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
198 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700199 mDrawingState.color.r = -1.0_hf;
200 mDrawingState.color.g = -1.0_hf;
201 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700202 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700203
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500204 mFrameTracker.setDisplayRefreshPeriod(
205 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700206
Vishnu Naircb8be502022-10-12 19:03:23 +0000207 mOwnerUid = args.ownerUid;
208 mOwnerPid = args.ownerPid;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000209
210 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
211 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
212 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
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) {
Vishnu Nair3be61902023-04-26 19:47:29 -0700256 auto& roots = mFlinger->mLayerMirrorRoots;
257 roots.erase(std::remove(roots.begin(), roots.end(), this), roots.end());
Robert Carr6a0382d2021-07-01 15:57:17 -0700258 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000259 if (hasTrustedPresentationListener()) {
260 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000261 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000262 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700263}
264
Mathias Agopian13127d82013-03-05 17:47:11 -0800265// ---------------------------------------------------------------------------
266// callbacks
267// ---------------------------------------------------------------------------
268
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700269void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700270 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700271 return;
272 }
Robert Carr2e102c92018-10-23 12:11:15 -0700273
Robert Carr6a160312021-05-17 12:08:20 -0700274 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700275 if (strongRelative == nullptr) {
276 setZOrderRelativeOf(nullptr);
277 return;
278 }
279
280 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700281 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700282 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800283 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700284 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700285}
286
287void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700288 if (!mRemovedFromDrawingState) {
289 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700290 mFlinger->mScheduler->deregisterLayer(this);
291 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000292 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000293
Ady Abrahamd11bade2022-08-01 16:18:03 -0700294 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700295}
Chia-I Wu38512252017-05-17 14:36:16 -0700296
chaviw68d4dab2020-06-08 15:07:32 -0700297sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000298 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700299 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700300 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700301 }
302 return parent->getRootLayer();
303}
304
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700305void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700306 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
307 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700308 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700309
Josh Gao194ff392022-09-08 16:19:29 -0700310 REQUIRE_MUTEX(mFlinger->mStateLock);
311 traverse(LayerVector::StateSet::Current,
312 [&](Layer* layer) REQUIRES(layer->mFlinger->mStateLock) {
313 layer->removeFromCurrentState();
314 layer->removeRelativeZ(layersInTree);
315 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700316}
317
chaviw61626f22018-11-15 16:26:27 -0800318void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700319 if (mRemovedFromDrawingState) {
320 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700321 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700322 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700323 }
chaviw61626f22018-11-15 16:26:27 -0800324
325 for (const auto& child : mCurrentChildren) {
326 child->addToCurrentState();
327 }
328}
329
Mathias Agopian13127d82013-03-05 17:47:11 -0800330// ---------------------------------------------------------------------------
331// set-up
332// ---------------------------------------------------------------------------
333
chaviw13fdc492017-06-27 12:40:18 -0700334bool Layer::getPremultipledAlpha() const {
335 return mPremultipliedAlpha;
336}
337
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700338sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800339 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700340 if (mGetHandleCalled) {
341 ALOGE("Get handle called twice" );
342 return nullptr;
343 }
344 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700345 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000346 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800347}
348
349// ---------------------------------------------------------------------------
350// h/w composer set-up
351// ---------------------------------------------------------------------------
352
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700353static Rect reduce(const Rect& win, const Region& exclude) {
354 if (CC_LIKELY(exclude.isEmpty())) {
355 return win;
356 }
357 if (exclude.isRect()) {
358 return win.reduce(exclude.getBounds());
359 }
360 return Region(win).subtract(exclude).getBounds();
361}
362
Dan Stoza80d61162017-12-20 15:57:52 -0800363static FloatRect reduce(const FloatRect& win, const Region& exclude) {
364 if (CC_LIKELY(exclude.isEmpty())) {
365 return win;
366 }
367 // Convert through Rect (by rounding) for lack of FloatRegion
368 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
369}
370
Vishnu Nair4351ad52019-02-11 14:13:02 -0800371Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800372 if (!reduceTransparentRegion) {
373 return Rect{mScreenBounds};
374 }
375
376 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800377 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800378 // Transform to screen space.
379 bounds = t.transform(bounds);
380 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700381}
382
Vishnu Nair4351ad52019-02-11 14:13:02 -0800383FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000384 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800385 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700386}
387
Vishnu Nairf0c28512019-02-08 12:40:28 -0800388FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
389 // Subtract the transparent region and snap to the bounds.
390 return reduce(mBounds, activeTransparentRegion);
391}
392
Chavi Weingarten076acac2023-01-19 17:20:43 +0000393// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000394void Layer::updateTrustedPresentationState(const DisplayDevice* display,
395 const frontend::LayerSnapshot* snapshot,
396 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000397 if (!hasTrustedPresentationListener()) {
398 return;
399 }
400 const bool lastState = mLastComputedTrustedPresentationState;
401 mLastComputedTrustedPresentationState = false;
402
403 if (!leaveState) {
404 const auto outputLayer = findOutputLayerForDisplay(display);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000405 if (outputLayer != nullptr) {
406 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
407 Region coveredRegion =
408 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
409 mLastComputedTrustedPresentationState =
410 computeTrustedPresentationState(snapshot->geomLayerBounds,
411 snapshot->sourceBounds(), coveredRegion,
412 snapshot->transformedBounds,
413 snapshot->alpha,
414 snapshot->geomLayerTransform,
415 mTrustedPresentationThresholds);
416 } else {
417 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
418 "TrustedPresentationState",
419 getDebugName());
420 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000421 }
422 }
423 const bool newState = mLastComputedTrustedPresentationState;
424 if (lastState && !newState) {
425 // We were in the trusted presentation state, but now we left it,
426 // emit the callback if needed
427 if (mLastReportedTrustedPresentationState) {
428 mLastReportedTrustedPresentationState = false;
429 mTrustedPresentationListener.invoke(false);
430 }
431 // Reset the timer
432 mEnteredTrustedPresentationStateTime = -1;
433 } else if (!lastState && newState) {
434 // We were not in the trusted presentation state, but we entered it, begin the timer
435 // and make sure this gets called at least once more!
436 mEnteredTrustedPresentationStateTime = time_in_ms;
437 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
438 }
439
440 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
441 if (!mLastReportedTrustedPresentationState && newState &&
442 (time_in_ms - mEnteredTrustedPresentationStateTime >
443 mTrustedPresentationThresholds.stabilityRequirementMs)) {
444 mLastReportedTrustedPresentationState = true;
445 mTrustedPresentationListener.invoke(true);
446 }
447}
448
449/**
450 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
451 * of how the parameters and thresholds are interpreted. The general spirit is
452 * to produce an upper bound on the amount of the buffer which was presented.
453 */
454bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
455 const Region& coveredRegion,
456 const FloatRect& screenBounds, float alpha,
457 const ui::Transform& effectiveTransform,
458 const TrustedPresentationThresholds& thresholds) {
459 if (alpha < thresholds.minAlpha) {
460 return false;
461 }
462 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
463 return false;
464 }
465 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
466 return false;
467 }
468
469 const float sx = effectiveTransform.dsdx();
470 const float sy = effectiveTransform.dsdy();
471 float fractionRendered = std::min(sx * sy, 1.0f);
472
473 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
474 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
475 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
476
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000477 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
478 // Compute the size of all the rects since they may be disconnected.
479 float coveredSize = 0;
480 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
481 float size = rect->width() * rect->height();
482 coveredSize += size;
483 }
484
485 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000486
487 if (fractionRendered < thresholds.minFractionRendered) {
488 return false;
489 }
490
491 return true;
492}
493
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700494void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
495 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800496 const State& s(getDrawingState());
497
498 // Calculate effective layer transform
499 mEffectiveTransform = parentTransform * getActiveTransform(s);
500
Garfield Tan2c1782c2022-02-16 15:25:05 -0800501 if (CC_UNLIKELY(!isTransformValid())) {
502 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
503 getDebugName());
504 return;
505 }
506
Vishnu Nair4351ad52019-02-11 14:13:02 -0800507 // Transform parent bounds to layer space
508 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
509
Vishnu Nairc652ff82019-03-15 12:48:54 -0700510 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800511 mSourceBounds = computeSourceBounds(parentBounds);
512
513 // Calculate bounds by croping diplay frame with layer crop and parent bounds
514 FloatRect bounds = mSourceBounds;
515 const Rect layerCrop = getCrop(s);
516 if (!layerCrop.isEmpty()) {
517 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
518 }
519 bounds = bounds.intersect(parentBounds);
520
521 mBounds = bounds;
522 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700523
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700524 // Use the layer's own shadow radius if set. Otherwise get the radius from
525 // parent.
526 if (s.shadowRadius > 0.f) {
527 mEffectiveShadowRadius = s.shadowRadius;
528 } else {
529 mEffectiveShadowRadius = parentShadowRadius;
530 }
531
532 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
533 // don't pass it to its children.
534 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
535
Vishnu Nair4351ad52019-02-11 14:13:02 -0800536 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700537 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800538 }
Vishnu Nairba354102022-08-01 00:14:18 +0000539
540 if (mPotentialCursor) {
541 prepareCursorCompositionState();
542 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800543}
544
Vishnu Nair60356342018-11-13 13:00:45 -0800545Rect Layer::getCroppedBufferSize(const State& s) const {
546 Rect size = getBufferSize(s);
547 Rect crop = getCrop(s);
548 if (!crop.isEmpty() && size.isValid()) {
549 size.intersect(crop, &size);
550 } else if (!crop.isEmpty()) {
551 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700552 }
Vishnu Nair60356342018-11-13 13:00:45 -0800553 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800554}
555
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700556void Layer::setupRoundedCornersCropCoordinates(Rect win,
557 const FloatRect& roundedCornersCrop) const {
558 // Translate win by the rounded corners rect coordinates, to have all values in
559 // layer coordinate space.
560 win.left -= roundedCornersCrop.left;
561 win.right -= roundedCornersCrop.left;
562 win.top -= roundedCornersCrop.top;
563 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700564}
565
Lloyd Piquede196652020-01-22 17:29:58 -0800566void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800567 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800568 const auto alpha = static_cast<float>(getAlpha());
569 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700570 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800571
572 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
573 if (!opaque || alpha != 1.0f) {
574 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
575 : Hwc2::IComposerClient::BlendMode::COVERAGE;
576 }
577
Alec Mourif4af03e2023-02-11 00:25:24 +0000578 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000579 auto* snapshot = editLayerSnapshot();
580 snapshot->outputFilter = getOutputFilter();
581 snapshot->isVisible = isVisible();
582 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
583 snapshot->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800584
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000585 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800586 contentDirty = false;
587
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000588 snapshot->geomLayerBounds = mBounds;
589 snapshot->geomLayerTransform = getTransform();
590 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
591 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000592 snapshot->localTransform = getActiveTransform(drawingState);
593 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000594 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
595 snapshot->alpha = alpha;
596 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
597 snapshot->blurRegions = drawingState.blurRegions;
598 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800599}
600
Lloyd Piquede196652020-01-22 17:29:58 -0800601void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800602 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000603 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700604
Alec Mourif4af03e2023-02-11 00:25:24 +0000605 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000606 snapshot->geomBufferSize = getBufferSize(drawingState);
607 snapshot->geomContentCrop = getBufferCrop();
608 snapshot->geomCrop = getCrop(drawingState);
609 snapshot->geomBufferTransform = getBufferTransform();
610 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
611 snapshot->geomUsesSourceCrop = usesSourceCrop();
612 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800613
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000614 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800615 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
616 for (const auto& [key, mandatory] : supportedMetadata) {
617 const auto& genericLayerMetadataCompatibilityMap =
618 mFlinger->getGenericLayerMetadataKeyMap();
619 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
620 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
621 continue;
622 }
623 const uint32_t id = compatIter->second;
624
625 auto it = drawingState.metadata.mMap.find(id);
626 if (it == std::end(drawingState.metadata.mMap)) {
627 continue;
628 }
629
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000630 snapshot->metadata.emplace(key,
631 compositionengine::GenericLayerMetadataEntry{mandatory,
632 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800633 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800634}
David Sodmanba340492018-08-05 21:51:33 -0700635
Lloyd Piquede196652020-01-22 17:29:58 -0800636void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800637 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000638 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000639 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800640
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000641 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800642
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000643 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
644 snapshot->dataspace = getDataSpace();
645 snapshot->colorTransform = getColorTransform();
646 snapshot->colorTransformIsIdentity = !hasColorTransform();
647 snapshot->surfaceDamage = surfaceDamageRegion;
648 snapshot->hasProtectedContent = isProtected();
649 snapshot->dimmingEnabled = isDimmingEnabled();
Sally Qi963049b2023-03-23 14:06:21 -0700650 snapshot->currentHdrSdrRatio = getCurrentHdrSdrRatio();
651 snapshot->desiredHdrSdrRatio = getDesiredHdrSdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000652 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800653
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700654 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700655
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000656 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800657
658 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400659 // Rounded corners no longer force client composition, since we may use a
660 // hole punch so that the layer will appear to have rounded corners.
661 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000662 snapshot->stretchEffect.hasEffect()) {
663 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800664 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700665 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000666 snapshot->blurRegions = drawingState.blurRegions;
667 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400668
669 // Layer framerate is used in caching decisions.
670 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
671 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000672 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000673
674 if (hasBufferOrSidebandStream()) {
675 preparePerFrameBufferCompositionState();
676 } else {
677 preparePerFrameEffectsCompositionState();
678 }
679}
680
681void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000682 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000683 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000684 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000685 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
686 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000687 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
688 return;
689 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000690 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000691 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800692 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
693 snapshot->compositionType =
694 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000695 } else {
696 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000697 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
698 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000699 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
700 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
701 }
702
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000703 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000704 snapshot->acquireFence = mBufferInfo.mFence;
705 snapshot->frameNumber = mBufferInfo.mFrameNumber;
706 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000707}
708
709void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000710 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000711 auto* snapshot = editLayerSnapshot();
712 snapshot->color = getColor();
713 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000714 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800715}
716
Lloyd Piquede196652020-01-22 17:29:58 -0800717void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800718 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000719 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000720 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800721
722 // Apply the layer's transform, followed by the display's global transform
723 // Here we're guaranteed that the layer's transform preserves rects
724 Rect win = getCroppedBufferSize(drawingState);
725 // Subtract the transparent region and snap to the bounds
726 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
727 Rect frame(getTransform().transform(bounds));
728
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000729 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800730}
731
Lloyd Piquea83776c2019-01-29 18:42:32 -0800732const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700733 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800734}
735
Mathias Agopian13127d82013-03-05 17:47:11 -0800736// ---------------------------------------------------------------------------
737// drawing...
738// ---------------------------------------------------------------------------
739
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500740aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
741 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700742 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800743 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500744 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800745 }
746 if (outputLayer->getState().hwc) {
747 return (*outputLayer->getState().hwc).hwcCompositionType;
748 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500749 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800750 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800751}
752
Mathias Agopian13127d82013-03-05 17:47:11 -0800753// ----------------------------------------------------------------------------
754// local state
755// ----------------------------------------------------------------------------
756
David Sodman41fdfc92017-11-06 16:09:56 -0800757bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800758 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700759 if (s.flags & layer_state_t::eLayerSecure) {
760 return true;
761 }
762
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000763 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700764 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700765}
766
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100767void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
768 std::vector<JankData>& jankData) {
769 if (mPendingJankClassifications.empty() ||
770 !mPendingJankClassifications.front()->getJankType()) {
771 return;
772 }
773
774 bool includeJankData = false;
775 for (const auto& handle : handles) {
776 for (const auto& cb : handle->callbackIds) {
777 if (cb.includeJankData) {
778 includeJankData = true;
779 break;
780 }
781 }
782
783 if (includeJankData) {
784 jankData.reserve(mPendingJankClassifications.size());
785 break;
786 }
787 }
788
789 while (!mPendingJankClassifications.empty() &&
790 mPendingJankClassifications.front()->getJankType()) {
791 if (includeJankData) {
792 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
793 mPendingJankClassifications.front();
794 jankData.emplace_back(
795 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
796 }
797 mPendingJankClassifications.pop_front();
798 }
799}
800
Mathias Agopian13127d82013-03-05 17:47:11 -0800801// ----------------------------------------------------------------------------
802// transaction
803// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800804
Vishnu Naira156f482023-02-22 00:23:38 +0000805uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700806 ATRACE_CALL();
807
Robert Carr0758e5d2021-03-11 22:15:04 -0800808 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700809 mDrawingStateModified = mDrawingState.modified;
810 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700811
Alec Mourib416efd2018-09-06 21:01:59 +0000812 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700813
Robert Carr6a160312021-05-17 12:08:20 -0700814 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800815 // invalidate and recompute the visible regions if needed
816 flags |= Layer::eVisibleRegion;
817 }
818
Robert Carr6a160312021-05-17 12:08:20 -0700819 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800820 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000821 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800822 flags |= eVisibleRegion;
823 this->contentDirty = true;
824
825 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700826 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800827 }
828
Arthur Hung9ed43392022-05-27 06:31:57 +0000829 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
830 mFlinger->mUpdateInputInfo = true;
831 }
832
Vishnu Naira156f482023-02-22 00:23:38 +0000833 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800834
Mathias Agopian13127d82013-03-05 17:47:11 -0800835 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800836}
837
Vishnu Naira156f482023-02-22 00:23:38 +0000838void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000839 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
840 // bufferSurfaceFrameTX will be presented in latchBuffer.
841 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
842 if (surfaceFrame->getPresentState() != PresentState::Presented) {
843 // With applyPendingStates, we could end up having presented surfaceframes from previous
844 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800845 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000846 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
847 }
848 }
Robert Carr6a160312021-05-17 12:08:20 -0700849 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700850}
851
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700852uint32_t Layer::clearTransactionFlags(uint32_t mask) {
853 const auto flags = mTransactionFlags & mask;
854 mTransactionFlags &= ~mask;
855 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800856}
857
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700858void Layer::setTransactionFlags(uint32_t mask) {
859 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800860}
861
Robert Carr1f0a16a2016-10-24 16:27:39 -0700862bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
863 ssize_t idx = mCurrentChildren.indexOf(childLayer);
864 if (idx < 0) {
865 return false;
866 }
867 if (childLayer->setLayer(z)) {
868 mCurrentChildren.removeAt(idx);
869 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800870 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700871 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800872 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700873}
874
Robert Carr503c7042017-09-27 15:06:08 -0700875bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
876 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
877 ssize_t idx = mCurrentChildren.indexOf(childLayer);
878 if (idx < 0) {
879 return false;
880 }
881 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
882 mCurrentChildren.removeAt(idx);
883 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800884 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700885 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800886 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700887}
888
Robert Carrae060832016-11-28 10:51:00 -0800889bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700890 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
891 mDrawingState.sequence++;
892 mDrawingState.z = z;
893 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700894
Robert Carra70e91c2021-06-11 13:59:52 -0700895 mFlinger->mSomeChildrenChanged = true;
896
Robert Carrdb66e622017-04-10 16:55:57 -0700897 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700898 if (mDrawingState.zOrderRelativeOf != nullptr) {
899 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700900 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700901 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700902 }
chaviw606e5cf2019-03-01 10:12:10 -0800903 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700904 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800905 setTransactionFlags(eTransactionNeeded);
906 return true;
907}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700908
Robert Carrdb66e622017-04-10 16:55:57 -0700909void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700910 mDrawingState.zOrderRelatives.remove(relative);
911 mDrawingState.sequence++;
912 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700913 setTransactionFlags(eTransactionNeeded);
914}
915
916void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700917 mDrawingState.zOrderRelatives.add(relative);
918 mDrawingState.modified = true;
919 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700920 setTransactionFlags(eTransactionNeeded);
921}
922
chaviw606e5cf2019-03-01 10:12:10 -0800923void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700924 mDrawingState.zOrderRelativeOf = relativeOf;
925 mDrawingState.sequence++;
926 mDrawingState.modified = true;
927 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700928
chaviw606e5cf2019-03-01 10:12:10 -0800929 setTransactionFlags(eTransactionNeeded);
930}
931
Robert Carr503d2bd2017-12-04 15:49:47 -0800932bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000933 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700934 if (relative == nullptr) {
935 return false;
936 }
937
Robert Carr6a160312021-05-17 12:08:20 -0700938 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
939 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800940 return false;
941 }
942
Robert Carr88b85e12022-03-21 15:47:35 -0700943 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
944 (relative->mDrawingState.zOrderRelativeOf == this)) {
945 ALOGE("Detected relative layer loop between %s and %s",
946 mName.c_str(), relative->mName.c_str());
947 ALOGE("Ignoring new call to set relative layer");
948 return false;
949 }
950
Robert Carra70e91c2021-06-11 13:59:52 -0700951 mFlinger->mSomeChildrenChanged = true;
952
Robert Carr6a160312021-05-17 12:08:20 -0700953 mDrawingState.sequence++;
954 mDrawingState.modified = true;
955 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700956
Robert Carr6a160312021-05-17 12:08:20 -0700957 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700958 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700959 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700960 }
chaviw606e5cf2019-03-01 10:12:10 -0800961 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700962 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700963
964 setTransactionFlags(eTransactionNeeded);
965
966 return true;
967}
968
Winson Chunga30f7c92021-06-29 15:42:56 -0700969bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
970 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
971 mDrawingState.isTrustedOverlay = isTrustedOverlay;
972 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000973 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700974 setTransactionFlags(eTransactionNeeded);
975 return true;
976}
977
978bool Layer::isTrustedOverlay() const {
979 if (getDrawingState().isTrustedOverlay) {
980 return true;
981 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000982 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700983 return (p != nullptr) && p->isTrustedOverlay();
984}
985
Dan Stoza9e56aa02015-11-02 13:00:03 -0800986bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700987 if (mDrawingState.color.a == alpha) return false;
988 mDrawingState.sequence++;
989 mDrawingState.color.a = alpha;
990 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800991 setTransactionFlags(eTransactionNeeded);
992 return true;
993}
chaviw13fdc492017-06-27 12:40:18 -0700994
Valerie Haudd0b7572019-01-29 14:59:27 -0800995bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700996 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700997 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800998 }
Robert Carr6a160312021-05-17 12:08:20 -0700999 mDrawingState.sequence++;
1000 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -08001001 setTransactionFlags(eTransactionNeeded);
1002
Robert Carr6a160312021-05-17 12:08:20 -07001003 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001004 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001005 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001006 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001007 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08001008 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001009 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001010
Valerie Haudd0b7572019-01-29 14:59:27 -08001011 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001012 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001013 mFlinger->mLayersAdded = true;
1014 // set up SF to handle added color layer
1015 if (isRemovedFromCurrentState()) {
Josh Gao194ff392022-09-08 16:19:29 -07001016 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001017 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001018 }
1019 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001020 } else if (mDrawingState.bgColorLayer && alpha == 0) {
Josh Gao194ff392022-09-08 16:19:29 -07001021 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001022 mDrawingState.bgColorLayer->reparent(nullptr);
1023 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001024 return true;
1025 }
1026
Robert Carr6a160312021-05-17 12:08:20 -07001027 mDrawingState.bgColorLayer->setColor(color);
1028 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1029 mDrawingState.bgColorLayer->setAlpha(alpha);
1030 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001031
chaviw13fdc492017-06-27 12:40:18 -07001032 return true;
1033}
1034
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001035bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001036 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001037
Robert Carr6a160312021-05-17 12:08:20 -07001038 mDrawingState.sequence++;
1039 mDrawingState.cornerRadius = cornerRadius;
1040 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001041 setTransactionFlags(eTransactionNeeded);
1042 return true;
1043}
1044
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001045bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001046 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001047 // If we start or stop drawing blur then the layer's visibility state may change so increment
1048 // the magic sequence number.
1049 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1050 mDrawingState.sequence++;
1051 }
Robert Carr6a160312021-05-17 12:08:20 -07001052 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1053 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001054 setTransactionFlags(eTransactionNeeded);
1055 return true;
1056}
Marissa Wall61c58622018-07-18 10:12:20 -07001057
Mathias Agopian13127d82013-03-05 17:47:11 -08001058bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001059 mDrawingState.sequence++;
1060 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001061 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001062 setTransactionFlags(eTransactionNeeded);
1063 return true;
1064}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001065
Lucas Dupinc3800b82020-10-02 16:24:48 -07001066bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001067 // If we start or stop drawing blur then the layer's visibility state may change so increment
1068 // the magic sequence number.
1069 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1070 mDrawingState.sequence++;
1071 }
Robert Carr6a160312021-05-17 12:08:20 -07001072 mDrawingState.blurRegions = blurRegions;
1073 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001074 setTransactionFlags(eTransactionNeeded);
1075 return true;
1076}
1077
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001078bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001079 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1080 if (mDrawingState.flags == newFlags) return false;
1081 mDrawingState.sequence++;
1082 mDrawingState.flags = newFlags;
1083 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001084 setTransactionFlags(eTransactionNeeded);
1085 return true;
1086}
Robert Carr99e27f02016-06-16 15:18:02 -07001087
chaviw25714502021-02-11 10:01:08 -08001088bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001089 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001090 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001091 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001092
Robert Carr6a160312021-05-17 12:08:20 -07001093 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001094 setTransactionFlags(eTransactionNeeded);
1095 return true;
1096}
Robert Carr8d5227b2017-03-16 15:41:03 -07001097
Evan Roskyef876c92019-01-25 17:46:06 -08001098bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001099 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1100 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001101 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001102 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001103}
1104
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001105bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001106 if (mDrawingState.layerStack == layerStack) return false;
1107 mDrawingState.sequence++;
1108 mDrawingState.layerStack = layerStack;
1109 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001110 setTransactionFlags(eTransactionNeeded);
1111 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001112}
1113
Peiyong Linc502cb72019-03-01 15:00:23 -08001114bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001115 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001116 return false;
1117 }
Robert Carr6a160312021-05-17 12:08:20 -07001118 mDrawingState.sequence++;
1119 mDrawingState.colorSpaceAgnostic = agnostic;
1120 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001121 setTransactionFlags(eTransactionNeeded);
1122 return true;
1123}
1124
Sally Qi81d95e62022-03-21 19:41:33 -07001125bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1126 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1127
1128 mDrawingState.sequence++;
1129 mDrawingState.dimmingEnabled = dimmingEnabled;
1130 mDrawingState.modified = true;
1131 setTransactionFlags(eTransactionNeeded);
1132 return true;
1133}
1134
Ana Krulecc84d09b2019-11-02 23:10:29 +01001135bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001136 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1137 mDrawingState.frameRateSelectionPriority = priority;
1138 mDrawingState.sequence++;
1139 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001140 setTransactionFlags(eTransactionNeeded);
1141 return true;
1142}
1143
1144int32_t Layer::getFrameRateSelectionPriority() const {
1145 // Check if layer has priority set.
1146 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1147 return mDrawingState.frameRateSelectionPriority;
1148 }
1149 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001150 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001151 if (parent != nullptr) {
1152 return parent->getFrameRateSelectionPriority();
1153 }
1154
1155 return Layer::PRIORITY_UNSET;
1156}
1157
Andy Labrada096227e2022-06-15 16:58:11 +00001158bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1159 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1160 mDrawingState.defaultFrameRateCompatibility = compatibility;
1161 mDrawingState.modified = true;
1162 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1163 setTransactionFlags(eTransactionNeeded);
1164 return true;
1165}
1166
1167scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1168 return mDrawingState.defaultFrameRateCompatibility;
1169}
1170
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001171bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1172 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1173};
1174
Vishnu Nair73908d12022-10-24 21:46:42 -07001175ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1176 bool useDrawing = state == LayerVector::StateSet::Drawing;
1177 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1178 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001179 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001180 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001181 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001182}
1183
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001184bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001185 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001186 return false;
1187 }
1188
Robert Carr6a160312021-05-17 12:08:20 -07001189 mDrawingState.sequence++;
1190 mDrawingState.shadowRadius = shadowRadius;
1191 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001192 setTransactionFlags(eTransactionNeeded);
1193 return true;
1194}
1195
Vishnu Nair6213bd92020-05-08 17:42:25 -07001196bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001197 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001198 return false;
1199 }
1200
Robert Carr6a160312021-05-17 12:08:20 -07001201 mDrawingState.sequence++;
1202 mDrawingState.fixedTransformHint = fixedTransformHint;
1203 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001204 setTransactionFlags(eTransactionNeeded);
1205 return true;
1206}
1207
John Reckcdb4ed72021-02-04 13:39:33 -05001208bool Layer::setStretchEffect(const StretchEffect& effect) {
1209 StretchEffect temp = effect;
1210 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001211 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001212 return false;
1213 }
Robert Carr6a160312021-05-17 12:08:20 -07001214 mDrawingState.sequence++;
1215 mDrawingState.stretchEffect = temp;
1216 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001217 setTransactionFlags(eTransactionNeeded);
1218 return true;
1219}
1220
John Reckc00c6692021-02-16 11:37:33 -05001221StretchEffect Layer::getStretchEffect() const {
1222 if (mDrawingState.stretchEffect.hasEffect()) {
1223 return mDrawingState.stretchEffect;
1224 }
1225
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001226 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001227 if (parent != nullptr) {
1228 auto effect = parent->getStretchEffect();
1229 if (effect.hasEffect()) {
1230 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1231 return effect;
1232 }
1233 }
1234 return StretchEffect{};
1235}
1236
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001237bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1238 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001239 return false;
1240 }
1241 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001242 mBorderWidth = width;
1243 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001244 return true;
1245}
1246
1247bool Layer::isBorderEnabled() {
1248 return mBorderEnabled;
1249}
1250
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001251float Layer::getBorderWidth() {
1252 return mBorderWidth;
1253}
1254
1255const half4& Layer::getBorderColor() {
1256 return mBorderColor;
1257}
1258
Ady Abrahama850c182021-08-04 13:04:37 -07001259bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1260 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1261 const auto frameRate = [&] {
1262 if (mDrawingState.frameRate.rate.isValid() ||
1263 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1264 return mDrawingState.frameRate;
1265 }
1266
1267 return parentFrameRate;
1268 }();
1269
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001270 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001271
1272 // The frame rate is propagated to the children
1273 bool childrenHaveFrameRate = false;
1274 for (const sp<Layer>& child : mCurrentChildren) {
1275 childrenHaveFrameRate |=
1276 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1277 }
1278
1279 // If we don't have a valid frame rate, but the children do, we set this
1280 // layer as NoVote to allow the children to control the refresh rate
1281 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1282 childrenHaveFrameRate) {
1283 *transactionNeeded |=
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001284 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001285 }
1286
1287 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1288 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001289 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001290 const auto layerVotedWithDefaultCompatibility =
1291 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1292 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1293 const auto layerVotedWithExactCompatibility =
1294 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1295 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1296 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1297}
1298
Ady Abraham60e42ea2020-03-09 19:17:31 -07001299void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001300 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001301 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001302 while (auto parent = layer->getParent()) {
1303 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001304 }
Ady Abrahama850c182021-08-04 13:04:37 -07001305 return layer;
1306 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001307
Ady Abraham60e42ea2020-03-09 19:17:31 -07001308 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001309 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001310
Ady Abrahama850c182021-08-04 13:04:37 -07001311 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001312 if (transactionNeeded) {
1313 mFlinger->setTransactionFlags(eTraversalNeeded);
1314 }
1315}
1316
Ady Abraham71c437d2020-01-31 15:56:57 -08001317bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001318 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001319 return false;
1320 }
1321
Robert Carr6a160312021-05-17 12:08:20 -07001322 mDrawingState.sequence++;
1323 mDrawingState.frameRate = frameRate;
1324 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001325
1326 updateTreeHasFrameRateVote();
1327
Steven Thomas3172e202020-01-06 19:25:30 -08001328 setTransactionFlags(eTransactionNeeded);
1329 return true;
1330}
1331
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001332void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1333 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001334 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001335
1336 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1337 // there are two transactions with the same token, the first one without a buffer and the
1338 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1339 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001340 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1341 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001342 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001343 mDrawingState.bufferSurfaceFrameTX = it->second;
1344 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1345 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1346 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001347 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001348 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001349 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1350 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001351
1352 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001353}
1354
1355void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1356 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001357 mDrawingState.frameTimelineInfo = info;
1358 mDrawingState.postTime = postTime;
1359 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001360 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001361
Robert Carr6a160312021-05-17 12:08:20 -07001362 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001363 bufferSurfaceFrameTX != nullptr) {
1364 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1365 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1366 // being used for BufferSurfaceFrame, don't create a new one.
1367 return;
1368 }
1369 }
1370 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1371 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1372 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001373 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1374 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001375 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001376 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001377 } else {
1378 if (it->second->getPresentState() == PresentState::Presented) {
1379 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1380 // have been from previous vsync.
1381 it->second = createSurfaceFrameForTransaction(info, postTime);
1382 }
1383 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001384
1385 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001386}
1387
1388void Layer::addSurfaceFrameDroppedForBuffer(
Ady Abraham5a3e3562023-06-07 10:32:08 -07001389 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t dropTime) {
1390 surfaceFrame->setDropTime(dropTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001391 surfaceFrame->setPresentState(PresentState::Dropped);
1392 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1393}
1394
1395void Layer::addSurfaceFramePresentedForBuffer(
1396 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1397 nsecs_t currentLatchTime) {
1398 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1399 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1400 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001401 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001402}
1403
1404std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1405 const FrameTimelineInfo& info, nsecs_t postTime) {
1406 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001407 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1408 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001409 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001410 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001411 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001412 // For Transactions, the post time is considered to be both queue and acquire fence time.
1413 surfaceFrame->setActualQueueTime(postTime);
1414 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001415 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1416 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001417 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001418 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001419 onSurfaceFrameCreated(surfaceFrame);
1420 return surfaceFrame;
1421}
1422
1423std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1424 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1425 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001426 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001427 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001428 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001429 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001430 // For buffers, acquire fence time will set during latch.
1431 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001432 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1433 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001434 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001435 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001436 onSurfaceFrameCreated(surfaceFrame);
1437 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001438}
1439
Ady Abraham5a3e3562023-06-07 10:32:08 -07001440void Layer::setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
1441 std::string debugName) {
1442 if (info.skippedFrameVsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
1443 return;
1444 }
1445
1446 FrameTimelineInfo skippedFrameTimelineInfo = info;
1447 skippedFrameTimelineInfo.vsyncId = info.skippedFrameVsyncId;
1448
1449 auto surfaceFrame =
1450 mFlinger->mFrameTimeline->createSurfaceFrameForToken(skippedFrameTimelineInfo,
1451 mOwnerPid, mOwnerUid,
1452 getSequence(), mName, debugName,
1453 /*isBuffer*/ false, getGameMode());
1454 surfaceFrame->setActualStartTime(skippedFrameTimelineInfo.skippedFrameStartTimeNanos);
1455 // For Transactions, the post time is considered to be both queue and acquire fence time.
1456 surfaceFrame->setActualQueueTime(postTime);
1457 surfaceFrame->setAcquireFenceTime(postTime);
1458 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1459 if (fps) {
1460 surfaceFrame->setRenderRate(*fps);
1461 }
1462 onSurfaceFrameCreated(surfaceFrame);
1463 addSurfaceFrameDroppedForBuffer(surfaceFrame, postTime);
1464}
1465
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001466bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001467 if (mDrawingState.frameRateForLayerTree == frameRate) {
1468 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001469 }
1470
Ady Abrahama850c182021-08-04 13:04:37 -07001471 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001472
Ady Abrahama850c182021-08-04 13:04:37 -07001473 // TODO(b/195668952): we probably don't need to dirty visible regions here
1474 // or even store frameRateForLayerTree in mDrawingState
1475 mDrawingState.sequence++;
1476 mDrawingState.modified = true;
1477 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001478
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001479 mFlinger->mScheduler
1480 ->recordLayerHistory(sequence, getLayerProps(), systemTime(),
1481 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1482 return true;
1483}
Ady Abrahama850c182021-08-04 13:04:37 -07001484
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001485bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps) {
1486 if (mDrawingState.frameRateForLayerTree == frameRate) {
1487 return false;
1488 }
1489
1490 mDrawingState.frameRateForLayerTree = frameRate;
1491 mFlinger->mScheduler
1492 ->recordLayerHistory(sequence, layerProps, systemTime(),
1493 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001494 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001495}
1496
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001497Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1498 return getDrawingState().frameRateForLayerTree;
1499}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001500
Robert Carr1f0a16a2016-10-24 16:27:39 -07001501bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001502 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001503 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001504 if (parent != nullptr && parent->isHiddenByPolicy()) {
1505 return true;
1506 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001507 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1508 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1509 if (zOrderRelativeOf != nullptr) {
1510 if (zOrderRelativeOf->isHiddenByPolicy()) {
1511 return true;
1512 }
1513 }
1514 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001515 if (CC_UNLIKELY(!isTransformValid())) {
1516 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1517 return true;
1518 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001519 return s.flags & layer_state_t::eLayerHidden;
1520}
1521
David Sodman41fdfc92017-11-06 16:09:56 -08001522uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001523 // TODO: should we do something special if mSecure is set?
1524 if (mProtectedByApp) {
1525 // need a hardware-protected path to external video sink
1526 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001527 }
Riley Andrews03414a12014-07-01 14:22:59 -07001528 if (mPotentialCursor) {
1529 usage |= GraphicBuffer::USAGE_CURSOR;
1530 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001531 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001532 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001533}
1534
Vishnu Nair71fcf912022-10-18 09:14:20 -07001535void Layer::skipReportingTransformHint() {
1536 mSkipReportingTransformHint = true;
1537}
1538
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001539void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1540 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1541 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001542 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001543
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001544 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001545}
1546
Mathias Agopian13127d82013-03-05 17:47:11 -08001547// ----------------------------------------------------------------------------
1548// debugging
1549// ----------------------------------------------------------------------------
1550
Marissa Wall61c58622018-07-18 10:12:20 -07001551// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001552gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001553 using namespace std::string_literals;
1554
Huihong Luo05539a12022-02-23 10:29:40 -08001555 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001556 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001557 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001558 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001559 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001560 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001561
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001562 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001563 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001564 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001565 info.mX = ds.transform.tx();
1566 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001567 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001568 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001569 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001570 info.mFlags = ds.flags;
1571 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001572 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001573 info.mMatrix[0][0] = ds.transform[0][0];
1574 info.mMatrix[0][1] = ds.transform[0][1];
1575 info.mMatrix[1][0] = ds.transform[1][0];
1576 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001577 {
chaviwd62d3062019-09-04 14:48:02 -07001578 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001579 if (buffer != 0) {
1580 info.mActiveBufferWidth = buffer->getWidth();
1581 info.mActiveBufferHeight = buffer->getHeight();
1582 info.mActiveBufferStride = buffer->getStride();
1583 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001584 } else {
1585 info.mActiveBufferWidth = 0;
1586 info.mActiveBufferHeight = 0;
1587 info.mActiveBufferStride = 0;
1588 info.mActiveBufferFormat = 0;
1589 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001590 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001591 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001592 info.mIsOpaque = isOpaque(ds);
1593 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001594 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001595 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001596}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001597
Yiwei Zhang5434a782018-12-05 18:06:32 -08001598void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001599 result.append(kDumpTableRowLength, '-');
1600 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001601 result.append(" Layer name\n");
1602 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001603 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001604 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001605 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001606 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001607 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001608 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1609 result.append(kDumpTableRowLength, '-');
1610 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001611}
1612
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001613void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1614 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001615 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001616 return;
1617 }
1618
Yiwei Zhang5434a782018-12-05 18:06:32 -08001619 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001620 if (mName.length() > 77) {
1621 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001622 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001623 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001624 shortened.append(mName, mName.length() - 36);
1625 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001626 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001627 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001628 }
1629
Yiwei Zhang5434a782018-12-05 18:06:32 -08001630 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001631
Alec Mourib416efd2018-09-06 21:01:59 +00001632 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001633 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001634
Chia-I Wu1e043612018-03-01 09:45:09 -08001635 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001636 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001637 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001638 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001639 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001640 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001641 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001642 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1643 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001644 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001645 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001646 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001647 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001648 const auto frameRate = getFrameRateForLayerTree();
1649 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1650 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001651 ftl::enum_string(frameRate.type).c_str(),
1652 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001653 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001654 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001655 }
Dan Stozae22aec72016-08-01 13:20:59 -07001656
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001657 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1658 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1659
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001660 result.append(kDumpTableRowLength, '-');
1661 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001662}
Dan Stozae22aec72016-08-01 13:20:59 -07001663
Yiwei Zhang5434a782018-12-05 18:06:32 -08001664void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001665 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001666}
1667
Svetoslavd85084b2014-03-20 10:28:31 -07001668void Layer::clearFrameStats() {
1669 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001670}
1671
Jamie Gennis6547ff42013-07-16 20:12:42 -07001672void Layer::logFrameStats() {
1673 mFrameTracker.logAndResetStats(mName);
1674}
1675
Svetoslavd85084b2014-03-20 10:28:31 -07001676void Layer::getFrameStats(FrameStats* outStats) const {
1677 mFrameTracker.getStats(outStats);
1678}
1679
Vishnu Nair76554eb2022-12-09 03:38:36 +00001680void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1681 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
Vishnu Nair3be61902023-04-26 19:47:29 -07001682 StringAppendF(&result, "Layer %s%s pid:%d uid:%d%s\n", getName().c_str(), hasBuffer.c_str(),
1683 mOwnerPid, mOwnerUid, isHandleAlive() ? " handleAlive" : "");
Vishnu Nair0f085c62019-08-30 08:49:12 -07001684}
1685
Brian Anderson5ea5e592016-12-01 16:54:33 -08001686void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001687 const int32_t layerId = getSequence();
1688 mFlinger->mTimeStats->onDestroy(layerId);
1689 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001690}
1691
Vishnu Nair787aa782023-03-17 13:46:46 -07001692size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001693 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001694 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001695 count += 1 + child->getChildrenCount();
1696 }
1697 return count;
1698}
1699
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001700void Layer::setGameModeForTree(GameMode gameMode) {
1701 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001702 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1703 gameMode =
1704 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001705 }
1706 setGameMode(gameMode);
1707 for (const sp<Layer>& child : mCurrentChildren) {
1708 child->setGameModeForTree(gameMode);
1709 }
1710}
1711
Robert Carr1f0a16a2016-10-24 16:27:39 -07001712void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001713 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001714 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001715
Robert Carr1f0a16a2016-10-24 16:27:39 -07001716 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001717 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001718 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001719 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001720}
1721
1722ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001723 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001724 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001725
Robert Carr1323c952019-01-28 18:13:27 -08001726 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001727 const auto removeResult = mCurrentChildren.remove(layer);
1728
1729 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001730 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001731 layer->updateTreeHasFrameRateVote();
1732
1733 return removeResult;
1734}
1735
Robert Carr15eae092018-03-23 13:43:53 -07001736void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001737 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001738 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001739 const float parentShadowRadius =
1740 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001741 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001742 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001743 }
1744}
1745
chaviwf1961f72017-09-18 16:41:07 -07001746bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001747 sp<Layer> newParent;
1748 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001749 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001750 if (newParent == nullptr) {
1751 ALOGE("Unable to promote Layer handle");
1752 return false;
1753 }
1754 if (newParent == this) {
1755 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1756 return false;
1757 }
1758 }
1759
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001760 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001761 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001762 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001763 }
1764
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001765 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001766 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001767 if (!newParent->isRemovedFromCurrentState()) {
1768 addToCurrentState();
1769 } else {
1770 onRemovedFromCurrentState();
1771 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001772 } else {
1773 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001774 }
1775
chaviw06178942017-07-27 10:25:59 -07001776 return true;
1777}
1778
Peiyong Lind3788632018-09-18 16:01:31 -07001779bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001780 static const mat4 identityMatrix = mat4();
1781
Robert Carr6a160312021-05-17 12:08:20 -07001782 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001783 return false;
1784 }
Robert Carr6a160312021-05-17 12:08:20 -07001785 ++mDrawingState.sequence;
1786 mDrawingState.colorTransform = matrix;
1787 mDrawingState.hasColorTransform = matrix != identityMatrix;
1788 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001789 setTransactionFlags(eTransactionNeeded);
1790 return true;
1791}
1792
chaviwf66724d2018-11-28 16:35:21 -08001793mat4 Layer::getColorTransform() const {
1794 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001795 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001796 colorTransform = parent->getColorTransform() * colorTransform;
1797 }
1798 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001799}
1800
1801bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001802 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001803 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001804 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1805 }
1806 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001807}
1808
Chia-I Wu11481472018-05-04 10:43:19 -07001809bool Layer::isLegacyDataSpace() const {
1810 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001811 return !(getDataSpace() &
1812 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1813 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001814}
1815
Robert Carr1f0a16a2016-10-24 16:27:39 -07001816void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001817 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001818}
1819
Robert Carr6a160312021-05-17 12:08:20 -07001820int32_t Layer::getZ(LayerVector::StateSet) const {
1821 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001822}
1823
Robert Carr1c5481e2019-07-01 14:42:27 -07001824bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001825 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001826 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001827 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001828}
1829
David Sodman41fdfc92017-11-06 16:09:56 -08001830__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001831 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001832 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1833 "makeTraversalList received invalid stateSet");
1834 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1835 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001836 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001837
Robert Carr29abff82017-12-04 13:51:20 -08001838 if (state.zOrderRelatives.size() == 0) {
1839 *outSkipRelativeZUsers = true;
1840 return children;
1841 }
1842
chaviwfd462612018-05-31 16:11:27 -07001843 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001844 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001845 sp<Layer> strongRelative = weakRelative.promote();
1846 if (strongRelative != nullptr) {
1847 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001848 }
1849 }
1850
Dan Stoza412903f2017-04-27 13:42:17 -07001851 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001852 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001853 continue;
1854 }
Robert Carrdb66e622017-04-10 16:55:57 -07001855 traverse.add(child);
1856 }
1857
1858 return traverse;
1859}
1860
Robert Carr1f0a16a2016-10-24 16:27:39 -07001861/**
Robert Carrdb66e622017-04-10 16:55:57 -07001862 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001863 */
Dan Stoza412903f2017-04-27 13:42:17 -07001864void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001865 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1866 // produce a new list for traversing, including our relatives, and not including our children
1867 // who are relatives of another surface. In the case that there are no relative Z,
1868 // makeTraversalList returns our children directly to avoid significant overhead.
1869 // However in this case we need to take the responsibility for filtering children which
1870 // are relatives of another surface here.
1871 bool skipRelativeZUsers = false;
1872 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001873
Robert Carr1f0a16a2016-10-24 16:27:39 -07001874 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001875 for (; i < list.size(); i++) {
1876 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001877 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1878 continue;
1879 }
1880
chaviw301b1d82019-11-06 13:15:09 -08001881 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001882 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001883 }
Dan Stoza412903f2017-04-27 13:42:17 -07001884 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001885 }
Robert Carr29abff82017-12-04 13:51:20 -08001886
Dan Stoza412903f2017-04-27 13:42:17 -07001887 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001888 for (; i < list.size(); i++) {
1889 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001890
Robert Carr29abff82017-12-04 13:51:20 -08001891 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1892 continue;
1893 }
Dan Stoza412903f2017-04-27 13:42:17 -07001894 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001895 }
1896}
1897
1898/**
Robert Carrdb66e622017-04-10 16:55:57 -07001899 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001900 */
Dan Stoza412903f2017-04-27 13:42:17 -07001901void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1902 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001903 // See traverseInZOrder for documentation.
1904 bool skipRelativeZUsers = false;
1905 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001906
Robert Carr1f0a16a2016-10-24 16:27:39 -07001907 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001908 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001909 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001910
1911 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1912 continue;
1913 }
1914
chaviw301b1d82019-11-06 13:15:09 -08001915 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001916 break;
1917 }
Dan Stoza412903f2017-04-27 13:42:17 -07001918 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001919 }
Dan Stoza412903f2017-04-27 13:42:17 -07001920 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001921 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001922 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001923
1924 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1925 continue;
1926 }
1927
Dan Stoza412903f2017-04-27 13:42:17 -07001928 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001929 }
1930}
1931
Edgar Arriaga844fa672020-01-16 14:21:42 -08001932void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1933 visitor(this);
1934 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001935 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001936 for (const sp<Layer>& child : children) {
1937 child->traverse(state, visitor);
1938 }
1939}
1940
Vishnu Nair787aa782023-03-17 13:46:46 -07001941void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
1942 for (const sp<Layer>& child : mDrawingChildren) {
1943 visitor(child.get());
1944 }
1945}
1946
chaviw4b129c22018-04-09 16:19:43 -07001947LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1948 const std::vector<Layer*>& layersInTree) {
1949 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1950 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001951 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1952 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001953 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001954
chaviwfd462612018-05-31 16:11:27 -07001955 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001956 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1957 sp<Layer> strongRelative = weakRelative.promote();
1958 // Only add relative layers that are also descendents of the top most parent of the tree.
1959 // If a relative layer is not a descendent, then it should be ignored.
1960 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1961 traverse.add(strongRelative);
1962 }
1963 }
1964
1965 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001966 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001967 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1968 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1969 // the child here since it won't be added later as a relative.
1970 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1971 childState.zOrderRelativeOf.promote().get())) {
1972 continue;
1973 }
1974 traverse.add(child);
1975 }
1976
1977 return traverse;
1978}
1979
1980void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1981 LayerVector::StateSet stateSet,
1982 const LayerVector::Visitor& visitor) {
1983 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001984
1985 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001986 for (; i < list.size(); i++) {
1987 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001988 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001989 break;
1990 }
chaviw4b129c22018-04-09 16:19:43 -07001991 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001992 }
chaviw4b129c22018-04-09 16:19:43 -07001993
chaviwa76b2712017-09-20 12:02:26 -07001994 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001995 for (; i < list.size(); i++) {
1996 const auto& relative = list[i];
1997 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001998 }
1999}
2000
chaviw4b129c22018-04-09 16:19:43 -07002001std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2002 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2003 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2004
2005 std::vector<Layer*> layersInTree = {this};
2006 for (size_t i = 0; i < children.size(); i++) {
2007 const auto& child = children[i];
2008 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2009 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2010 }
2011
2012 return layersInTree;
2013}
2014
2015void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2016 const LayerVector::Visitor& visitor) {
2017 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2018 std::sort(layersInTree.begin(), layersInTree.end());
2019 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2020}
2021
Peiyong Linefefaac2018-08-17 12:27:51 -07002022ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08002023 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002024}
2025
Garfield Tan2c1782c2022-02-16 15:25:05 -08002026bool Layer::isTransformValid() const {
2027 float transformDet = getTransform().det();
2028 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2029}
2030
chaviw13fdc492017-06-27 12:40:18 -07002031half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002032 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002033
chaviw13fdc492017-06-27 12:40:18 -07002034 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2035 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002036}
Robert Carr6452f122017-03-21 10:41:29 -07002037
Vishnu Nair6213bd92020-05-08 17:42:25 -07002038ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002039 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002040 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2041 return fixedTransformHint;
2042 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002043 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002044 if (!p) return fixedTransformHint;
2045 return p->getFixedTransformHint();
2046}
2047
chaviw13fdc492017-06-27 12:40:18 -07002048half4 Layer::getColor() const {
2049 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002050 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002051}
Robert Carr6452f122017-03-21 10:41:29 -07002052
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002053int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002054 if (getDrawingState().backgroundBlurRadius == 0) {
2055 return 0;
2056 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002057
Vishnu Nair29810f72022-07-01 16:38:41 +00002058 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002059 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2060 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002061}
2062
Galia Peychevae0acf382021-04-12 21:22:34 +02002063const std::vector<BlurRegion> Layer::getBlurRegions() const {
2064 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002065 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002066 for (auto& region : regionsCopy) {
2067 region.alpha = region.alpha * layerAlpha;
2068 }
2069 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002070}
2071
Vishnu Naire14c6b32022-08-06 04:20:15 +00002072RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002073 // Get parent settings
2074 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002075 const auto& parent = mDrawingParent.promote();
2076 if (parent != nullptr) {
2077 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002078 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002079 ui::Transform t = getActiveTransform(getDrawingState());
2080 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002081 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002082 parentSettings.radius.x *= t.getScaleX();
2083 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002084 }
2085 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002086
2087 // Get layer settings
2088 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002089 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002090 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002091 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002092
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002093 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002094 // If the parent and the layer have rounded corner settings, use the parent settings if the
2095 // parent crop is entirely inside the layer crop.
2096 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2097 if (parentSettings.cropRect.left > layerCropRect.left &&
2098 parentSettings.cropRect.top > layerCropRect.top &&
2099 parentSettings.cropRect.right < layerCropRect.right &&
2100 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2101 return parentSettings;
2102 } else {
2103 return layerSettings;
2104 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002105 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002106 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002107 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002108 return parentSettings;
2109 }
2110 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002111}
2112
Robert Carr88b85e12022-03-21 15:47:35 -07002113bool Layer::findInHierarchy(const sp<Layer>& l) {
2114 if (l == this) {
2115 return true;
2116 }
2117 for (auto& child : mDrawingChildren) {
2118 if (child->findInHierarchy(l)) {
2119 return true;
2120 }
2121 }
2122 return false;
2123}
2124
Robert Carr1f0a16a2016-10-24 16:27:39 -07002125void Layer::commitChildList() {
2126 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2127 const auto& child = mCurrentChildren[i];
2128 child->commitChildList();
2129 }
2130 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002131 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002132 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2133 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2134 if (zOrderRelativeOf == nullptr) return;
2135 if (findInHierarchy(zOrderRelativeOf)) {
2136 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2137 zOrderRelativeOf->mName.c_str());
2138 ALOGE("Severing rel Z loop, potentially dangerous");
2139 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002140 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002141 }
2142 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002143}
2144
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002145
chaviw3277faf2021-05-19 16:45:23 -05002146void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002147 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002148 mDrawingState.touchableRegionCrop =
2149 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002150 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002151 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002152 setTransactionFlags(eTransactionNeeded);
2153}
2154
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002155LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002156 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002157 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002158 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2159
Vishnu Nair00b90132021-11-05 14:03:40 -07002160 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nair2f65e972023-04-04 16:36:28 +00002161 ui::LayerStack layerStack =
2162 (mSnapshot) ? mSnapshot->outputFilter.layerStack : ui::INVALID_LAYER_STACK;
2163 writeCompositionStateToProto(layerProto, layerStack);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002164 }
2165
chaviw08f3cb22020-01-13 13:17:21 -08002166 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002167 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002168 }
chaviw6d89e2d2020-01-14 14:42:01 -08002169
2170 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002171}
2172
Vishnu Nair2f65e972023-04-04 16:36:28 +00002173void Layer::writeCompositionStateToProto(LayerProto* layerProto, ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002174 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002175 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +00002176
2177 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002178 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002179 const auto compositionType = getCompositionType(*display);
2180 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +00002181 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +00002182 [&]() { return layerProto->mutable_visible_region(); });
2183 }
2184}
2185
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002186void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002187 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002188 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002189 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002190 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002191 [&]() { return layerInfo->mutable_active_buffer(); });
2192 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2193 layerInfo->mutable_buffer_transform());
2194 }
2195 layerInfo->set_invalidate(contentDirty);
2196 layerInfo->set_is_protected(isProtected());
2197 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2198 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002199 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002200 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002201 layerInfo->set_corner_radius(
2202 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002203 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2204 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2205 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2206 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2207 [&]() { return layerInfo->mutable_position(); });
2208 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002209 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2210 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002211
Vishnu Nair00b90132021-11-05 14:03:40 -07002212 if (hasColorTransform()) {
2213 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002214 }
2215
Vishnu Nair60db8c02020-04-02 11:55:16 -07002216 LayerProtoHelper::writeToProto(mSourceBounds,
2217 [&]() { return layerInfo->mutable_source_bounds(); });
2218 LayerProtoHelper::writeToProto(mScreenBounds,
2219 [&]() { return layerInfo->mutable_screen_bounds(); });
2220 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2221 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2222 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002223}
2224
2225void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002226 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002227 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2228 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002229 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002230
chaviw766c9c52021-02-10 17:36:47 -08002231 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002232
Vishnu Nair00b90132021-11-05 14:03:40 -07002233 layerInfo->set_id(sequence);
2234 layerInfo->set_name(getName().c_str());
2235 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002236
Vishnu Nair00b90132021-11-05 14:03:40 -07002237 for (const auto& child : children) {
2238 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002239 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002240
Vishnu Nair00b90132021-11-05 14:03:40 -07002241 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2242 sp<Layer> strongRelative = weakRelative.promote();
2243 if (strongRelative != nullptr) {
2244 layerInfo->add_relatives(strongRelative->sequence);
2245 }
2246 }
2247
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002248 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002249 [&]() { return layerInfo->mutable_transparent_region(); });
2250
2251 layerInfo->set_layer_stack(getLayerStack().id);
2252 layerInfo->set_z(state.z);
2253
2254 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2255 return layerInfo->mutable_requested_position();
2256 });
2257
Vishnu Nair00b90132021-11-05 14:03:40 -07002258 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2259
2260 layerInfo->set_is_opaque(isOpaque(state));
2261
2262 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2263 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2264 LayerProtoHelper::writeToProto(state.color,
2265 [&]() { return layerInfo->mutable_requested_color(); });
2266 layerInfo->set_flags(state.flags);
2267
2268 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2269 layerInfo->mutable_requested_transform());
2270
2271 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2272 if (parent != nullptr) {
2273 layerInfo->set_parent(parent->sequence);
2274 } else {
2275 layerInfo->set_parent(-1);
2276 }
2277
2278 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2279 if (zOrderRelativeOf != nullptr) {
2280 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2281 } else {
2282 layerInfo->set_z_order_relative_of(-1);
2283 }
2284
2285 layerInfo->set_is_relative_of(state.isRelativeOf);
2286
2287 layerInfo->set_owner_uid(mOwnerUid);
2288
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002289 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002290 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002291 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002292 info = fillInputInfo(
2293 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002294 } else {
2295 info = state.inputInfo;
2296 }
2297
2298 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002299 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002300 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002301
Vishnu Nair00b90132021-11-05 14:03:40 -07002302 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002303 auto protoMap = layerInfo->mutable_metadata();
2304 for (const auto& entry : state.metadata.mMap) {
2305 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2306 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002307 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002308
2309 LayerProtoHelper::writeToProto(state.destinationFrame,
2310 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002311}
2312
Robert Carr2e102c92018-10-23 12:11:15 -07002313bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002314 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002315}
2316
Prabir Pradhan33da9462022-06-14 14:55:57 +00002317// Applies the given transform to the region, while protecting against overflows caused by any
2318// offsets. If applying the offset in the transform to any of the Rects in the region would result
2319// in an overflow, they are not added to the output Region.
2320static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2321 const std::string& debugWindowName) {
2322 // Round the translation using the same rounding strategy used by ui::Transform.
2323 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2324 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2325
2326 ui::Transform transformWithoutOffset = t;
2327 transformWithoutOffset.set(0.f, 0.f);
2328
2329 const Region transformed = transformWithoutOffset.transform(r);
2330
2331 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2332 Region ret;
2333 for (const auto& rect : transformed) {
2334 Rect newRect;
2335 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2336 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2337 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2338 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2339 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2340 debugWindowName.c_str());
2341 continue;
2342 }
2343 ret.orSelf(newRect);
2344 }
2345 return ret;
2346}
2347
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002348void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002349 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2350 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002351 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002352 }
2353
Vishnu Nairfed7c122023-03-18 01:54:43 +00002354 const Rect roundedFrameInDisplay = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002355 info.frameLeft = roundedFrameInDisplay.left;
2356 info.frameTop = roundedFrameInDisplay.top;
2357 info.frameRight = roundedFrameInDisplay.right;
2358 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002359
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002360 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002361 inputToLayer.set(inputBounds.left, inputBounds.top);
2362 const ui::Transform layerToScreen = getInputTransform();
2363 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002364
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002365 // InputDispatcher expects a display-to-input transform.
2366 info.transform = inputToDisplay.inverse();
2367
2368 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002369 info.touchableRegion =
2370 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002371}
2372
chaviw3277faf2021-05-19 16:45:23 -05002373void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002374 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002375 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002376 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002377 }
2378 if (p != nullptr) {
2379 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2380 }
2381}
2382
Vishnu Naira066d902021-09-13 18:40:17 -07002383gui::DropInputMode Layer::getDropInputMode() const {
2384 gui::DropInputMode mode = mDrawingState.dropInputMode;
2385 if (mode == gui::DropInputMode::ALL) {
2386 return mode;
2387 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002388 sp<Layer> parent = mDrawingParent.promote();
2389 if (parent) {
2390 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002391 if (parentMode != gui::DropInputMode::NONE) {
2392 return parentMode;
2393 }
2394 }
2395 return mode;
2396}
2397
2398void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002399 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002400 return;
2401 }
2402
2403 // Check if we need to drop input unconditionally
2404 gui::DropInputMode dropInputMode = getDropInputMode();
2405 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002406 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002407 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2408 return;
2409 }
2410
2411 // Check if we need to check if the window is obscured by parent
2412 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2413 return;
2414 }
2415
2416 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002417 sp<Layer> parent = mDrawingParent.promote();
2418 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002419 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002420 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2421 static_cast<float>(getAlpha()));
2422 }
2423
2424 // Check if the parent has cropped the buffer
2425 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2426 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002427 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002428 return;
2429 }
2430
2431 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2432 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2433 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2434 // match then the layer has not been cropped by its parents.
2435 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2436 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2437
2438 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002439 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002440 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2441 getDebugName());
2442 } else {
2443 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2444 // input if the window is obscured. This check should be done in surfaceflinger but the
2445 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2446 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002447 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002448 }
2449}
2450
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002451WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002452 if (!hasInputInfo()) {
2453 mDrawingState.inputInfo.name = getName();
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002454 mDrawingState.inputInfo.ownerUid = gui::Uid{mOwnerUid};
Prabir Pradhane59c6dc2023-06-13 19:53:03 +00002455 mDrawingState.inputInfo.ownerPid = gui::Pid{mOwnerPid};
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002456 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002457 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002458 }
2459
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002460 const ui::Transform& displayTransform =
2461 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2462
chaviw3277faf2021-05-19 16:45:23 -05002463 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002464 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002465 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002466
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002467 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002468
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002469 if (displayArgs.transform == nullptr) {
2470 // Do not let the window receive touches if it is not associated with a valid display
2471 // transform. We still allow the window to receive keys and prevent ANRs.
2472 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2473 }
2474
Patrick Williams1caf3b72023-03-31 10:59:10 -05002475 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !isVisibleForInput());
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002476
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002477 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002478 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002479 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002480
Vishnu Nair16a938f2021-09-24 07:14:54 -07002481 // If the window will be blacked out on a display because the display does not have the secure
2482 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002483 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002484 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002485 }
2486
Vishnu Nairfed7c122023-03-18 01:54:43 +00002487 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002488 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002489 Rect inputBoundsInDisplaySpace;
2490 if (!cropLayer) {
2491 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2492 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2493 } else {
2494 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2495 inputBoundsInDisplaySpace =
2496 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2497 }
2498 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002499 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002500 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2501 Rect inputBoundsInDisplaySpace =
2502 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2503 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002504 }
2505
Winson Chunga30f7c92021-06-29 15:42:56 -07002506 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2507 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002508 if (isTrustedOverlay()) {
2509 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2510 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002511
chaviwaf87b3e2019-10-01 16:59:28 -07002512 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2513 // touches from going outside the cloned area.
2514 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002515 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002516 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2517 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002518 info.touchableRegion = info.touchableRegion.intersect(rect);
2519 }
2520 }
2521
Robert Carr720e5062018-07-30 17:45:14 -07002522 return info;
2523}
2524
Vishnu Nairfed7c122023-03-18 01:54:43 +00002525Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2526 const ui::Transform& screenToDisplay) {
2527 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2528 // frame and transform used for the layer, which determines the bounds and the coordinate space
2529 // within which the layer will receive input.
2530
2531 // Coordinate space definitions:
2532 // - display: The display device's coordinate space. Correlates to pixels on the display.
2533 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2534 // - layer: The coordinate space of this layer.
2535 // - input: The coordinate space in which this layer will receive input events. This could be
2536 // different than layer space if a surfaceInset is used, which changes the origin
2537 // of the input space.
2538
2539 // Crop the input bounds to ensure it is within the parent's bounds.
2540 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2541 const ui::Transform layerToScreen = getInputTransform();
2542 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2543 return Rect{layerToDisplay.transform(croppedInputBounds)};
2544}
2545
chaviwaf87b3e2019-10-01 16:59:28 -07002546sp<Layer> Layer::getClonedRoot() {
2547 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002548 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002549 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002550 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002551 return nullptr;
2552 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002553 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002554}
2555
Robert Carredd13602020-04-13 17:24:34 -07002556bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002557 return mDrawingState.inputInfo.token != nullptr ||
2558 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002559}
2560
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002561compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002562 const DisplayDevice* display) const {
2563 if (!display) return nullptr;
Vishnu Naird47bcee2023-02-24 18:08:51 +00002564 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2565 return display->getCompositionDisplay()->getOutputLayerForLayer(
2566 getCompositionEngineLayerFE());
2567 }
2568 sp<LayerFE> layerFE;
2569 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2570 for (auto& [p, layer] : mLayerFEs) {
2571 if (p == path) {
2572 layerFE = layer;
2573 }
2574 }
2575
2576 if (!layerFE) return nullptr;
2577 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002578}
2579
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002580Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2581 const auto outputLayer = findOutputLayerForDisplay(display);
2582 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002583}
2584
Vishnu Nairde177252023-04-21 12:44:10 -07002585void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom, uint32_t mirrorRootId) {
2586 mSnapshot->path.id = clonedFrom->getSequence();
2587 mSnapshot->path.mirrorRootId = mirrorRootId;
2588
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002589 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002590 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002591 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2592 mPotentialCursor = clonedFrom->mPotentialCursor;
2593 mProtectedByApp = clonedFrom->mProtectedByApp;
2594 updateCloneBufferInfo();
2595}
2596
2597void Layer::updateCloneBufferInfo() {
2598 if (!isClone() || !isClonedFromAlive()) {
2599 return;
2600 }
2601
2602 sp<Layer> clonedFrom = getClonedFrom();
2603 mBufferInfo = clonedFrom->mBufferInfo;
2604 mSidebandStream = clonedFrom->mSidebandStream;
2605 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2606 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2607 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2608
2609 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2610 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2611 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2612 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2613 // the cloned drawingState again.
2614 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2615 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2616 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2617 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2618
2619 cloneDrawingState(clonedFrom.get());
2620
2621 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2622 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2623 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2624 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002625}
chaviw74b03172019-08-19 11:09:03 -07002626
Vishnu Nair3be61902023-04-26 19:47:29 -07002627bool Layer::updateMirrorInfo(const std::deque<Layer*>& cloneRootsPendingUpdates) {
chaviw74b03172019-08-19 11:09:03 -07002628 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2629 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2630 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2631 // that case, we want to delete the reference to the clone since we want it to get
2632 // destroyed. The root, this layer, will still be around since the client can continue
2633 // to hold a reference, but no cloned layers will be displayed.
2634 mClonedChild = nullptr;
Vishnu Nair3be61902023-04-26 19:47:29 -07002635 return true;
chaviw74b03172019-08-19 11:09:03 -07002636 }
2637
2638 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2639 // If the real layer exists and is in current state, add the clone as a child of the root.
2640 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2641 // copied to drawingState for the root layer. So the clonedChild is always removed from
2642 // drawingState and then needs to be added back each traversal.
2643 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2644 addChildToDrawing(mClonedChild);
2645 }
2646
2647 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002648 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002649 mClonedChild->updateClonedRelatives(clonedLayersMap);
Vishnu Nair3be61902023-04-26 19:47:29 -07002650
2651 for (Layer* root : cloneRootsPendingUpdates) {
2652 if (clonedLayersMap.find(sp<Layer>::fromExisting(root)) != clonedLayersMap.end()) {
2653 return false;
2654 }
2655 }
2656 return true;
chaviw74b03172019-08-19 11:09:03 -07002657}
2658
2659void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2660 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2661 // to the clone. If the real layer is no longer alive, continue traversing the children
2662 // since we may be able to pull out other children that are still alive.
2663 if (isClonedFromAlive()) {
2664 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002665 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002666 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002667 }
2668
2669 // The clone layer may have children in drawingState since they may have been created and
2670 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2671 // that already exist, since we can just re-use them.
2672 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2673 // not updated in the regular traversal. They are skipped since the root will lose the
2674 // reference to them when it copies its currentChildren to drawing.
2675 for (sp<Layer>& child : mDrawingChildren) {
2676 child->updateClonedDrawingState(clonedLayersMap);
2677 }
2678}
2679
2680void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2681 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2682 mDrawingChildren.clear();
2683
2684 if (!isClonedFromAlive()) {
2685 return;
2686 }
2687
2688 sp<Layer> clonedFrom = getClonedFrom();
2689 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2690 if (child == mirrorRoot) {
2691 // This is to avoid cyclical mirroring.
2692 continue;
2693 }
2694 sp<Layer> clonedChild = clonedLayersMap[child];
2695 if (clonedChild == nullptr) {
Vishnu Nairde177252023-04-21 12:44:10 -07002696 clonedChild = child->createClone(mirrorRoot->getSequence());
chaviw74b03172019-08-19 11:09:03 -07002697 clonedLayersMap[child] = clonedChild;
2698 }
2699 addChildToDrawing(clonedChild);
2700 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2701 }
2702}
2703
chaviwaf87b3e2019-10-01 16:59:28 -07002704void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2705 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2706 if (cropLayer != nullptr) {
2707 if (clonedLayersMap.count(cropLayer) == 0) {
2708 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2709 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002710 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002711 } else {
2712 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2713 mDrawingState.touchableRegionCrop = clonedCropLayer;
2714 }
2715 }
2716 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2717 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002718 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002719}
2720
2721void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002722 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002723 mDrawingState.zOrderRelatives.clear();
2724
2725 if (!isClonedFromAlive()) {
2726 return;
2727 }
2728
chaviwaf87b3e2019-10-01 16:59:28 -07002729 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002730 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002731 const sp<Layer>& relative = relativeWeak.promote();
2732 if (clonedLayersMap.count(relative) > 0) {
2733 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002734 mDrawingState.zOrderRelatives.add(clonedRelative);
2735 }
2736 }
2737
2738 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2739 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2740 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2741 // still traverse the children, but the layer with the missing relativeOf will not be shown
2742 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002743 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2744 if (clonedLayersMap.count(relativeOf) > 0) {
2745 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002746 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2747 }
2748
chaviwaf87b3e2019-10-01 16:59:28 -07002749 updateClonedInputInfo(clonedLayersMap);
2750
chaviw74b03172019-08-19 11:09:03 -07002751 for (sp<Layer>& child : mDrawingChildren) {
2752 child->updateClonedRelatives(clonedLayersMap);
2753 }
2754}
2755
2756void Layer::addChildToDrawing(const sp<Layer>& layer) {
2757 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002758 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002759}
2760
Steven Thomas62a4cf82020-01-31 12:04:03 -08002761Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2762 switch (compatibility) {
2763 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2764 return FrameRateCompatibility::Default;
2765 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2766 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002767 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2768 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002769 case ANATIVEWINDOW_FRAME_RATE_MIN:
2770 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002771 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2772 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002773 default:
2774 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2775 return FrameRateCompatibility::Default;
2776 }
2777}
2778
Marin Shalamanovc5986772021-03-16 16:09:49 +01002779scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2780 switch (strategy) {
2781 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2782 return Seamlessness::OnlySeamless;
2783 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2784 return Seamlessness::SeamedAndSeamless;
2785 default:
2786 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2787 return Seamlessness::Default;
2788 }
2789}
2790
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002791bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002792 const State& s(mDrawingState);
2793 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2794 return true;
2795 }
2796
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002797 sp<Layer> parent = mDrawingParent.promote();
2798 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002799}
2800
Robert Carr6a0382d2021-07-01 15:57:17 -07002801void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2802 mClonedChild = clonedChild;
2803 mHadClonedChild = true;
Vishnu Nair3be61902023-04-26 19:47:29 -07002804 mFlinger->mLayerMirrorRoots.push_back(this);
Robert Carr6a0382d2021-07-01 15:57:17 -07002805}
2806
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002807bool Layer::setDropInputMode(gui::DropInputMode mode) {
2808 if (mDrawingState.dropInputMode == mode) {
2809 return false;
2810 }
2811 mDrawingState.dropInputMode = mode;
2812 return true;
2813}
2814
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002815void Layer::cloneDrawingState(const Layer* from) {
2816 mDrawingState = from->mDrawingState;
2817 // Skip callback info since they are not applicable for cloned layers.
2818 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002819 // TODO (b/238781169) currently broken for mirror layers because we do not
2820 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002821 mDrawingState.callbackHandles = {};
2822}
2823
Patrick Williamsbb25f802022-08-30 23:02:34 +00002824void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2825 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002826 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002827 if (!listener) {
2828 return;
2829 }
2830 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002831 uint32_t currentMaxAcquiredBufferCount =
2832 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002833 listener->onReleaseBuffer({buffer->getId(), framenumber},
2834 releaseFence ? releaseFence : Fence::NO_FENCE,
2835 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002836}
2837
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002838void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
2839 ui::LayerStack layerStack) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002840 // If we are displayed on multiple displays in a single composition cycle then we would
2841 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2842 // For example we can only use it if all the displays are client comp, and we need
2843 // to merge all the client comp fences. We could do this, but for now we just
2844 // disable the optimization when a layer is composed on multiple displays.
2845 if (mClearClientCompositionFenceOnLayerDisplayed) {
2846 mLastClientCompositionFence = nullptr;
2847 } else {
2848 mClearClientCompositionFenceOnLayerDisplayed = true;
2849 }
2850
2851 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2852 // buffer that was presented on this layer. The first transaction that came in this frame that
2853 // replaced the previous buffer on this layer needs this release fence, because the fence will
2854 // let the client know when that previous buffer is removed from the screen.
2855 //
2856 // Every other transaction on this layer does not need a release fence because no other
2857 // Transactions that were set on this layer this frame are going to have their preceding buffer
2858 // removed from the display this frame.
2859 //
2860 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2861 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2862 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2863 // the previous buffer will be released this frame. The third transaction also contains a
2864 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2865 // transaction will now no longer be presented so it is released immediately and the third
2866 // transaction doesn't need a previous release fence.
2867 sp<CallbackHandle> ch;
2868 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002869 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002870 ch = handle;
2871 break;
2872 }
2873 }
2874
2875 // Prevent tracing the same release multiple times.
2876 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2877 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2878 }
2879
2880 if (ch != nullptr) {
2881 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2882 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2883 ch->name = mName;
2884 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002885 mPreviouslyPresentedLayerStacks.push_back(layerStack);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002886}
2887
2888void Layer::onSurfaceFrameCreated(
2889 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2890 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2891 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2892 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2893 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002894 if (hasBufferOrSidebandStreamInDrawing()) {
2895 // Only log for layers with a buffer, since we expect the jank data to be drained for
2896 // these, while there may be no jank listeners for bufferless layers.
2897 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2898 mName.c_str());
2899 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2900 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2901 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002902 mPendingJankClassifications.pop_front();
2903 }
2904 mPendingJankClassifications.emplace_back(surfaceFrame);
2905}
2906
2907void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2908 for (const auto& handle : mDrawingState.callbackHandles) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -07002909 if (mFlinger->mLayerLifecycleManagerEnabled) {
2910 handle->transformHint = mTransformHint;
2911 } else {
2912 handle->transformHint = mSkipReportingTransformHint
2913 ? std::nullopt
2914 : std::make_optional<uint32_t>(mTransformHintLegacy);
2915 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002916 handle->dequeueReadyTime = dequeueReadyTime;
2917 handle->currentMaxAcquiredBufferCount =
2918 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2919 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2920 handle->previousReleaseCallbackId.framenumber);
2921 }
2922
2923 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002924 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002925 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2926 break;
2927 }
2928 }
2929
2930 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002931 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002932 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2933 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002934 mDrawingState.callbackHandles = {};
2935}
2936
2937bool Layer::willPresentCurrentTransaction() const {
2938 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2939 return (getSidebandStreamChanged() || getAutoRefresh() ||
2940 (mDrawingState.modified &&
2941 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2942}
2943
2944bool Layer::setTransform(uint32_t transform) {
2945 if (mDrawingState.bufferTransform == transform) return false;
2946 mDrawingState.bufferTransform = transform;
2947 mDrawingState.modified = true;
2948 setTransactionFlags(eTransactionNeeded);
2949 return true;
2950}
2951
2952bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2953 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2954 mDrawingState.sequence++;
2955 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2956 mDrawingState.modified = true;
2957 setTransactionFlags(eTransactionNeeded);
2958 return true;
2959}
2960
2961bool Layer::setBufferCrop(const Rect& bufferCrop) {
2962 if (mDrawingState.bufferCrop == bufferCrop) return false;
2963
2964 mDrawingState.sequence++;
2965 mDrawingState.bufferCrop = bufferCrop;
2966
2967 mDrawingState.modified = true;
2968 setTransactionFlags(eTransactionNeeded);
2969 return true;
2970}
2971
2972bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2973 if (mDrawingState.destinationFrame == destinationFrame) return false;
2974
2975 mDrawingState.sequence++;
2976 mDrawingState.destinationFrame = destinationFrame;
2977
2978 mDrawingState.modified = true;
2979 setTransactionFlags(eTransactionNeeded);
2980 return true;
2981}
2982
2983// Translate destination frame into scale and position. If a destination frame is not set, use the
2984// provided scale and position
2985bool Layer::updateGeometry() {
2986 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2987 mDrawingState.destinationFrame.isEmpty()) {
2988 // If destination frame is not set, use the requested transform set via
2989 // Layer::setPosition and Layer::setMatrix.
2990 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2991 }
2992
2993 Rect destRect = mDrawingState.destinationFrame;
2994 int32_t destW = destRect.width();
2995 int32_t destH = destRect.height();
2996 if (destRect.left < 0) {
2997 destRect.left = 0;
2998 destRect.right = destW;
2999 }
3000 if (destRect.top < 0) {
3001 destRect.top = 0;
3002 destRect.bottom = destH;
3003 }
3004
3005 if (!mDrawingState.buffer) {
3006 ui::Transform t;
3007 t.set(destRect.left, destRect.top);
3008 return assignTransform(&mDrawingState.transform, t);
3009 }
3010
3011 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3012 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3013 // Undo any transformations on the buffer.
3014 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3015 std::swap(bufferWidth, bufferHeight);
3016 }
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003017 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003018 if (mDrawingState.transformToDisplayInverse) {
3019 if (invTransform & ui::Transform::ROT_90) {
3020 std::swap(bufferWidth, bufferHeight);
3021 }
3022 }
3023
3024 float sx = destW / static_cast<float>(bufferWidth);
3025 float sy = destH / static_cast<float>(bufferHeight);
3026 ui::Transform t;
3027 t.set(sx, 0, 0, sy);
3028 t.set(destRect.left, destRect.top);
3029 return assignTransform(&mDrawingState.transform, t);
3030}
3031
3032bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3033 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3034 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3035 return false;
3036 }
3037
3038 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3039
3040 mDrawingState.sequence++;
3041 mDrawingState.modified = true;
3042 setTransactionFlags(eTransactionNeeded);
3043
3044 return true;
3045}
3046
3047bool Layer::setPosition(float x, float y) {
3048 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3049 return false;
3050 }
3051
3052 mRequestedTransform.set(x, y);
3053
3054 mDrawingState.sequence++;
3055 mDrawingState.modified = true;
3056 setTransactionFlags(eTransactionNeeded);
3057
3058 return true;
3059}
3060
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003061void Layer::resetDrawingStateBufferInfo() {
3062 mDrawingState.producerId = 0;
3063 mDrawingState.frameNumber = 0;
3064 mDrawingState.releaseBufferListener = nullptr;
3065 mDrawingState.buffer = nullptr;
3066 mDrawingState.acquireFence = sp<Fence>::make(-1);
3067 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3068 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3069 mDrawingState.releaseBufferEndpoint = nullptr;
3070}
3071
Patrick Williamsbb25f802022-08-30 23:02:34 +00003072bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3073 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3074 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003075 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003076 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003077
3078 const bool frameNumberChanged =
3079 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3080 const uint64_t frameNumber =
3081 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003082 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003083
3084 if (mDrawingState.buffer) {
3085 mReleasePreviousBuffer = true;
3086 if (!mBufferInfo.mBuffer ||
3087 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3088 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3089 // If mDrawingState has a buffer, and we are about to update again
3090 // before swapping to drawing state, then the first buffer will be
3091 // dropped and we should decrement the pending buffer count and
3092 // call any release buffer callbacks if set.
3093 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3094 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003095 mDrawingState.acquireFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003096 decrementPendingBufferCount();
3097 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3098 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
Ady Abraham5a3e3562023-06-07 10:32:08 -07003099 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX, systemTime());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003100 mDrawingState.bufferSurfaceFrameTX.reset();
3101 }
3102 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3103 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3104 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003105 mLastClientCompositionFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003106 mLastClientCompositionFence = nullptr;
3107 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003108 } else if (buffer) {
Vishnu Nairc09c0232023-03-02 03:22:35 +00003109 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3110 // we don't want to incorrectly classify a frame if we miss the desired present time.
3111 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003112 }
3113
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003114 mDrawingState.desiredPresentTime = desiredPresentTime;
3115 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3116 mDrawingState.latchedVsyncId = info.vsyncId;
Ady Abraham55269162023-05-09 11:26:06 -07003117 mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003118 mDrawingState.modified = true;
3119 if (!buffer) {
3120 resetDrawingStateBufferInfo();
3121 setTransactionFlags(eTransactionNeeded);
3122 mDrawingState.bufferSurfaceFrameTX = nullptr;
3123 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3124 return true;
3125 }
3126
Vishnu Naird1f74982023-06-15 20:16:51 -07003127 if ((mDrawingState.producerId > bufferData.producerId) ||
3128 ((mDrawingState.producerId == bufferData.producerId) &&
3129 (mDrawingState.frameNumber > frameNumber))) {
3130 ALOGE("Out of order buffers detected for %s producedId=%d frameNumber=%" PRIu64
3131 " -> producedId=%d frameNumber=%" PRIu64,
3132 getDebugName(), mDrawingState.producerId, mDrawingState.frameNumber,
3133 bufferData.producerId, frameNumber);
3134 TransactionTraceWriter::getInstance().invoke("out_of_order_buffers_", /*overwrite=*/false);
3135 }
3136
liulijuneb489f62022-10-17 22:02:14 +08003137 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -07003138 mDrawingState.barrierProducerId =
3139 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003140 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -07003141 mDrawingState.barrierFrameNumber =
3142 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
3143
Patrick Williamsbb25f802022-08-30 23:02:34 +00003144 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3145 mDrawingState.buffer = std::move(buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003146 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3147 ? bufferData.acquireFence
3148 : Fence::NO_FENCE;
3149 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3150 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3151 // We latched this buffer unsiganled, so we need to pass the acquire fence
3152 // on the callback instead of just the acquire time, since it's unknown at
3153 // this point.
3154 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3155 } else {
3156 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3157 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003158 setTransactionFlags(eTransactionNeeded);
3159
3160 const int32_t layerId = getSequence();
3161 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3162 mOwnerUid, postTime, getGameMode());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003163
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003164 if (mFlinger->mLegacyFrontEndEnabled) {
3165 recordLayerHistoryBufferUpdate(getLayerProps());
3166 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003167
3168 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3169
3170 if (dequeueTime && *dequeueTime != 0) {
3171 const uint64_t bufferId = mDrawingState.buffer->getId();
3172 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3173 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3174 FrameTracer::FrameEvent::DEQUEUE);
3175 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3176 FrameTracer::FrameEvent::QUEUE);
3177 }
3178
3179 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
Arthur Hung0cc8a382023-06-02 01:35:52 +00003180
3181 // If the layer had been updated a TextureView, this would make sure the present time could be
3182 // same to TextureView update when it's a small dirty, and get the correct heuristic rate.
3183 if (mFlinger->mScheduler->supportSmallDirtyDetection()) {
3184 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3185 mUsedVsyncIdForRefreshRateSelection = true;
3186 }
3187 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003188 return true;
3189}
3190
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003191void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3192 mDrawingState.desiredPresentTime = desiredPresentTime;
3193 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3194}
3195
3196void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps) {
Ady Abraham55269162023-05-09 11:26:06 -07003197 ATRACE_CALL();
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003198 const nsecs_t presentTime = [&] {
Ady Abraham55269162023-05-09 11:26:06 -07003199 if (!mDrawingState.isAutoTimestamp) {
3200 ATRACE_FORMAT_INSTANT("desiredPresentTime");
3201 return mDrawingState.desiredPresentTime;
3202 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003203
Ady Abraham55269162023-05-09 11:26:06 -07003204 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3205 const auto prediction =
3206 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3207 mDrawingState.latchedVsyncId);
3208 if (prediction.has_value()) {
3209 ATRACE_FORMAT_INSTANT("predictedPresentTime");
Arthur Hung0cc8a382023-06-02 01:35:52 +00003210 mMaxTimeForUseVsyncId = prediction->presentTime +
3211 scheduler::LayerHistory::kMaxPeriodForHistory.count();
Ady Abraham55269162023-05-09 11:26:06 -07003212 return prediction->presentTime;
3213 }
3214 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003215
Arthur Hung0cc8a382023-06-02 01:35:52 +00003216 if (!mFlinger->mScheduler->supportSmallDirtyDetection()) {
3217 return static_cast<nsecs_t>(0);
3218 }
3219
3220 // If the layer is not an application and didn't set an explicit rate or desiredPresentTime,
3221 // return "0" to tell the layer history that it will use the max refresh rate without
3222 // calculating the adaptive rate.
3223 if (mWindowType != WindowInfo::Type::APPLICATION &&
3224 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
3225 return static_cast<nsecs_t>(0);
3226 }
3227
3228 // Return the valid present time only when the layer potentially updated a TextureView so
3229 // LayerHistory could heuristically calculate the rate if the UI is continually updating.
3230 if (mUsedVsyncIdForRefreshRateSelection) {
3231 const auto prediction =
3232 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3233 mDrawingState.latchedVsyncId);
3234 if (prediction.has_value()) {
3235 if (mMaxTimeForUseVsyncId >= prediction->presentTime) {
3236 return prediction->presentTime;
3237 }
3238 mUsedVsyncIdForRefreshRateSelection = false;
3239 }
3240 }
3241
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003242 return static_cast<nsecs_t>(0);
3243 }();
Ady Abraham55269162023-05-09 11:26:06 -07003244
3245 if (ATRACE_ENABLED() && presentTime > 0) {
3246 const auto presentIn = TimePoint::fromNs(presentTime) - TimePoint::now();
3247 ATRACE_FORMAT_INSTANT("presentIn %s", to_string(presentIn).c_str());
3248 }
3249
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003250 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3251 scheduler::LayerHistory::LayerUpdateType::Buffer);
3252}
3253
3254void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps) {
3255 const nsecs_t presentTime =
3256 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
3257 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3258 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3259}
3260
Patrick Williamsbb25f802022-08-30 23:02:34 +00003261bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003262 if (mDrawingState.dataspace == dataspace) return false;
3263 mDrawingState.dataspace = dataspace;
3264 mDrawingState.modified = true;
3265 setTransactionFlags(eTransactionNeeded);
3266 return true;
3267}
3268
John Reck68796592023-01-25 13:47:12 -05003269bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07003270 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3271 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05003272 return false;
Sally Qi963049b2023-03-23 14:06:21 -07003273 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3274 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05003275 mDrawingState.modified = true;
3276 setTransactionFlags(eTransactionNeeded);
3277 return true;
3278}
3279
Alec Mourif4af03e2023-02-11 00:25:24 +00003280bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3281 if (mDrawingState.cachingHint == cachingHint) return false;
3282 mDrawingState.cachingHint = cachingHint;
3283 mDrawingState.modified = true;
3284 setTransactionFlags(eTransactionNeeded);
3285 return true;
3286}
3287
Patrick Williamsbb25f802022-08-30 23:02:34 +00003288bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3289 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3290 mDrawingState.hdrMetadata = hdrMetadata;
3291 mDrawingState.modified = true;
3292 setTransactionFlags(eTransactionNeeded);
3293 return true;
3294}
3295
3296bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003297 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003298 mDrawingState.surfaceDamageRegion = surfaceDamage;
3299 mDrawingState.modified = true;
3300 setTransactionFlags(eTransactionNeeded);
Arthur Hung0cc8a382023-06-02 01:35:52 +00003301 setIsSmallDirty();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003302 return true;
3303}
3304
3305bool Layer::setApi(int32_t api) {
3306 if (mDrawingState.api == api) return false;
3307 mDrawingState.api = api;
3308 mDrawingState.modified = true;
3309 setTransactionFlags(eTransactionNeeded);
3310 return true;
3311}
3312
3313bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3314 if (mDrawingState.sidebandStream == sidebandStream) return false;
3315
3316 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3317 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3318 } else if (sidebandStream != nullptr) {
3319 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3320 }
3321
3322 mDrawingState.sidebandStream = sidebandStream;
3323 mDrawingState.modified = true;
3324 setTransactionFlags(eTransactionNeeded);
3325 if (!mSidebandStreamChanged.exchange(true)) {
3326 // mSidebandStreamChanged was false
3327 mFlinger->onLayerUpdate();
3328 }
3329 return true;
3330}
3331
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003332bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3333 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003334 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3335 if (handles.empty()) {
3336 mReleasePreviousBuffer = false;
3337 return false;
3338 }
3339
Pascal Muetschard81cef292023-02-06 12:18:52 +01003340 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003341 for (const auto& handle : handles) {
3342 // If this transaction set a buffer on this layer, release its previous buffer
3343 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3344
3345 // If this layer will be presented in this frame
3346 if (willPresent) {
3347 // If this transaction set an acquire fence on this layer, set its acquire time
3348 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3349 handle->frameNumber = mDrawingState.frameNumber;
3350
3351 // Store so latched time and release fence can be set
3352 mDrawingState.callbackHandles.push_back(handle);
3353
3354 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003355 // Queue this handle to be notified below.
3356 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003357 }
3358 }
3359
Pascal Muetschard81cef292023-02-06 12:18:52 +01003360 if (!remainingHandles.empty()) {
3361 // Notify the transaction completed threads these handles are done. These are only the
3362 // handles that were not added to the mDrawingState, which will be notified later.
3363 std::vector<JankData> jankData;
3364 transferAvailableJankData(remainingHandles, jankData);
3365 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3366 }
3367
Patrick Williamsbb25f802022-08-30 23:02:34 +00003368 mReleasePreviousBuffer = false;
3369 mCallbackHandleAcquireTimeOrFence = -1;
3370
3371 return willPresent;
3372}
3373
3374Rect Layer::getBufferSize(const State& /*s*/) const {
3375 // for buffer state layers we use the display frame size as the buffer size.
3376
3377 if (mBufferInfo.mBuffer == nullptr) {
3378 return Rect::INVALID_RECT;
3379 }
3380
3381 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3382 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3383
3384 // Undo any transformations on the buffer and return the result.
3385 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3386 std::swap(bufWidth, bufHeight);
3387 }
3388
3389 if (getTransformToDisplayInverse()) {
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003390 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003391 if (invTransform & ui::Transform::ROT_90) {
3392 std::swap(bufWidth, bufHeight);
3393 }
3394 }
3395
3396 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3397}
3398
3399FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3400 if (mBufferInfo.mBuffer == nullptr) {
3401 return parentBounds;
3402 }
3403
3404 return getBufferSize(getDrawingState()).toFloatRect();
3405}
3406
3407bool Layer::fenceHasSignaled() const {
3408 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3409 return true;
3410 }
3411
3412 const bool fenceSignaled =
3413 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3414 if (!fenceSignaled) {
3415 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3416 TimeStats::LatchSkipReason::LateAcquire);
3417 }
3418
3419 return fenceSignaled;
3420}
3421
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003422void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003423 for (const auto& handle : mDrawingState.callbackHandles) {
3424 handle->refreshStartTime = refreshStartTime;
3425 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003426}
3427
3428void Layer::setAutoRefresh(bool autoRefresh) {
3429 mDrawingState.autoRefresh = autoRefresh;
3430}
3431
3432bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3433 // 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 +00003434 auto* snapshot = editLayerSnapshot();
3435 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003436
3437 if (mSidebandStreamChanged.exchange(false)) {
3438 const State& s(getDrawingState());
3439 // mSidebandStreamChanged was true
3440 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003441 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003442 if (mSidebandStream != nullptr) {
3443 setTransactionFlags(eTransactionNeeded);
3444 mFlinger->setTransactionFlags(eTraversalNeeded);
3445 }
3446 recomputeVisibleRegions = true;
3447
3448 return true;
3449 }
3450 return false;
3451}
3452
3453bool Layer::hasFrameUpdate() const {
3454 const State& c(getDrawingState());
3455 return (mDrawingStateModified || mDrawingState.modified) &&
3456 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3457}
3458
Vishnu Naird47bcee2023-02-24 18:08:51 +00003459void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003460 const State& s(getDrawingState());
3461
3462 if (!s.buffer) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003463 if (bgColorOnly || mBufferInfo.mBuffer) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003464 for (auto& handle : mDrawingState.callbackHandles) {
3465 handle->latchTime = latchTime;
3466 }
3467 }
3468 return;
3469 }
3470
3471 for (auto& handle : mDrawingState.callbackHandles) {
3472 if (handle->frameNumber == mDrawingState.frameNumber) {
3473 handle->latchTime = latchTime;
3474 }
3475 }
3476
3477 const int32_t layerId = getSequence();
3478 const uint64_t bufferId = mDrawingState.buffer->getId();
3479 const uint64_t frameNumber = mDrawingState.frameNumber;
3480 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3481 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3482 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3483
3484 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3485 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3486 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3487 FrameTracer::FrameEvent::LATCH);
3488
3489 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3490 if (bufferSurfaceFrame != nullptr &&
3491 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3492 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3493 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3494 // are processing the next state.
3495 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3496 mDrawingState.acquireFenceTime->getSignalTime(),
3497 latchTime);
3498 mDrawingState.bufferSurfaceFrameTX.reset();
3499 }
3500
3501 std::deque<sp<CallbackHandle>> remainingHandles;
3502 mFlinger->getTransactionCallbackInvoker()
3503 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3504 mDrawingState.callbackHandles = remainingHandles;
3505
3506 mDrawingStateModified = false;
3507}
3508
3509void Layer::gatherBufferInfo() {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003510 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3511 mPreviousReleaseBufferEndpoint = mBufferInfo.mReleaseBufferEndpoint;
3512 if (!mDrawingState.buffer) {
3513 mBufferInfo = {};
3514 return;
3515 }
3516
3517 if ((!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer))) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003518 decrementPendingBufferCount();
3519 }
3520
Patrick Williamsbb25f802022-08-30 23:02:34 +00003521 mBufferInfo.mBuffer = mDrawingState.buffer;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003522 mBufferInfo.mReleaseBufferEndpoint = mDrawingState.releaseBufferEndpoint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003523 mBufferInfo.mFence = mDrawingState.acquireFence;
3524 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3525 mBufferInfo.mPixelFormat =
3526 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3527 mBufferInfo.mFrameLatencyNeeded = true;
3528 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3529 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3530 mBufferInfo.mFence = mDrawingState.acquireFence;
3531 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3532 auto lastDataspace = mBufferInfo.mDataspace;
3533 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003534 if (mBufferInfo.mBuffer != nullptr) {
3535 auto& mapper = GraphicBufferMapper::get();
3536 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
3537 // and don't need to possibly remaps buffers.
3538 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
3539 status_t err = OK;
3540 {
3541 ATRACE_NAME("getDataspace");
3542 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
3543 }
3544 if (err != OK || dataspace != mBufferInfo.mDataspace) {
3545 {
3546 ATRACE_NAME("setDataspace");
3547 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
3548 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
3549 }
3550
3551 // Some GPU drivers may cache gralloc metadata which means before we composite we need
3552 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
3553 // compatible with old vendors, with a ticking clock.
3554 static const int32_t kVendorVersion =
3555 base::GetIntProperty("ro.vndk.version", __ANDROID_API_FUTURE__);
3556 if (const auto format =
3557 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
3558 mBufferInfo.mBuffer->getPixelFormat());
3559 err == OK && kVendorVersion < __ANDROID_API_U__ &&
3560 (format ==
3561 aidl::android::hardware::graphics::common::PixelFormat::
3562 IMPLEMENTATION_DEFINED ||
3563 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
3564 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
3565 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
3566 mBufferInfo.mBuffer->remapBuffer();
3567 }
3568 }
3569 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003570 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003571 mFlinger->mHdrLayerInfoChanged = true;
3572 }
Sally Qi963049b2023-03-23 14:06:21 -07003573 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3574 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05003575 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003576 }
3577 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3578 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3579 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3580 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3581 mBufferInfo.mApi = mDrawingState.api;
3582 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003583}
3584
3585Rect Layer::computeBufferCrop(const State& s) {
3586 if (s.buffer && !s.bufferCrop.isEmpty()) {
3587 Rect bufferCrop;
3588 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3589 return bufferCrop;
3590 } else if (s.buffer) {
3591 return s.buffer->getBounds();
3592 } else {
3593 return s.bufferCrop;
3594 }
3595}
3596
Vishnu Nairde177252023-04-21 12:44:10 -07003597sp<Layer> Layer::createClone(uint32_t mirrorRootId) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003598 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3599 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003600 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Vishnu Nairde177252023-04-21 12:44:10 -07003601 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this), mirrorRootId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003602 return layer;
3603}
3604
Patrick Williamsbb25f802022-08-30 23:02:34 +00003605void Layer::decrementPendingBufferCount() {
3606 int32_t pendingBuffers = --mPendingBufferTransactions;
3607 tracePendingBufferCount(pendingBuffers);
3608}
3609
3610void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3611 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3612}
3613
3614/*
3615 * We don't want to send the layer's transform to input, but rather the
3616 * parent's transform. This is because Layer's transform is
3617 * information about how the buffer is placed on screen. The parent's
3618 * transform makes more sense to send since it's information about how the
3619 * layer is placed on screen. This transform is used by input to determine
3620 * how to go from screen space back to window space.
3621 */
3622ui::Transform Layer::getInputTransform() const {
3623 if (!hasBufferOrSidebandStream()) {
3624 return getTransform();
3625 }
3626 sp<Layer> parent = mDrawingParent.promote();
3627 if (parent == nullptr) {
3628 return ui::Transform();
3629 }
3630
3631 return parent->getTransform();
3632}
3633
3634/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003635 * Returns the bounds used to fill the input frame and the touchable region.
3636 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003637 * Similar to getInputTransform, we need to update the bounds to include the transform.
3638 * This is because bounds don't include the buffer transform, where the input assumes
3639 * that's already included.
3640 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003641std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3642 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3643 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3644 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3645 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3646 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003647 }
3648
Vishnu Nairfed7c122023-03-18 01:54:43 +00003649 bool inputBoundsValid = croppedBufferSize.isValid();
3650 if (!inputBoundsValid) {
3651 /**
3652 * Input bounds are based on the layer crop or buffer size. But if we are using
3653 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3654 * we can use the parent bounds as the input bounds if the layer does not have buffer
3655 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3656 * use the parent bounds. A layer without a buffer can get input. So when a window is
3657 * initially added, its touchable region can fill its parent layer bounds and that can
3658 * have negative consequences.
3659 */
3660 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003661 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003662
3663 // Clamp surface inset to the input bounds.
3664 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3665 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3666 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3667
3668 // Apply the insets to the input bounds.
3669 inputBounds.left += xSurfaceInset;
3670 inputBounds.top += ySurfaceInset;
3671 inputBounds.right -= xSurfaceInset;
3672 inputBounds.bottom -= ySurfaceInset;
3673
3674 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003675}
3676
Ady Abraham005398b2023-06-05 13:59:41 -07003677bool Layer::isSimpleBufferUpdate(const layer_state_t& s) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003678 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3679
3680 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3681 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3682 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3683 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3684 layer_state_t::eReparent;
3685
Patrick Williamsbb25f802022-08-30 23:02:34 +00003686 if ((s.what & requiredFlags) != requiredFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003687 ATRACE_FORMAT_INSTANT("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3688 (s.what | requiredFlags) & ~s.what);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003689 return false;
3690 }
3691
3692 if (s.what & deniedFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003693 ATRACE_FORMAT_INSTANT("%s: false [has denied flags 0x%" PRIx64 "]", __func__,
3694 s.what & deniedFlags);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003695 return false;
3696 }
3697
Patrick Williamsbb25f802022-08-30 23:02:34 +00003698 if (s.what & layer_state_t::ePositionChanged) {
3699 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
Ady Abraham005398b2023-06-05 13:59:41 -07003700 ATRACE_FORMAT_INSTANT("%s: false [ePositionChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003701 return false;
3702 }
3703 }
3704
3705 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003706 if (mDrawingState.color.a != s.color.a) {
Ady Abraham005398b2023-06-05 13:59:41 -07003707 ATRACE_FORMAT_INSTANT("%s: false [eAlphaChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003708 return false;
3709 }
3710 }
3711
3712 if (s.what & layer_state_t::eColorTransformChanged) {
3713 if (mDrawingState.colorTransform != s.colorTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003714 ATRACE_FORMAT_INSTANT("%s: false [eColorTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003715 return false;
3716 }
3717 }
3718
3719 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003720 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Ady Abraham005398b2023-06-05 13:59:41 -07003721 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundColorChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003722 return false;
3723 }
3724 }
3725
3726 if (s.what & layer_state_t::eMatrixChanged) {
3727 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3728 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3729 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3730 mRequestedTransform.dsdy() != s.matrix.dsdy) {
Ady Abraham005398b2023-06-05 13:59:41 -07003731 ATRACE_FORMAT_INSTANT("%s: false [eMatrixChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003732 return false;
3733 }
3734 }
3735
3736 if (s.what & layer_state_t::eCornerRadiusChanged) {
3737 if (mDrawingState.cornerRadius != s.cornerRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003738 ATRACE_FORMAT_INSTANT("%s: false [eCornerRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003739 return false;
3740 }
3741 }
3742
3743 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3744 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
Ady Abraham005398b2023-06-05 13:59:41 -07003745 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003746 return false;
3747 }
3748 }
3749
Vishnu Nairbbceb462022-10-10 04:52:13 +00003750 if (s.what & layer_state_t::eBufferTransformChanged) {
3751 if (mDrawingState.bufferTransform != s.bufferTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003752 ATRACE_FORMAT_INSTANT("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003753 return false;
3754 }
3755 }
3756
3757 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3758 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
Ady Abraham005398b2023-06-05 13:59:41 -07003759 ATRACE_FORMAT_INSTANT("%s: false [eTransformToDisplayInverseChanged changed]",
3760 __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003761 return false;
3762 }
3763 }
3764
3765 if (s.what & layer_state_t::eCropChanged) {
3766 if (mDrawingState.crop != s.crop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003767 ATRACE_FORMAT_INSTANT("%s: false [eCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003768 return false;
3769 }
3770 }
3771
3772 if (s.what & layer_state_t::eDataspaceChanged) {
3773 if (mDrawingState.dataspace != s.dataspace) {
Ady Abraham005398b2023-06-05 13:59:41 -07003774 ATRACE_FORMAT_INSTANT("%s: false [eDataspaceChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003775 return false;
3776 }
3777 }
3778
3779 if (s.what & layer_state_t::eHdrMetadataChanged) {
3780 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
Ady Abraham005398b2023-06-05 13:59:41 -07003781 ATRACE_FORMAT_INSTANT("%s: false [eHdrMetadataChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003782 return false;
3783 }
3784 }
3785
3786 if (s.what & layer_state_t::eSidebandStreamChanged) {
3787 if (mDrawingState.sidebandStream != s.sidebandStream) {
Ady Abraham005398b2023-06-05 13:59:41 -07003788 ATRACE_FORMAT_INSTANT("%s: false [eSidebandStreamChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003789 return false;
3790 }
3791 }
3792
3793 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3794 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
Ady Abraham005398b2023-06-05 13:59:41 -07003795 ATRACE_FORMAT_INSTANT("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003796 return false;
3797 }
3798 }
3799
3800 if (s.what & layer_state_t::eShadowRadiusChanged) {
3801 if (mDrawingState.shadowRadius != s.shadowRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003802 ATRACE_FORMAT_INSTANT("%s: false [eShadowRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003803 return false;
3804 }
3805 }
3806
3807 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3808 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
Ady Abraham005398b2023-06-05 13:59:41 -07003809 ATRACE_FORMAT_INSTANT("%s: false [eFixedTransformHintChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003810 return false;
3811 }
3812 }
3813
3814 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3815 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
Ady Abraham005398b2023-06-05 13:59:41 -07003816 ATRACE_FORMAT_INSTANT("%s: false [eTrustedOverlayChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003817 return false;
3818 }
3819 }
3820
3821 if (s.what & layer_state_t::eStretchChanged) {
3822 StretchEffect temp = s.stretchEffect;
3823 temp.sanitize();
3824 if (mDrawingState.stretchEffect != temp) {
Ady Abraham005398b2023-06-05 13:59:41 -07003825 ATRACE_FORMAT_INSTANT("%s: false [eStretchChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003826 return false;
3827 }
3828 }
3829
3830 if (s.what & layer_state_t::eBufferCropChanged) {
3831 if (mDrawingState.bufferCrop != s.bufferCrop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003832 ATRACE_FORMAT_INSTANT("%s: false [eBufferCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003833 return false;
3834 }
3835 }
3836
3837 if (s.what & layer_state_t::eDestinationFrameChanged) {
3838 if (mDrawingState.destinationFrame != s.destinationFrame) {
Ady Abraham005398b2023-06-05 13:59:41 -07003839 ATRACE_FORMAT_INSTANT("%s: false [eDestinationFrameChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003840 return false;
3841 }
3842 }
3843
3844 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3845 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
Ady Abraham005398b2023-06-05 13:59:41 -07003846 ATRACE_FORMAT_INSTANT("%s: false [eDimmingEnabledChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003847 return false;
3848 }
3849 }
3850
John Reck68796592023-01-25 13:47:12 -05003851 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07003852 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
3853 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
Ady Abraham005398b2023-06-05 13:59:41 -07003854 ATRACE_FORMAT_INSTANT("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05003855 return false;
3856 }
3857 }
3858
Patrick Williamsbb25f802022-08-30 23:02:34 +00003859 return true;
3860}
3861
3862bool Layer::isHdrY410() const {
3863 // pixel format is HDR Y410 masquerading as RGBA_1010102
3864 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3865 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3866 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3867}
3868
Vishnu Naire14c6b32022-08-06 04:20:15 +00003869sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003870 // 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 +00003871 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003872}
3873
Vishnu Naire14c6b32022-08-06 04:20:15 +00003874const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003875 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003876}
3877
Vishnu Naire14c6b32022-08-06 04:20:15 +00003878LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003879 return mSnapshot.get();
3880}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003881
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003882std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3883 return std::move(mSnapshot);
3884}
3885
3886void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3887 mSnapshot = std::move(snapshot);
3888}
3889
Patrick Williamsbb25f802022-08-30 23:02:34 +00003890const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003891 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003892}
3893
Patrick Williams7584c6a2022-10-29 02:10:58 +00003894sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003895 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003896 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3897 return result;
3898}
3899
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003900sp<LayerFE> Layer::getCompositionEngineLayerFE(
3901 const frontend::LayerHierarchy::TraversalPath& path) {
3902 for (auto& [p, layerFE] : mLayerFEs) {
3903 if (p == path) {
3904 return layerFE;
3905 }
3906 }
3907 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3908 mLayerFEs.emplace_back(path, layerFE);
3909 return layerFE;
3910}
3911
Patrick Williamsbb25f802022-08-30 23:02:34 +00003912void Layer::useSurfaceDamage() {
3913 if (mFlinger->mForceFullDamage) {
3914 surfaceDamageRegion = Region::INVALID_REGION;
3915 } else {
3916 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3917 }
3918}
3919
3920void Layer::useEmptyDamage() {
3921 surfaceDamageRegion.clear();
3922}
3923
3924bool Layer::isOpaque(const Layer::State& s) const {
3925 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3926 // layer's opaque flag.
3927 if (!hasSomethingToDraw()) {
3928 return false;
3929 }
3930
3931 // if the layer has the opaque flag, then we're always opaque
3932 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3933 return true;
3934 }
3935
3936 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003937 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003938 return true;
3939 }
3940
3941 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3942 return fillsColor() && getAlpha() == 1.0_hf;
3943}
3944
3945bool Layer::canReceiveInput() const {
3946 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3947}
3948
3949bool Layer::isVisible() const {
3950 if (!hasSomethingToDraw()) {
3951 return false;
3952 }
3953
3954 if (isHiddenByPolicy()) {
3955 return false;
3956 }
3957
3958 return getAlpha() > 0.0f || hasBlur();
3959}
3960
3961void Layer::onPostComposition(const DisplayDevice* display,
3962 const std::shared_ptr<FenceTime>& glDoneFence,
3963 const std::shared_ptr<FenceTime>& presentFence,
3964 const CompositorTiming& compositorTiming) {
3965 // mFrameLatencyNeeded is true when a new frame was latched for the
3966 // composition.
3967 if (!mBufferInfo.mFrameLatencyNeeded) return;
3968
3969 for (const auto& handle : mDrawingState.callbackHandles) {
3970 handle->gpuCompositionDoneFence = glDoneFence;
3971 handle->compositorTiming = compositorTiming;
3972 }
3973
3974 // Update mFrameTracker.
3975 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3976 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3977
3978 const int32_t layerId = getSequence();
3979 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3980
3981 const auto outputLayer = findOutputLayerForDisplay(display);
3982 if (outputLayer && outputLayer->requiresClientComposition()) {
3983 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3984 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3985 clientCompositionTimestamp,
3986 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3987 // Update the SurfaceFrames in the drawing state
3988 if (mDrawingState.bufferSurfaceFrameTX) {
3989 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3990 }
3991 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3992 surfaceFrame->setGpuComposition();
3993 }
3994 }
3995
3996 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3997 if (frameReadyFence->isValid()) {
3998 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3999 } else {
4000 // There was no fence for this frame, so assume that it was ready
4001 // to be presented at the desired present time.
4002 mFrameTracker.setFrameReadyTime(desiredPresentTime);
4003 }
4004
4005 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08004006 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004007 const std::optional<Fps> renderRate =
4008 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
4009
4010 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
4011 const auto gameMode = getGameMode();
4012
4013 if (presentFence->isValid()) {
4014 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
4015 refreshRate, renderRate, vote, gameMode);
4016 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4017 presentFence,
4018 FrameTracer::FrameEvent::PRESENT_FENCE);
4019 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
4020 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
4021 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04004022 // The HWC doesn't support present fences, so use the present timestamp instead.
4023 const nsecs_t presentTimestamp =
4024 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
4025
4026 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
4027 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
4028 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
4029
Patrick Williamsbb25f802022-08-30 23:02:34 +00004030 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
4031 refreshRate, renderRate, vote, gameMode);
4032 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
4033 mCurrentFrameNumber, actualPresentTime,
4034 FrameTracer::FrameEvent::PRESENT_FENCE);
4035 mFrameTracker.setActualPresentTime(actualPresentTime);
4036 }
4037 }
4038
4039 mFrameTracker.advanceFrame();
4040 mBufferInfo.mFrameLatencyNeeded = false;
4041}
4042
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004043bool Layer::willReleaseBufferOnLatch() const {
4044 return !mDrawingState.buffer && mBufferInfo.mBuffer;
4045}
4046
Patrick Williamsbb25f802022-08-30 23:02:34 +00004047bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00004048 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
4049 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
4050}
4051
4052bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004053 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
4054 getDrawingState().frameNumber);
4055
4056 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
4057
4058 if (refreshRequired) {
4059 return refreshRequired;
4060 }
4061
4062 // If the head buffer's acquire fence hasn't signaled yet, return and
4063 // try again later
4064 if (!fenceHasSignaled()) {
4065 ATRACE_NAME("!fenceHasSignaled()");
4066 mFlinger->onLayerUpdate();
4067 return false;
4068 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00004069 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004070
4071 // Capture the old state of the layer for comparisons later
4072 BufferInfo oldBufferInfo = mBufferInfo;
4073 const bool oldOpacity = isOpaque(mDrawingState);
4074 mPreviousFrameNumber = mCurrentFrameNumber;
4075 mCurrentFrameNumber = mDrawingState.frameNumber;
4076 gatherBufferInfo();
4077
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004078 if (mBufferInfo.mBuffer) {
4079 // We latched a buffer that will be presented soon. Clear the previously presented layer
4080 // stack list.
4081 mPreviouslyPresentedLayerStacks.clear();
4082 }
4083
4084 if (mDrawingState.buffer == nullptr) {
4085 const bool bufferReleased = oldBufferInfo.mBuffer != nullptr;
4086 recomputeVisibleRegions = bufferReleased;
4087 return bufferReleased;
4088 }
4089
Patrick Williamsbb25f802022-08-30 23:02:34 +00004090 if (oldBufferInfo.mBuffer == nullptr) {
4091 // the first time we receive a buffer, we need to trigger a
4092 // geometry invalidation.
4093 recomputeVisibleRegions = true;
4094 }
4095
4096 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
4097 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
4098 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
4099 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
4100 recomputeVisibleRegions = true;
4101 }
4102
4103 if (oldBufferInfo.mBuffer != nullptr) {
4104 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
4105 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
4106 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
4107 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
4108 recomputeVisibleRegions = true;
4109 }
4110 }
4111
4112 if (oldOpacity != isOpaque(mDrawingState)) {
4113 recomputeVisibleRegions = true;
4114 }
4115
4116 return true;
4117}
4118
4119bool Layer::hasReadyFrame() const {
4120 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4121}
4122
4123bool Layer::isProtected() const {
4124 return (mBufferInfo.mBuffer != nullptr) &&
4125 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4126}
4127
Patrick Williamsbb25f802022-08-30 23:02:34 +00004128void Layer::latchAndReleaseBuffer() {
4129 if (hasReadyFrame()) {
4130 bool ignored = false;
4131 latchBuffer(ignored, systemTime());
4132 }
4133 releasePendingBuffer(systemTime());
4134}
4135
4136PixelFormat Layer::getPixelFormat() const {
4137 return mBufferInfo.mPixelFormat;
4138}
4139
4140bool Layer::getTransformToDisplayInverse() const {
4141 return mBufferInfo.mTransformToDisplayInverse;
4142}
4143
4144Rect Layer::getBufferCrop() const {
4145 // this is the crop rectangle that applies to the buffer
4146 // itself (as opposed to the window)
4147 if (!mBufferInfo.mCrop.isEmpty()) {
4148 // if the buffer crop is defined, we use that
4149 return mBufferInfo.mCrop;
4150 } else if (mBufferInfo.mBuffer != nullptr) {
4151 // otherwise we use the whole buffer
4152 return mBufferInfo.mBuffer->getBounds();
4153 } else {
4154 // if we don't have a buffer yet, we use an empty/invalid crop
4155 return Rect();
4156 }
4157}
4158
4159uint32_t Layer::getBufferTransform() const {
4160 return mBufferInfo.mTransform;
4161}
4162
4163ui::Dataspace Layer::getDataSpace() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004164 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4165}
4166
4167ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4168 ui::Dataspace updatedDataspace = dataspace;
4169 // translate legacy dataspaces to modern dataspaces
4170 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00004171 // Treat unknown dataspaces as V0_sRGB
4172 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00004173 case ui::Dataspace::SRGB:
4174 updatedDataspace = ui::Dataspace::V0_SRGB;
4175 break;
4176 case ui::Dataspace::SRGB_LINEAR:
4177 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4178 break;
4179 case ui::Dataspace::JFIF:
4180 updatedDataspace = ui::Dataspace::V0_JFIF;
4181 break;
4182 case ui::Dataspace::BT601_625:
4183 updatedDataspace = ui::Dataspace::V0_BT601_625;
4184 break;
4185 case ui::Dataspace::BT601_525:
4186 updatedDataspace = ui::Dataspace::V0_BT601_525;
4187 break;
4188 case ui::Dataspace::BT709:
4189 updatedDataspace = ui::Dataspace::V0_BT709;
4190 break;
4191 default:
4192 break;
4193 }
4194
4195 return updatedDataspace;
4196}
4197
4198sp<GraphicBuffer> Layer::getBuffer() const {
4199 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4200}
4201
Vishnu Nairb76d99a2023-03-19 18:22:31 -07004202void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4203 mTransformHintLegacy = getFixedTransformHint();
4204 if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4205 mTransformHintLegacy = displayTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004206 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004207 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004208}
4209
4210const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4211 return mBufferInfo.mBuffer;
4212}
4213
4214bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004215 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004216 return false;
4217 }
4218
4219 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004220 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004221 mDrawingState.modified = true;
4222 setTransactionFlags(eTransactionNeeded);
4223 return true;
4224}
4225
4226bool Layer::fillsColor() const {
4227 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4228 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4229}
4230
4231bool Layer::hasBlur() const {
4232 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4233}
4234
Vishnu Nairba354102022-08-01 00:14:18 +00004235void Layer::updateSnapshot(bool updateGeometry) {
4236 if (!getCompositionEngineLayerFE()) {
4237 return;
4238 }
4239
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004240 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004241 if (updateGeometry) {
4242 prepareBasicGeometryCompositionState();
4243 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004244 snapshot->roundedCorner = getRoundedCornerState();
4245 snapshot->stretchEffect = getStretchEffect();
4246 snapshot->transformedBounds = mScreenBounds;
4247 if (mEffectiveShadowRadius > 0.f) {
4248 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4249
4250 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4251 // it if transparent regions are present. This may not be necessary since shadows are
4252 // typically cast by layers without transparent regions.
4253 snapshot->shadowSettings.boundaries = mBounds;
4254
4255 const float casterAlpha = snapshot->alpha;
4256 const bool casterIsOpaque =
4257 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4258
4259 // If the casting layer is translucent, we need to fill in the shadow underneath the
4260 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4261 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4262 snapshot->shadowSettings.ambientColor *= casterAlpha;
4263 snapshot->shadowSettings.spotColor *= casterAlpha;
4264 }
4265 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004266 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004267 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004268 snapshot->layerOpaqueFlagSet =
4269 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004270 snapshot->isHdrY410 = isHdrY410();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004271 sp<Layer> p = mDrawingParent.promote();
4272 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004273 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004274 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004275 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004276 }
4277 snapshot->bufferSize = getBufferSize(mDrawingState);
4278 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004279 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004280 preparePerFrameCompositionState();
4281}
4282
Vishnu Naire14c6b32022-08-06 04:20:15 +00004283void Layer::updateChildrenSnapshots(bool updateGeometry) {
4284 for (const sp<Layer>& child : mDrawingChildren) {
4285 child->updateSnapshot(updateGeometry);
4286 child->updateChildrenSnapshots(updateGeometry);
4287 }
4288}
4289
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004290void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4291 mSnapshot->layerMetadata = parentMetadata;
4292 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4293 for (const sp<Layer>& child : mDrawingChildren) {
4294 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4295 }
4296}
4297
4298void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4299 std::unordered_set<Layer*>& visited) {
4300 if (visited.find(this) != visited.end()) {
4301 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4302 return;
4303 }
4304 visited.insert(this);
4305
4306 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4307
4308 if (mDrawingState.zOrderRelatives.empty()) {
4309 return;
4310 }
4311 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4312 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4313 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4314 sp<Layer> relative = weakRelative.promote();
4315 if (!relative) {
4316 continue;
4317 }
4318 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4319 }
4320}
4321
Chavi Weingarten328a8312023-01-26 21:17:52 +00004322bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004323 TrustedPresentationListener const& listener) {
4324 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4325 mTrustedPresentationListener = listener;
4326 mTrustedPresentationThresholds = thresholds;
4327 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4328 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4329 mFlinger->mNumTrustedPresentationListeners++;
4330 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4331 mFlinger->mNumTrustedPresentationListeners--;
4332 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004333
4334 // Reset trusted presentation states to ensure we start the time again.
4335 mEnteredTrustedPresentationStateTime = -1;
4336 mLastReportedTrustedPresentationState = false;
4337 mLastComputedTrustedPresentationState = false;
4338
4339 // If there's a new trusted presentation listener, the code needs to go through the composite
4340 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4341 // we're already in the requested state.
4342 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004343}
4344
Vishnu Naira156f482023-02-22 00:23:38 +00004345void Layer::updateLastLatchTime(nsecs_t latchTime) {
4346 mLastLatchTime = latchTime;
4347}
4348
Arthur Hung0cc8a382023-06-02 01:35:52 +00004349void Layer::setIsSmallDirty() {
4350 if (!mFlinger->mScheduler->supportSmallDirtyDetection()) {
4351 return;
4352 }
4353
4354 if (mWindowType != WindowInfo::Type::APPLICATION &&
4355 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
4356 return;
4357 }
4358 Rect bounds = mDrawingState.surfaceDamageRegion.getBounds();
4359 if (!bounds.isValid()) {
4360 return;
4361 }
4362
4363 // If the damage region is a small dirty, this could give the hint for the layer history that
4364 // it could suppress the heuristic rate when calculating.
Tony Huang00886f42023-08-24 09:01:44 +00004365 mSmallDirty = mFlinger->mScheduler->isSmallDirtyArea(mOwnerUid,
4366 bounds.getWidth() * bounds.getHeight());
Arthur Hung0cc8a382023-06-02 01:35:52 +00004367}
4368
Mathias Agopian13127d82013-03-05 17:47:11 -08004369// ---------------------------------------------------------------------------
4370
Marin Shalamanov46084422020-10-13 12:33:42 +02004371std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004372 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4373 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004374}
4375
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004376} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004377
4378#if defined(__gl_h_)
4379#error "don't include gl/gl.h in this file"
4380#endif
4381
4382#if defined(__gl2_h_)
4383#error "don't include gl2/gl2.h in this file"
4384#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004385
4386// TODO(b/129481165): remove the #pragma below and fix conversion issues
4387#pragma clang diagnostic pop // ignored "-Wconversion"