blob: f7800bb4855e3840df561fd4e1c0f925bfa1c19f [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>
Vishnu Nair0f085c62019-08-30 08:49:12 -070030#include <binder/IPCThreadState.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000031#include <compositionengine/CompositionEngine.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080032#include <compositionengine/Display.h>
Lloyd Piquea83776c2019-01-29 18:42:32 -080033#include <compositionengine/LayerFECompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080034#include <compositionengine/OutputLayer.h>
35#include <compositionengine/impl/OutputLayerCompositionState.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070036#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070037#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070038#include <cutils/properties.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070039#include <ftl/enum.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080040#include <ftl/fake_guard.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080041#include <gui/BufferItem.h>
42#include <gui/LayerDebugInfo.h>
43#include <gui/Surface.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000044#include <gui/TraceUtils.h>
Alec Mourie60041e2019-06-14 18:59:51 -070045#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070046#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080047#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070048#include <stdint.h>
49#include <stdlib.h>
50#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000051#include <system/graphics-base-v1.0.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080052#include <ui/DebugUtils.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000053#include <ui/FloatRect.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080054#include <ui/GraphicBuffer.h>
Sally Qif6918d42023-08-07 15:28:30 -070055#include <ui/HdrRenderTypeUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080056#include <ui/PixelFormat.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000057#include <ui/Rect.h>
58#include <ui/Transform.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059#include <utils/Errors.h>
60#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080061#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080063#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Alec Mourie60041e2019-06-14 18:59:51 -070065#include <algorithm>
66#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070067#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070068#include <sstream>
69
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070070#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080071#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070072#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070073#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +000074#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000075#include "FrontEnd/LayerHandle.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080076#include "LayerProtoHelper.h"
Josh Gao194ff392022-09-08 16:19:29 -070077#include "MutexUtils.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080079#include "TimeStats/TimeStats.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070080#include "TunnelModeEnabledReporter.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070081
David Sodman41fdfc92017-11-06 16:09:56 -080082#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000083#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085namespace android {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010086namespace {
87constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000088
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000089const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000090
Patrick Williamsbb25f802022-08-30 23:02:34 +000091bool assignTransform(ui::Transform* dst, ui::Transform& from) {
92 if (*dst == from) {
93 return false;
94 }
95 *dst = from;
96 return true;
97}
98
99TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
100 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
101 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
102 const auto frameRateCompatibility = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700103 switch (frameRate.vote.type) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000104 case Layer::FrameRateCompatibility::Default:
105 return FrameRateCompatibility::Default;
106 case Layer::FrameRateCompatibility::ExactOrMultiple:
107 return FrameRateCompatibility::ExactOrMultiple;
108 default:
109 return FrameRateCompatibility::Undefined;
110 }
111 }();
112
113 const auto seamlessness = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700114 switch (frameRate.vote.seamlessness) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000115 case scheduler::Seamlessness::OnlySeamless:
116 return Seamlessness::ShouldBeSeamless;
117 case scheduler::Seamlessness::SeamedAndSeamless:
118 return Seamlessness::NotRequired;
119 default:
120 return Seamlessness::Undefined;
121 }
122 }();
123
Rachel Leece6e0042023-06-27 11:22:54 -0700124 return TimeStats::SetFrameRateVote{.frameRate = frameRate.vote.rate.getValue(),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000125 .frameRateCompatibility = frameRateCompatibility,
126 .seamlessness = seamlessness};
127}
128
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100129} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800130
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700131using namespace ftl::flag_operators;
132
Yiwei Zhang5434a782018-12-05 18:06:32 -0800133using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000134using frontend::LayerSnapshot;
135using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800136using gui::GameMode;
137using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500138using gui::WindowInfo;
Vishnu Nair494a2e42023-11-10 17:21:19 -0800139using ui::Size;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800140
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700141using PresentState = frametimeline::SurfaceFrame::PresentState;
142
Kean Mariotti4ba343c2023-04-19 13:31:02 +0000143Layer::Layer(const surfaceflinger::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),
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000152 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000153 ALOGV("Creating Layer %s", getDebugName());
154
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700155 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700156 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
157 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
158 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700159 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
160 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700161 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700162 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700163 mDrawingState.z = 0;
164 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700165 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700166 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700167 mDrawingState.transform.set(0, 0);
168 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +0000169 mDrawingState.previousFrameNumber = 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;
Rachel Lee70f7b692023-11-22 11:24:02 -0800196 mDrawingState.frameRateSelectionStrategy = FrameRateSelectionStrategy::Propagate;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700197
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700198 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
199 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700200 mDrawingState.color.r = -1.0_hf;
201 mDrawingState.color.g = -1.0_hf;
202 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700203 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700204
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500205 mFrameTracker.setDisplayRefreshPeriod(
206 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700207
Vishnu Naircb8be502022-10-12 19:03:23 +0000208 mOwnerUid = args.ownerUid;
209 mOwnerPid = args.ownerPid;
Tony Huangf3621102023-09-04 17:14:22 +0800210 mOwnerAppId = mOwnerUid % PER_USER_RANGE;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000211
212 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
213 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
214 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000215
216 mSnapshot->sequence = sequence;
217 mSnapshot->name = getDebugName();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000218 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000219 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800220}
221
222void Layer::onFirstRef() {
223 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700224}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700225
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700226Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000227 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
228 "Layer destructor called off the main thread.");
229
Patrick Williamsbb25f802022-08-30 23:02:34 +0000230 // The original layer and the clone layer share the same texture and buffer. Therefore, only
231 // one of the layers, in this case the original layer, needs to handle the deletion. The
232 // original layer and the clone should be removed at the same time so there shouldn't be any
233 // issue with the clone layer trying to use the texture.
234 if (mBufferInfo.mBuffer != nullptr) {
235 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
236 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800237 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000238 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000239 const int32_t layerId = getSequence();
240 mFlinger->mTimeStats->onDestroy(layerId);
241 mFlinger->mFrameTracer->onDestroy(layerId);
242
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000243 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700244 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700245
246 if (mDrawingState.sidebandStream != nullptr) {
247 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
248 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700249 if (mHadClonedChild) {
Vishnu Nair3be61902023-04-26 19:47:29 -0700250 auto& roots = mFlinger->mLayerMirrorRoots;
251 roots.erase(std::remove(roots.begin(), roots.end(), this), roots.end());
Robert Carr6a0382d2021-07-01 15:57:17 -0700252 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000253 if (hasTrustedPresentationListener()) {
254 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000255 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000256 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700257}
258
Mathias Agopian13127d82013-03-05 17:47:11 -0800259// ---------------------------------------------------------------------------
260// callbacks
261// ---------------------------------------------------------------------------
262
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700263void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700264 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700265 return;
266 }
Robert Carr2e102c92018-10-23 12:11:15 -0700267
Robert Carr6a160312021-05-17 12:08:20 -0700268 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700269 if (strongRelative == nullptr) {
270 setZOrderRelativeOf(nullptr);
271 return;
272 }
273
274 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700275 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700276 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800277 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700278 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700279}
280
281void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700282 if (!mRemovedFromDrawingState) {
283 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700284 mFlinger->mScheduler->deregisterLayer(this);
285 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000286 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000287
Ady Abrahamd11bade2022-08-01 16:18:03 -0700288 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700289}
Chia-I Wu38512252017-05-17 14:36:16 -0700290
chaviw68d4dab2020-06-08 15:07:32 -0700291sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000292 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700293 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700294 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700295 }
296 return parent->getRootLayer();
297}
298
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700299void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700300 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
301 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700302 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700303
Josh Gao194ff392022-09-08 16:19:29 -0700304 REQUIRE_MUTEX(mFlinger->mStateLock);
305 traverse(LayerVector::StateSet::Current,
306 [&](Layer* layer) REQUIRES(layer->mFlinger->mStateLock) {
307 layer->removeFromCurrentState();
308 layer->removeRelativeZ(layersInTree);
309 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700310}
311
chaviw61626f22018-11-15 16:26:27 -0800312void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700313 if (mRemovedFromDrawingState) {
314 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700315 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700316 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700317 }
chaviw61626f22018-11-15 16:26:27 -0800318
319 for (const auto& child : mCurrentChildren) {
320 child->addToCurrentState();
321 }
322}
323
Mathias Agopian13127d82013-03-05 17:47:11 -0800324// ---------------------------------------------------------------------------
325// set-up
326// ---------------------------------------------------------------------------
327
chaviw13fdc492017-06-27 12:40:18 -0700328bool Layer::getPremultipledAlpha() const {
329 return mPremultipliedAlpha;
330}
331
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700332sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800333 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700334 if (mGetHandleCalled) {
335 ALOGE("Get handle called twice" );
336 return nullptr;
337 }
338 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700339 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000340 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800341}
342
343// ---------------------------------------------------------------------------
344// h/w composer set-up
345// ---------------------------------------------------------------------------
346
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700347static Rect reduce(const Rect& win, const Region& exclude) {
348 if (CC_LIKELY(exclude.isEmpty())) {
349 return win;
350 }
351 if (exclude.isRect()) {
352 return win.reduce(exclude.getBounds());
353 }
354 return Region(win).subtract(exclude).getBounds();
355}
356
Dan Stoza80d61162017-12-20 15:57:52 -0800357static FloatRect reduce(const FloatRect& win, const Region& exclude) {
358 if (CC_LIKELY(exclude.isEmpty())) {
359 return win;
360 }
361 // Convert through Rect (by rounding) for lack of FloatRegion
362 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
363}
364
Vishnu Nair4351ad52019-02-11 14:13:02 -0800365Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800366 if (!reduceTransparentRegion) {
367 return Rect{mScreenBounds};
368 }
369
370 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800371 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800372 // Transform to screen space.
373 bounds = t.transform(bounds);
374 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700375}
376
Vishnu Nair4351ad52019-02-11 14:13:02 -0800377FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000378 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800379 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700380}
381
Vishnu Nairf0c28512019-02-08 12:40:28 -0800382FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
383 // Subtract the transparent region and snap to the bounds.
384 return reduce(mBounds, activeTransparentRegion);
385}
386
Chavi Weingarten076acac2023-01-19 17:20:43 +0000387// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000388void Layer::updateTrustedPresentationState(const DisplayDevice* display,
389 const frontend::LayerSnapshot* snapshot,
390 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000391 if (!hasTrustedPresentationListener()) {
392 return;
393 }
394 const bool lastState = mLastComputedTrustedPresentationState;
395 mLastComputedTrustedPresentationState = false;
396
397 if (!leaveState) {
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000398 const auto outputLayer = findOutputLayerForDisplay(display, snapshot->path);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000399 if (outputLayer != nullptr) {
400 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
401 Region coveredRegion =
402 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
403 mLastComputedTrustedPresentationState =
404 computeTrustedPresentationState(snapshot->geomLayerBounds,
405 snapshot->sourceBounds(), coveredRegion,
406 snapshot->transformedBounds,
407 snapshot->alpha,
408 snapshot->geomLayerTransform,
409 mTrustedPresentationThresholds);
410 } else {
411 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
412 "TrustedPresentationState",
413 getDebugName());
414 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000415 }
416 }
417 const bool newState = mLastComputedTrustedPresentationState;
418 if (lastState && !newState) {
419 // We were in the trusted presentation state, but now we left it,
420 // emit the callback if needed
421 if (mLastReportedTrustedPresentationState) {
422 mLastReportedTrustedPresentationState = false;
423 mTrustedPresentationListener.invoke(false);
424 }
425 // Reset the timer
426 mEnteredTrustedPresentationStateTime = -1;
427 } else if (!lastState && newState) {
428 // We were not in the trusted presentation state, but we entered it, begin the timer
429 // and make sure this gets called at least once more!
430 mEnteredTrustedPresentationStateTime = time_in_ms;
431 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
432 }
433
434 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
435 if (!mLastReportedTrustedPresentationState && newState &&
436 (time_in_ms - mEnteredTrustedPresentationStateTime >
437 mTrustedPresentationThresholds.stabilityRequirementMs)) {
438 mLastReportedTrustedPresentationState = true;
439 mTrustedPresentationListener.invoke(true);
440 }
441}
442
443/**
444 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
445 * of how the parameters and thresholds are interpreted. The general spirit is
446 * to produce an upper bound on the amount of the buffer which was presented.
447 */
448bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
449 const Region& coveredRegion,
450 const FloatRect& screenBounds, float alpha,
451 const ui::Transform& effectiveTransform,
452 const TrustedPresentationThresholds& thresholds) {
453 if (alpha < thresholds.minAlpha) {
454 return false;
455 }
456 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
457 return false;
458 }
459 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
460 return false;
461 }
462
463 const float sx = effectiveTransform.dsdx();
464 const float sy = effectiveTransform.dsdy();
465 float fractionRendered = std::min(sx * sy, 1.0f);
466
467 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
468 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
469 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
470
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000471 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
472 // Compute the size of all the rects since they may be disconnected.
473 float coveredSize = 0;
474 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
475 float size = rect->width() * rect->height();
476 coveredSize += size;
477 }
478
479 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000480
481 if (fractionRendered < thresholds.minFractionRendered) {
482 return false;
483 }
484
485 return true;
486}
487
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700488void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
489 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800490 const State& s(getDrawingState());
491
492 // Calculate effective layer transform
493 mEffectiveTransform = parentTransform * getActiveTransform(s);
494
Garfield Tan2c1782c2022-02-16 15:25:05 -0800495 if (CC_UNLIKELY(!isTransformValid())) {
496 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
497 getDebugName());
498 return;
499 }
500
Vishnu Nair4351ad52019-02-11 14:13:02 -0800501 // Transform parent bounds to layer space
502 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
503
Vishnu Nairc652ff82019-03-15 12:48:54 -0700504 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800505 mSourceBounds = computeSourceBounds(parentBounds);
506
507 // Calculate bounds by croping diplay frame with layer crop and parent bounds
508 FloatRect bounds = mSourceBounds;
509 const Rect layerCrop = getCrop(s);
510 if (!layerCrop.isEmpty()) {
511 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
512 }
513 bounds = bounds.intersect(parentBounds);
514
515 mBounds = bounds;
516 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700517
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700518 // Use the layer's own shadow radius if set. Otherwise get the radius from
519 // parent.
520 if (s.shadowRadius > 0.f) {
521 mEffectiveShadowRadius = s.shadowRadius;
522 } else {
523 mEffectiveShadowRadius = parentShadowRadius;
524 }
525
526 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
527 // don't pass it to its children.
528 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
529
Vishnu Nair4351ad52019-02-11 14:13:02 -0800530 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700531 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800532 }
Vishnu Nairba354102022-08-01 00:14:18 +0000533
534 if (mPotentialCursor) {
535 prepareCursorCompositionState();
536 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800537}
538
Vishnu Nair60356342018-11-13 13:00:45 -0800539Rect Layer::getCroppedBufferSize(const State& s) const {
540 Rect size = getBufferSize(s);
541 Rect crop = getCrop(s);
542 if (!crop.isEmpty() && size.isValid()) {
543 size.intersect(crop, &size);
544 } else if (!crop.isEmpty()) {
545 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700546 }
Vishnu Nair60356342018-11-13 13:00:45 -0800547 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800548}
549
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700550void Layer::setupRoundedCornersCropCoordinates(Rect win,
551 const FloatRect& roundedCornersCrop) const {
552 // Translate win by the rounded corners rect coordinates, to have all values in
553 // layer coordinate space.
554 win.left -= roundedCornersCrop.left;
555 win.right -= roundedCornersCrop.left;
556 win.top -= roundedCornersCrop.top;
557 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700558}
559
Lloyd Piquede196652020-01-22 17:29:58 -0800560void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800561 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800562 const auto alpha = static_cast<float>(getAlpha());
563 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700564 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800565
566 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
567 if (!opaque || alpha != 1.0f) {
568 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
569 : Hwc2::IComposerClient::BlendMode::COVERAGE;
570 }
571
Alec Mourif4af03e2023-02-11 00:25:24 +0000572 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000573 auto* snapshot = editLayerSnapshot();
574 snapshot->outputFilter = getOutputFilter();
575 snapshot->isVisible = isVisible();
576 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
Vishnu Naird9e4f462023-10-06 04:05:45 +0000577 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800578
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000579 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800580 contentDirty = false;
581
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000582 snapshot->geomLayerBounds = mBounds;
583 snapshot->geomLayerTransform = getTransform();
584 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
585 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000586 snapshot->localTransform = getActiveTransform(drawingState);
587 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000588 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
589 snapshot->alpha = alpha;
Vishnu Nairc6384702023-07-31 12:22:20 -0700590 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
591 snapshot->blurRegions = getBlurRegions();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000592 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800593}
594
Lloyd Piquede196652020-01-22 17:29:58 -0800595void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800596 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000597 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700598
Alec Mourif4af03e2023-02-11 00:25:24 +0000599 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000600 snapshot->geomBufferSize = getBufferSize(drawingState);
601 snapshot->geomContentCrop = getBufferCrop();
602 snapshot->geomCrop = getCrop(drawingState);
603 snapshot->geomBufferTransform = getBufferTransform();
604 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
605 snapshot->geomUsesSourceCrop = usesSourceCrop();
606 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800607
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000608 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800609 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
610 for (const auto& [key, mandatory] : supportedMetadata) {
611 const auto& genericLayerMetadataCompatibilityMap =
612 mFlinger->getGenericLayerMetadataKeyMap();
613 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
614 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
615 continue;
616 }
617 const uint32_t id = compatIter->second;
618
619 auto it = drawingState.metadata.mMap.find(id);
620 if (it == std::end(drawingState.metadata.mMap)) {
621 continue;
622 }
623
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000624 snapshot->metadata.emplace(key,
625 compositionengine::GenericLayerMetadataEntry{mandatory,
626 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800627 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800628}
David Sodmanba340492018-08-05 21:51:33 -0700629
Lloyd Piquede196652020-01-22 17:29:58 -0800630void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800631 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000632 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000633 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800634
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000635 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800636
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000637 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
638 snapshot->dataspace = getDataSpace();
639 snapshot->colorTransform = getColorTransform();
640 snapshot->colorTransformIsIdentity = !hasColorTransform();
641 snapshot->surfaceDamage = surfaceDamageRegion;
642 snapshot->hasProtectedContent = isProtected();
643 snapshot->dimmingEnabled = isDimmingEnabled();
Sally Qi963049b2023-03-23 14:06:21 -0700644 snapshot->currentHdrSdrRatio = getCurrentHdrSdrRatio();
645 snapshot->desiredHdrSdrRatio = getDesiredHdrSdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000646 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800647
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700648 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700649
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000650 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800651
652 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400653 // Rounded corners no longer force client composition, since we may use a
654 // hole punch so that the layer will appear to have rounded corners.
Alec Mouri994761f2023-08-04 21:50:55 +0000655 if (drawShadows() || snapshot->stretchEffect.hasEffect()) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000656 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800657 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700658 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairc6384702023-07-31 12:22:20 -0700659 snapshot->blurRegions = getBlurRegions();
660 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400661
662 // Layer framerate is used in caching decisions.
663 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
664 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000665 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000666
667 if (hasBufferOrSidebandStream()) {
668 preparePerFrameBufferCompositionState();
669 } else {
670 preparePerFrameEffectsCompositionState();
671 }
672}
673
674void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000675 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000676 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000677 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000678 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
679 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000680 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
681 return;
682 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000683 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000684 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800685 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
686 snapshot->compositionType =
687 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000688 } else {
689 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000690 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
691 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000692 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
693 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
694 }
695
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000696 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000697 snapshot->acquireFence = mBufferInfo.mFence;
698 snapshot->frameNumber = mBufferInfo.mFrameNumber;
699 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000700}
701
702void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000703 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000704 auto* snapshot = editLayerSnapshot();
705 snapshot->color = getColor();
706 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000707 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800708}
709
Lloyd Piquede196652020-01-22 17:29:58 -0800710void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800711 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000712 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000713 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800714
715 // Apply the layer's transform, followed by the display's global transform
716 // Here we're guaranteed that the layer's transform preserves rects
717 Rect win = getCroppedBufferSize(drawingState);
718 // Subtract the transparent region and snap to the bounds
719 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
720 Rect frame(getTransform().transform(bounds));
721
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000722 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800723}
724
Lloyd Piquea83776c2019-01-29 18:42:32 -0800725const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700726 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800727}
728
Mathias Agopian13127d82013-03-05 17:47:11 -0800729// ---------------------------------------------------------------------------
730// drawing...
731// ---------------------------------------------------------------------------
732
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500733aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
734 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700735 const auto outputLayer = findOutputLayerForDisplay(&display);
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000736 return getCompositionType(outputLayer);
737}
738
739aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
740 const compositionengine::OutputLayer* outputLayer) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -0800741 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500742 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800743 }
744 if (outputLayer->getState().hwc) {
745 return (*outputLayer->getState().hwc).hwcCompositionType;
746 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500747 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800748 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800749}
750
Mathias Agopian13127d82013-03-05 17:47:11 -0800751// ----------------------------------------------------------------------------
752// local state
753// ----------------------------------------------------------------------------
754
David Sodman41fdfc92017-11-06 16:09:56 -0800755bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800756 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700757 if (s.flags & layer_state_t::eLayerSecure) {
758 return true;
759 }
760
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000761 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700762 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700763}
764
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100765void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
766 std::vector<JankData>& jankData) {
767 if (mPendingJankClassifications.empty() ||
768 !mPendingJankClassifications.front()->getJankType()) {
769 return;
770 }
771
772 bool includeJankData = false;
773 for (const auto& handle : handles) {
774 for (const auto& cb : handle->callbackIds) {
775 if (cb.includeJankData) {
776 includeJankData = true;
777 break;
778 }
779 }
780
781 if (includeJankData) {
782 jankData.reserve(mPendingJankClassifications.size());
783 break;
784 }
785 }
786
787 while (!mPendingJankClassifications.empty() &&
788 mPendingJankClassifications.front()->getJankType()) {
789 if (includeJankData) {
790 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
791 mPendingJankClassifications.front();
Pascal Muetschardac7bcd92023-10-03 15:05:36 +0200792 jankData.emplace_back(JankData(surfaceFrame->getToken(),
793 surfaceFrame->getJankType().value(),
794 surfaceFrame->getRenderRate().getPeriodNsecs()));
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100795 }
796 mPendingJankClassifications.pop_front();
797 }
798}
799
Mathias Agopian13127d82013-03-05 17:47:11 -0800800// ----------------------------------------------------------------------------
801// transaction
802// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800803
Vishnu Naira156f482023-02-22 00:23:38 +0000804uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700805 ATRACE_CALL();
806
Robert Carr0758e5d2021-03-11 22:15:04 -0800807 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700808 mDrawingStateModified = mDrawingState.modified;
809 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700810
Alec Mourib416efd2018-09-06 21:01:59 +0000811 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700812
Robert Carr6a160312021-05-17 12:08:20 -0700813 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800814 // invalidate and recompute the visible regions if needed
815 flags |= Layer::eVisibleRegion;
816 }
817
Robert Carr6a160312021-05-17 12:08:20 -0700818 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800819 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000820 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800821 flags |= eVisibleRegion;
822 this->contentDirty = true;
823
824 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700825 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800826 }
827
Arthur Hung9ed43392022-05-27 06:31:57 +0000828 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
829 mFlinger->mUpdateInputInfo = true;
830 }
831
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700832 commitTransaction();
Robert Carra1257842020-01-31 13:48:28 -0800833
Mathias Agopian13127d82013-03-05 17:47:11 -0800834 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800835}
836
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700837void Layer::commitTransaction() {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000838 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
839 // bufferSurfaceFrameTX will be presented in latchBuffer.
840 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
841 if (surfaceFrame->getPresentState() != PresentState::Presented) {
842 // With applyPendingStates, we could end up having presented surfaceframes from previous
843 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800844 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000845 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
846 }
847 }
Robert Carr6a160312021-05-17 12:08:20 -0700848 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700849}
850
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700851uint32_t Layer::clearTransactionFlags(uint32_t mask) {
852 const auto flags = mTransactionFlags & mask;
853 mTransactionFlags &= ~mask;
854 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800855}
856
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700857void Layer::setTransactionFlags(uint32_t mask) {
858 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800859}
860
Robert Carr1f0a16a2016-10-24 16:27:39 -0700861bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
862 ssize_t idx = mCurrentChildren.indexOf(childLayer);
863 if (idx < 0) {
864 return false;
865 }
866 if (childLayer->setLayer(z)) {
867 mCurrentChildren.removeAt(idx);
868 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800869 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700870 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800871 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700872}
873
Robert Carr503c7042017-09-27 15:06:08 -0700874bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
875 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
876 ssize_t idx = mCurrentChildren.indexOf(childLayer);
877 if (idx < 0) {
878 return false;
879 }
880 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
881 mCurrentChildren.removeAt(idx);
882 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800883 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700884 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800885 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700886}
887
Robert Carrae060832016-11-28 10:51:00 -0800888bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700889 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
890 mDrawingState.sequence++;
891 mDrawingState.z = z;
892 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700893
Robert Carra70e91c2021-06-11 13:59:52 -0700894 mFlinger->mSomeChildrenChanged = true;
895
Robert Carrdb66e622017-04-10 16:55:57 -0700896 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700897 if (mDrawingState.zOrderRelativeOf != nullptr) {
898 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700899 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700900 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700901 }
chaviw606e5cf2019-03-01 10:12:10 -0800902 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700903 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800904 setTransactionFlags(eTransactionNeeded);
905 return true;
906}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700907
Robert Carrdb66e622017-04-10 16:55:57 -0700908void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700909 mDrawingState.zOrderRelatives.remove(relative);
910 mDrawingState.sequence++;
911 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700912 setTransactionFlags(eTransactionNeeded);
913}
914
915void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700916 mDrawingState.zOrderRelatives.add(relative);
917 mDrawingState.modified = true;
918 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700919 setTransactionFlags(eTransactionNeeded);
920}
921
chaviw606e5cf2019-03-01 10:12:10 -0800922void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700923 mDrawingState.zOrderRelativeOf = relativeOf;
924 mDrawingState.sequence++;
925 mDrawingState.modified = true;
926 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700927
chaviw606e5cf2019-03-01 10:12:10 -0800928 setTransactionFlags(eTransactionNeeded);
929}
930
Robert Carr503d2bd2017-12-04 15:49:47 -0800931bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000932 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700933 if (relative == nullptr) {
934 return false;
935 }
936
Robert Carr6a160312021-05-17 12:08:20 -0700937 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
938 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800939 return false;
940 }
941
Robert Carr88b85e12022-03-21 15:47:35 -0700942 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
943 (relative->mDrawingState.zOrderRelativeOf == this)) {
944 ALOGE("Detected relative layer loop between %s and %s",
945 mName.c_str(), relative->mName.c_str());
946 ALOGE("Ignoring new call to set relative layer");
947 return false;
948 }
949
Robert Carra70e91c2021-06-11 13:59:52 -0700950 mFlinger->mSomeChildrenChanged = true;
951
Robert Carr6a160312021-05-17 12:08:20 -0700952 mDrawingState.sequence++;
953 mDrawingState.modified = true;
954 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700955
Robert Carr6a160312021-05-17 12:08:20 -0700956 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700957 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700958 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700959 }
chaviw606e5cf2019-03-01 10:12:10 -0800960 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700961 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700962
963 setTransactionFlags(eTransactionNeeded);
964
965 return true;
966}
967
Winson Chunga30f7c92021-06-29 15:42:56 -0700968bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
969 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
970 mDrawingState.isTrustedOverlay = isTrustedOverlay;
971 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000972 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700973 setTransactionFlags(eTransactionNeeded);
974 return true;
975}
976
977bool Layer::isTrustedOverlay() const {
978 if (getDrawingState().isTrustedOverlay) {
979 return true;
980 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000981 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700982 return (p != nullptr) && p->isTrustedOverlay();
983}
984
Dan Stoza9e56aa02015-11-02 13:00:03 -0800985bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700986 if (mDrawingState.color.a == alpha) return false;
987 mDrawingState.sequence++;
988 mDrawingState.color.a = alpha;
989 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800990 setTransactionFlags(eTransactionNeeded);
991 return true;
992}
chaviw13fdc492017-06-27 12:40:18 -0700993
Valerie Haudd0b7572019-01-29 14:59:27 -0800994bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700995 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700996 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800997 }
Robert Carr6a160312021-05-17 12:08:20 -0700998 mDrawingState.sequence++;
999 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -08001000 setTransactionFlags(eTransactionNeeded);
1001
Robert Carr6a160312021-05-17 12:08:20 -07001002 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001003 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001004 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001005 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001006 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Kean Mariotti4ba343c2023-04-19 13:31:02 +00001007 surfaceflinger::LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
1008 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001009
Valerie Haudd0b7572019-01-29 14:59:27 -08001010 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001011 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001012 mFlinger->mLayersAdded = true;
1013 // set up SF to handle added color layer
1014 if (isRemovedFromCurrentState()) {
Josh Gao194ff392022-09-08 16:19:29 -07001015 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001016 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001017 }
1018 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001019 } else if (mDrawingState.bgColorLayer && alpha == 0) {
Josh Gao194ff392022-09-08 16:19:29 -07001020 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001021 mDrawingState.bgColorLayer->reparent(nullptr);
1022 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001023 return true;
1024 }
1025
Robert Carr6a160312021-05-17 12:08:20 -07001026 mDrawingState.bgColorLayer->setColor(color);
1027 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1028 mDrawingState.bgColorLayer->setAlpha(alpha);
1029 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001030
chaviw13fdc492017-06-27 12:40:18 -07001031 return true;
1032}
1033
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001034bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001035 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001036
Robert Carr6a160312021-05-17 12:08:20 -07001037 mDrawingState.sequence++;
1038 mDrawingState.cornerRadius = cornerRadius;
1039 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001040 setTransactionFlags(eTransactionNeeded);
1041 return true;
1042}
1043
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001044bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001045 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001046 // If we start or stop drawing blur then the layer's visibility state may change so increment
1047 // the magic sequence number.
1048 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1049 mDrawingState.sequence++;
1050 }
Robert Carr6a160312021-05-17 12:08:20 -07001051 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1052 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001053 setTransactionFlags(eTransactionNeeded);
1054 return true;
1055}
Marissa Wall61c58622018-07-18 10:12:20 -07001056
Mathias Agopian13127d82013-03-05 17:47:11 -08001057bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001058 mDrawingState.sequence++;
1059 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001060 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001061 setTransactionFlags(eTransactionNeeded);
1062 return true;
1063}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001064
Lucas Dupinc3800b82020-10-02 16:24:48 -07001065bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001066 // If we start or stop drawing blur then the layer's visibility state may change so increment
1067 // the magic sequence number.
1068 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1069 mDrawingState.sequence++;
1070 }
Robert Carr6a160312021-05-17 12:08:20 -07001071 mDrawingState.blurRegions = blurRegions;
1072 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001073 setTransactionFlags(eTransactionNeeded);
1074 return true;
1075}
1076
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001077bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001078 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1079 if (mDrawingState.flags == newFlags) return false;
1080 mDrawingState.sequence++;
1081 mDrawingState.flags = newFlags;
1082 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001083 setTransactionFlags(eTransactionNeeded);
1084 return true;
1085}
Robert Carr99e27f02016-06-16 15:18:02 -07001086
chaviw25714502021-02-11 10:01:08 -08001087bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001088 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001089 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001090 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001091
Robert Carr6a160312021-05-17 12:08:20 -07001092 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001093 setTransactionFlags(eTransactionNeeded);
1094 return true;
1095}
Robert Carr8d5227b2017-03-16 15:41:03 -07001096
Evan Roskyef876c92019-01-25 17:46:06 -08001097bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001098 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1099 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001100 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001101 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001102}
1103
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001104bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001105 if (mDrawingState.layerStack == layerStack) return false;
1106 mDrawingState.sequence++;
1107 mDrawingState.layerStack = layerStack;
1108 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001109 setTransactionFlags(eTransactionNeeded);
1110 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001111}
1112
Peiyong Linc502cb72019-03-01 15:00:23 -08001113bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001114 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001115 return false;
1116 }
Robert Carr6a160312021-05-17 12:08:20 -07001117 mDrawingState.sequence++;
1118 mDrawingState.colorSpaceAgnostic = agnostic;
1119 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001120 setTransactionFlags(eTransactionNeeded);
1121 return true;
1122}
1123
Sally Qi81d95e62022-03-21 19:41:33 -07001124bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1125 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1126
1127 mDrawingState.sequence++;
1128 mDrawingState.dimmingEnabled = dimmingEnabled;
1129 mDrawingState.modified = true;
1130 setTransactionFlags(eTransactionNeeded);
1131 return true;
1132}
1133
Ana Krulecc84d09b2019-11-02 23:10:29 +01001134bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001135 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1136 mDrawingState.frameRateSelectionPriority = priority;
1137 mDrawingState.sequence++;
1138 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001139 setTransactionFlags(eTransactionNeeded);
1140 return true;
1141}
1142
1143int32_t Layer::getFrameRateSelectionPriority() const {
1144 // Check if layer has priority set.
1145 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1146 return mDrawingState.frameRateSelectionPriority;
1147 }
1148 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001149 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001150 if (parent != nullptr) {
1151 return parent->getFrameRateSelectionPriority();
1152 }
1153
1154 return Layer::PRIORITY_UNSET;
1155}
1156
Andy Labrada096227e2022-06-15 16:58:11 +00001157bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1158 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1159 mDrawingState.defaultFrameRateCompatibility = compatibility;
1160 mDrawingState.modified = true;
Vishnu Nair80e8cfe2023-09-29 17:03:45 -07001161 mFlinger->mScheduler->setDefaultFrameRateCompatibility(sequence, compatibility);
Andy Labrada096227e2022-06-15 16:58:11 +00001162 setTransactionFlags(eTransactionNeeded);
1163 return true;
1164}
1165
Vishnu Nair3fbe3262023-09-29 17:07:00 -07001166scheduler::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
Andy Labrada096227e2022-06-15 16:58:11 +00001167 return mDrawingState.defaultFrameRateCompatibility;
1168}
1169
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001170bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1171 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1172};
1173
Vishnu Nair73908d12022-10-24 21:46:42 -07001174ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1175 bool useDrawing = state == LayerVector::StateSet::Drawing;
1176 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1177 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001178 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001179 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001180 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001181}
1182
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001183bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001184 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001185 return false;
1186 }
1187
Robert Carr6a160312021-05-17 12:08:20 -07001188 mDrawingState.sequence++;
1189 mDrawingState.shadowRadius = shadowRadius;
1190 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001191 setTransactionFlags(eTransactionNeeded);
1192 return true;
1193}
1194
Vishnu Nair6213bd92020-05-08 17:42:25 -07001195bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001196 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001197 return false;
1198 }
1199
Robert Carr6a160312021-05-17 12:08:20 -07001200 mDrawingState.sequence++;
1201 mDrawingState.fixedTransformHint = fixedTransformHint;
1202 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001203 setTransactionFlags(eTransactionNeeded);
1204 return true;
1205}
1206
John Reckcdb4ed72021-02-04 13:39:33 -05001207bool Layer::setStretchEffect(const StretchEffect& effect) {
1208 StretchEffect temp = effect;
1209 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001210 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001211 return false;
1212 }
Robert Carr6a160312021-05-17 12:08:20 -07001213 mDrawingState.sequence++;
1214 mDrawingState.stretchEffect = temp;
1215 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001216 setTransactionFlags(eTransactionNeeded);
1217 return true;
1218}
1219
John Reckc00c6692021-02-16 11:37:33 -05001220StretchEffect Layer::getStretchEffect() const {
1221 if (mDrawingState.stretchEffect.hasEffect()) {
1222 return mDrawingState.stretchEffect;
1223 }
1224
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001225 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001226 if (parent != nullptr) {
1227 auto effect = parent->getStretchEffect();
1228 if (effect.hasEffect()) {
1229 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1230 return effect;
1231 }
1232 }
1233 return StretchEffect{};
1234}
1235
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001236bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1237 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001238 return false;
1239 }
1240 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001241 mBorderWidth = width;
1242 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001243 return true;
1244}
1245
1246bool Layer::isBorderEnabled() {
1247 return mBorderEnabled;
1248}
1249
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001250float Layer::getBorderWidth() {
1251 return mBorderWidth;
1252}
1253
1254const half4& Layer::getBorderColor() {
1255 return mBorderColor;
1256}
1257
Rachel Lee0faad6c2023-09-08 13:34:34 -07001258bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool overrideChildren,
1259 bool* transactionNeeded) {
1260 // Gets the frame rate to propagate to children.
Ady Abrahama850c182021-08-04 13:04:37 -07001261 const auto frameRate = [&] {
Rachel Lee0faad6c2023-09-08 13:34:34 -07001262 if (overrideChildren && parentFrameRate.isValid()) {
1263 return parentFrameRate;
1264 }
1265
Rachel Leece6e0042023-06-27 11:22:54 -07001266 if (mDrawingState.frameRate.isValid()) {
Ady Abrahama850c182021-08-04 13:04:37 -07001267 return mDrawingState.frameRate;
1268 }
1269
1270 return parentFrameRate;
1271 }();
1272
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001273 auto now = systemTime();
1274 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate, now);
Ady Abrahama850c182021-08-04 13:04:37 -07001275
Rachel Leea021bb02023-11-20 21:51:09 -08001276 // The frame rate is propagated to the children by default, but some properties may override it.
Ady Abrahama850c182021-08-04 13:04:37 -07001277 bool childrenHaveFrameRate = false;
Rachel Leea021bb02023-11-20 21:51:09 -08001278 const bool overrideChildrenFrameRate = overrideChildren || shouldOverrideChildrenFrameRate();
1279 const bool canPropagateFrameRate = shouldPropagateFrameRate() || overrideChildrenFrameRate;
Ady Abrahama850c182021-08-04 13:04:37 -07001280 for (const sp<Layer>& child : mCurrentChildren) {
1281 childrenHaveFrameRate |=
Rachel Leea021bb02023-11-20 21:51:09 -08001282 child->propagateFrameRateForLayerTree(canPropagateFrameRate ? frameRate
1283 : FrameRate(),
1284 overrideChildrenFrameRate, transactionNeeded);
Ady Abrahama850c182021-08-04 13:04:37 -07001285 }
1286
Rachel Leece6e0042023-06-27 11:22:54 -07001287 // If we don't have a valid frame rate specification, but the children do, we set this
Ady Abrahama850c182021-08-04 13:04:37 -07001288 // layer as NoVote to allow the children to control the refresh rate
Rachel Leece6e0042023-06-27 11:22:54 -07001289 if (!frameRate.isValid() && childrenHaveFrameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001290 *transactionNeeded |=
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001291 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote),
1292 now);
Ady Abrahama850c182021-08-04 13:04:37 -07001293 }
1294
Rachel Leece6e0042023-06-27 11:22:54 -07001295 // We return whether this layer or its children has a vote. We ignore ExactOrMultiple votes for
Ady Abrahama850c182021-08-04 13:04:37 -07001296 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001297 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001298 const auto layerVotedWithDefaultCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001299 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Default;
1300 const auto layerVotedWithNoVote = frameRate.vote.type == FrameRateCompatibility::NoVote;
1301 const auto layerVotedWithCategory = frameRate.category != FrameRateCategory::Default;
Ady Abrahama850c182021-08-04 13:04:37 -07001302 const auto layerVotedWithExactCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001303 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Exact;
1304 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote || layerVotedWithCategory ||
Ady Abrahama850c182021-08-04 13:04:37 -07001305 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1306}
1307
Ady Abraham60e42ea2020-03-09 19:17:31 -07001308void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001309 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001310 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001311 while (auto parent = layer->getParent()) {
1312 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001313 }
Ady Abrahama850c182021-08-04 13:04:37 -07001314 return layer;
1315 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001316
Ady Abraham60e42ea2020-03-09 19:17:31 -07001317 bool transactionNeeded = false;
Rachel Lee0faad6c2023-09-08 13:34:34 -07001318 root->propagateFrameRateForLayerTree({}, false, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001319
Ady Abrahama850c182021-08-04 13:04:37 -07001320 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001321 if (transactionNeeded) {
1322 mFlinger->setTransactionFlags(eTraversalNeeded);
1323 }
1324}
1325
Rachel Leece6e0042023-06-27 11:22:54 -07001326bool Layer::setFrameRate(FrameRate::FrameRateVote frameRateVote) {
1327 if (mDrawingState.frameRate.vote == frameRateVote) {
Steven Thomas3172e202020-01-06 19:25:30 -08001328 return false;
1329 }
1330
Robert Carr6a160312021-05-17 12:08:20 -07001331 mDrawingState.sequence++;
Rachel Leece6e0042023-06-27 11:22:54 -07001332 mDrawingState.frameRate.vote = frameRateVote;
1333 mDrawingState.modified = true;
1334
1335 updateTreeHasFrameRateVote();
1336
1337 setTransactionFlags(eTransactionNeeded);
1338 return true;
1339}
1340
Rachel Lee67afbea2023-09-28 15:35:07 -07001341bool Layer::setFrameRateCategory(FrameRateCategory category, bool smoothSwitchOnly) {
1342 if (mDrawingState.frameRate.category == category &&
1343 mDrawingState.frameRate.categorySmoothSwitchOnly == smoothSwitchOnly) {
Rachel Leece6e0042023-06-27 11:22:54 -07001344 return false;
1345 }
1346
1347 mDrawingState.sequence++;
1348 mDrawingState.frameRate.category = category;
Rachel Lee67afbea2023-09-28 15:35:07 -07001349 mDrawingState.frameRate.categorySmoothSwitchOnly = smoothSwitchOnly;
Robert Carr6a160312021-05-17 12:08:20 -07001350 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001351
1352 updateTreeHasFrameRateVote();
1353
Steven Thomas3172e202020-01-06 19:25:30 -08001354 setTransactionFlags(eTransactionNeeded);
1355 return true;
1356}
1357
Rachel Lee58cc90d2023-09-05 18:50:20 -07001358bool Layer::setFrameRateSelectionStrategy(FrameRateSelectionStrategy strategy) {
1359 if (mDrawingState.frameRateSelectionStrategy == strategy) return false;
1360 mDrawingState.frameRateSelectionStrategy = strategy;
1361 mDrawingState.sequence++;
1362 mDrawingState.modified = true;
Rachel Leed7479502023-09-25 17:02:35 -07001363
1364 updateTreeHasFrameRateVote();
Rachel Lee58cc90d2023-09-05 18:50:20 -07001365 setTransactionFlags(eTransactionNeeded);
1366 return true;
1367}
1368
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001369void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1370 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001371 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001372
1373 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1374 // there are two transactions with the same token, the first one without a buffer and the
1375 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1376 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001377 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1378 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001379 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001380 mDrawingState.bufferSurfaceFrameTX = it->second;
1381 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1382 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1383 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001384 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001385 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001386 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1387 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001388
1389 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001390}
1391
1392void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1393 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001394 mDrawingState.frameTimelineInfo = info;
1395 mDrawingState.postTime = postTime;
1396 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001397 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001398
Robert Carr6a160312021-05-17 12:08:20 -07001399 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001400 bufferSurfaceFrameTX != nullptr) {
1401 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1402 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1403 // being used for BufferSurfaceFrame, don't create a new one.
1404 return;
1405 }
1406 }
1407 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1408 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1409 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001410 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1411 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001412 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001413 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001414 } else {
1415 if (it->second->getPresentState() == PresentState::Presented) {
1416 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1417 // have been from previous vsync.
1418 it->second = createSurfaceFrameForTransaction(info, postTime);
1419 }
1420 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001421
1422 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001423}
1424
1425void Layer::addSurfaceFrameDroppedForBuffer(
Ady Abraham5a3e3562023-06-07 10:32:08 -07001426 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t dropTime) {
1427 surfaceFrame->setDropTime(dropTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001428 surfaceFrame->setPresentState(PresentState::Dropped);
1429 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1430}
1431
1432void Layer::addSurfaceFramePresentedForBuffer(
1433 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1434 nsecs_t currentLatchTime) {
1435 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1436 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1437 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001438 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001439}
1440
1441std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1442 const FrameTimelineInfo& info, nsecs_t postTime) {
1443 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001444 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1445 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001446 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001447 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001448 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001449 // For Transactions, the post time is considered to be both queue and acquire fence time.
1450 surfaceFrame->setActualQueueTime(postTime);
1451 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001452 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1453 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001454 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001455 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001456 onSurfaceFrameCreated(surfaceFrame);
1457 return surfaceFrame;
1458}
1459
1460std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1461 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1462 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001463 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001464 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001465 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001466 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001467 // For buffers, acquire fence time will set during latch.
1468 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001469 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1470 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001471 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001472 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001473 onSurfaceFrameCreated(surfaceFrame);
1474 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001475}
1476
Ady Abraham5a3e3562023-06-07 10:32:08 -07001477void Layer::setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
1478 std::string debugName) {
1479 if (info.skippedFrameVsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
1480 return;
1481 }
1482
1483 FrameTimelineInfo skippedFrameTimelineInfo = info;
1484 skippedFrameTimelineInfo.vsyncId = info.skippedFrameVsyncId;
1485
1486 auto surfaceFrame =
1487 mFlinger->mFrameTimeline->createSurfaceFrameForToken(skippedFrameTimelineInfo,
1488 mOwnerPid, mOwnerUid,
1489 getSequence(), mName, debugName,
1490 /*isBuffer*/ false, getGameMode());
1491 surfaceFrame->setActualStartTime(skippedFrameTimelineInfo.skippedFrameStartTimeNanos);
1492 // For Transactions, the post time is considered to be both queue and acquire fence time.
1493 surfaceFrame->setActualQueueTime(postTime);
1494 surfaceFrame->setAcquireFenceTime(postTime);
1495 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1496 if (fps) {
1497 surfaceFrame->setRenderRate(*fps);
1498 }
1499 onSurfaceFrameCreated(surfaceFrame);
1500 addSurfaceFrameDroppedForBuffer(surfaceFrame, postTime);
1501}
1502
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001503bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate, nsecs_t now) {
Ady Abrahama850c182021-08-04 13:04:37 -07001504 if (mDrawingState.frameRateForLayerTree == frameRate) {
1505 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001506 }
1507
Ady Abrahama850c182021-08-04 13:04:37 -07001508 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001509
Ady Abrahama850c182021-08-04 13:04:37 -07001510 // TODO(b/195668952): we probably don't need to dirty visible regions here
1511 // or even store frameRateForLayerTree in mDrawingState
1512 mDrawingState.sequence++;
1513 mDrawingState.modified = true;
1514 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001515
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001516 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001517 ->recordLayerHistory(sequence, getLayerProps(), now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001518 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1519 return true;
1520}
Ady Abrahama850c182021-08-04 13:04:37 -07001521
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001522bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps,
1523 nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001524 if (mDrawingState.frameRateForLayerTree == frameRate) {
1525 return false;
1526 }
1527
1528 mDrawingState.frameRateForLayerTree = frameRate;
1529 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001530 ->recordLayerHistory(sequence, layerProps, now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001531 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001532 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001533}
1534
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001535Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1536 return getDrawingState().frameRateForLayerTree;
1537}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001538
Robert Carr1f0a16a2016-10-24 16:27:39 -07001539bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001540 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001541 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001542 if (parent != nullptr && parent->isHiddenByPolicy()) {
1543 return true;
1544 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001545 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1546 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1547 if (zOrderRelativeOf != nullptr) {
1548 if (zOrderRelativeOf->isHiddenByPolicy()) {
1549 return true;
1550 }
1551 }
1552 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001553 if (CC_UNLIKELY(!isTransformValid())) {
1554 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1555 return true;
1556 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001557 return s.flags & layer_state_t::eLayerHidden;
1558}
1559
David Sodman41fdfc92017-11-06 16:09:56 -08001560uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001561 // TODO: should we do something special if mSecure is set?
1562 if (mProtectedByApp) {
1563 // need a hardware-protected path to external video sink
1564 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001565 }
Riley Andrews03414a12014-07-01 14:22:59 -07001566 if (mPotentialCursor) {
1567 usage |= GraphicBuffer::USAGE_CURSOR;
1568 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001569 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001570 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001571}
1572
Vishnu Nair71fcf912022-10-18 09:14:20 -07001573void Layer::skipReportingTransformHint() {
1574 mSkipReportingTransformHint = true;
1575}
1576
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001577void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1578 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1579 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001580 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001581
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001582 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001583}
1584
Mathias Agopian13127d82013-03-05 17:47:11 -08001585// ----------------------------------------------------------------------------
1586// debugging
1587// ----------------------------------------------------------------------------
1588
Marissa Wall61c58622018-07-18 10:12:20 -07001589// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001590gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001591 using namespace std::string_literals;
1592
Huihong Luo05539a12022-02-23 10:29:40 -08001593 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001594 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001595 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001596 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001597 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001598 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001599
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001600 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001601 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001602 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001603 info.mX = ds.transform.tx();
1604 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001605 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001606 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001607 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001608 info.mFlags = ds.flags;
1609 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001610 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001611 info.mMatrix[0][0] = ds.transform[0][0];
1612 info.mMatrix[0][1] = ds.transform[0][1];
1613 info.mMatrix[1][0] = ds.transform[1][0];
1614 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001615 {
chaviwd62d3062019-09-04 14:48:02 -07001616 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001617 if (buffer != 0) {
1618 info.mActiveBufferWidth = buffer->getWidth();
1619 info.mActiveBufferHeight = buffer->getHeight();
1620 info.mActiveBufferStride = buffer->getStride();
1621 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001622 } else {
1623 info.mActiveBufferWidth = 0;
1624 info.mActiveBufferHeight = 0;
1625 info.mActiveBufferStride = 0;
1626 info.mActiveBufferFormat = 0;
1627 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001628 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001629 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001630 info.mIsOpaque = isOpaque(ds);
1631 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001632 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001633 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001634}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001635
Yiwei Zhang5434a782018-12-05 18:06:32 -08001636void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001637 result.append(kDumpTableRowLength, '-');
1638 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001639 result.append(" Layer name\n");
1640 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001641 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001642 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001643 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001644 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001645 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001646 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1647 result.append(kDumpTableRowLength, '-');
1648 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001649}
1650
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001651void Layer::miniDumpLegacy(std::string& result, const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001652 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001653 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001654 return;
1655 }
1656
Yiwei Zhang5434a782018-12-05 18:06:32 -08001657 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001658 if (mName.length() > 77) {
1659 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001660 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001661 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001662 shortened.append(mName, mName.length() - 36);
1663 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001664 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001665 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001666 }
1667
Yiwei Zhang5434a782018-12-05 18:06:32 -08001668 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001669
Alec Mourib416efd2018-09-06 21:01:59 +00001670 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001671 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001672
Chia-I Wu1e043612018-03-01 09:45:09 -08001673 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001674 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001675 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001676 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001677 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001678 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001679 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001680 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1681 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001682 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001683 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001684 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001685 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001686 const auto frameRate = getFrameRateForLayerTree();
Rachel Leece6e0042023-06-27 11:22:54 -07001687 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
1688 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.vote.rate).c_str(),
1689 ftl::enum_string(frameRate.vote.type).c_str(),
1690 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001691 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001692 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001693 }
Dan Stozae22aec72016-08-01 13:20:59 -07001694
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001695 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1696 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1697
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001698 result.append(kDumpTableRowLength, '-');
1699 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001700}
Dan Stozae22aec72016-08-01 13:20:59 -07001701
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001702void Layer::miniDump(std::string& result, const frontend::LayerSnapshot& snapshot,
1703 const DisplayDevice& display) const {
1704 const auto outputLayer = findOutputLayerForDisplay(&display, snapshot.path);
1705 if (!outputLayer) {
1706 return;
1707 }
1708
1709 StringAppendF(&result, " %s\n", snapshot.debugName.c_str());
1710 StringAppendF(&result, " %10zu | ", snapshot.globalZ);
1711 StringAppendF(&result, " %10d | ",
1712 snapshot.layerMetadata.getInt32(gui::METADATA_WINDOW_TYPE, 0));
1713 StringAppendF(&result, "%10s | ", toString(getCompositionType(outputLayer)).c_str());
1714 const auto& outputLayerState = outputLayer->getState();
1715 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1716 const Rect& frame = outputLayerState.displayFrame;
1717 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1718 const FloatRect& crop = outputLayerState.sourceCrop;
1719 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
1720 crop.bottom);
1721 const auto frameRate = snapshot.frameRate;
Ady Abraham77d406d2023-11-22 15:00:23 -08001722 std::string frameRateStr;
1723 if (frameRate.vote.rate.isValid()) {
1724 StringAppendF(&frameRateStr, "%.2f", frameRate.vote.rate.getValue());
1725 }
Rachel Leece6e0042023-06-27 11:22:54 -07001726 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
Ady Abraham77d406d2023-11-22 15:00:23 -08001727 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
Rachel Leece6e0042023-06-27 11:22:54 -07001728 ftl::enum_string(frameRate.vote.type).c_str(),
1729 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abraham77d406d2023-11-22 15:00:23 -08001730 } else if (frameRate.category != FrameRateCategory::Default) {
1731 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
1732 (std::string("Cat::") + ftl::enum_string(frameRate.category)).c_str(),
1733 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001734 } else {
1735 result.append(41, ' ');
1736 }
1737
1738 const auto focused = isLayerFocusedBasedOnPriority(snapshot.frameRateSelectionPriority);
1739 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1740
1741 result.append(kDumpTableRowLength, '-');
1742 result.append("\n");
1743}
1744
Yiwei Zhang5434a782018-12-05 18:06:32 -08001745void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001746 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001747}
1748
Svetoslavd85084b2014-03-20 10:28:31 -07001749void Layer::clearFrameStats() {
1750 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001751}
1752
Jamie Gennis6547ff42013-07-16 20:12:42 -07001753void Layer::logFrameStats() {
1754 mFrameTracker.logAndResetStats(mName);
1755}
1756
Svetoslavd85084b2014-03-20 10:28:31 -07001757void Layer::getFrameStats(FrameStats* outStats) const {
1758 mFrameTracker.getStats(outStats);
1759}
1760
Vishnu Nair76554eb2022-12-09 03:38:36 +00001761void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1762 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
Vishnu Nair3be61902023-04-26 19:47:29 -07001763 StringAppendF(&result, "Layer %s%s pid:%d uid:%d%s\n", getName().c_str(), hasBuffer.c_str(),
1764 mOwnerPid, mOwnerUid, isHandleAlive() ? " handleAlive" : "");
Vishnu Nair0f085c62019-08-30 08:49:12 -07001765}
1766
Brian Anderson5ea5e592016-12-01 16:54:33 -08001767void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001768 const int32_t layerId = getSequence();
1769 mFlinger->mTimeStats->onDestroy(layerId);
1770 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001771}
1772
Vishnu Nair787aa782023-03-17 13:46:46 -07001773size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001774 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001775 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001776 count += 1 + child->getChildrenCount();
1777 }
1778 return count;
1779}
1780
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001781void Layer::setGameModeForTree(GameMode gameMode) {
1782 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001783 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1784 gameMode =
1785 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001786 }
1787 setGameMode(gameMode);
1788 for (const sp<Layer>& child : mCurrentChildren) {
1789 child->setGameModeForTree(gameMode);
1790 }
1791}
1792
Robert Carr1f0a16a2016-10-24 16:27:39 -07001793void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001794 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001795 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001796
Robert Carr1f0a16a2016-10-24 16:27:39 -07001797 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001798 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001799 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001800 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001801}
1802
1803ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001804 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001805 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001806
Robert Carr1323c952019-01-28 18:13:27 -08001807 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001808 const auto removeResult = mCurrentChildren.remove(layer);
1809
1810 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001811 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001812 layer->updateTreeHasFrameRateVote();
1813
1814 return removeResult;
1815}
1816
Robert Carr15eae092018-03-23 13:43:53 -07001817void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001818 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001819 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001820 const float parentShadowRadius =
1821 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001822 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001823 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001824 }
1825}
1826
chaviwf1961f72017-09-18 16:41:07 -07001827bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001828 sp<Layer> newParent;
1829 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001830 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001831 if (newParent == nullptr) {
1832 ALOGE("Unable to promote Layer handle");
1833 return false;
1834 }
1835 if (newParent == this) {
1836 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1837 return false;
1838 }
1839 }
1840
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001841 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001842 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001843 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001844 }
1845
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001846 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001847 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001848 if (!newParent->isRemovedFromCurrentState()) {
1849 addToCurrentState();
1850 } else {
1851 onRemovedFromCurrentState();
1852 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001853 } else {
1854 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001855 }
1856
chaviw06178942017-07-27 10:25:59 -07001857 return true;
1858}
1859
Peiyong Lind3788632018-09-18 16:01:31 -07001860bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001861 static const mat4 identityMatrix = mat4();
1862
Robert Carr6a160312021-05-17 12:08:20 -07001863 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001864 return false;
1865 }
Robert Carr6a160312021-05-17 12:08:20 -07001866 ++mDrawingState.sequence;
1867 mDrawingState.colorTransform = matrix;
1868 mDrawingState.hasColorTransform = matrix != identityMatrix;
1869 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001870 setTransactionFlags(eTransactionNeeded);
1871 return true;
1872}
1873
chaviwf66724d2018-11-28 16:35:21 -08001874mat4 Layer::getColorTransform() const {
1875 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001876 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001877 colorTransform = parent->getColorTransform() * colorTransform;
1878 }
1879 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001880}
1881
1882bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001883 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001884 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001885 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1886 }
1887 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001888}
1889
Chia-I Wu11481472018-05-04 10:43:19 -07001890bool Layer::isLegacyDataSpace() const {
1891 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001892 return !(getDataSpace() &
1893 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1894 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001895}
1896
Robert Carr1f0a16a2016-10-24 16:27:39 -07001897void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001898 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001899}
1900
Robert Carr6a160312021-05-17 12:08:20 -07001901int32_t Layer::getZ(LayerVector::StateSet) const {
1902 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001903}
1904
Robert Carr1c5481e2019-07-01 14:42:27 -07001905bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001906 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001907 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001908 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001909}
1910
David Sodman41fdfc92017-11-06 16:09:56 -08001911__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001912 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001913 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1914 "makeTraversalList received invalid stateSet");
1915 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1916 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001917 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001918
Robert Carr29abff82017-12-04 13:51:20 -08001919 if (state.zOrderRelatives.size() == 0) {
1920 *outSkipRelativeZUsers = true;
1921 return children;
1922 }
1923
chaviwfd462612018-05-31 16:11:27 -07001924 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001925 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001926 sp<Layer> strongRelative = weakRelative.promote();
1927 if (strongRelative != nullptr) {
1928 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001929 }
1930 }
1931
Dan Stoza412903f2017-04-27 13:42:17 -07001932 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001933 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001934 continue;
1935 }
Robert Carrdb66e622017-04-10 16:55:57 -07001936 traverse.add(child);
1937 }
1938
1939 return traverse;
1940}
1941
Robert Carr1f0a16a2016-10-24 16:27:39 -07001942/**
Robert Carrdb66e622017-04-10 16:55:57 -07001943 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001944 */
Dan Stoza412903f2017-04-27 13:42:17 -07001945void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001946 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1947 // produce a new list for traversing, including our relatives, and not including our children
1948 // who are relatives of another surface. In the case that there are no relative Z,
1949 // makeTraversalList returns our children directly to avoid significant overhead.
1950 // However in this case we need to take the responsibility for filtering children which
1951 // are relatives of another surface here.
1952 bool skipRelativeZUsers = false;
1953 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001954
Robert Carr1f0a16a2016-10-24 16:27:39 -07001955 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001956 for (; i < list.size(); i++) {
1957 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001958 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1959 continue;
1960 }
1961
chaviw301b1d82019-11-06 13:15:09 -08001962 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001963 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001964 }
Dan Stoza412903f2017-04-27 13:42:17 -07001965 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001966 }
Robert Carr29abff82017-12-04 13:51:20 -08001967
Dan Stoza412903f2017-04-27 13:42:17 -07001968 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001969 for (; i < list.size(); i++) {
1970 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001971
Robert Carr29abff82017-12-04 13:51:20 -08001972 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1973 continue;
1974 }
Dan Stoza412903f2017-04-27 13:42:17 -07001975 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001976 }
1977}
1978
1979/**
Robert Carrdb66e622017-04-10 16:55:57 -07001980 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001981 */
Dan Stoza412903f2017-04-27 13:42:17 -07001982void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1983 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001984 // See traverseInZOrder for documentation.
1985 bool skipRelativeZUsers = false;
1986 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001987
Robert Carr1f0a16a2016-10-24 16:27:39 -07001988 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001989 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001990 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001991
1992 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1993 continue;
1994 }
1995
chaviw301b1d82019-11-06 13:15:09 -08001996 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001997 break;
1998 }
Dan Stoza412903f2017-04-27 13:42:17 -07001999 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002000 }
Dan Stoza412903f2017-04-27 13:42:17 -07002001 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08002002 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002003 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08002004
2005 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
2006 continue;
2007 }
2008
Dan Stoza412903f2017-04-27 13:42:17 -07002009 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002010 }
2011}
2012
Edgar Arriaga844fa672020-01-16 14:21:42 -08002013void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
2014 visitor(this);
2015 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07002016 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002017 for (const sp<Layer>& child : children) {
2018 child->traverse(state, visitor);
2019 }
2020}
2021
Vishnu Nair787aa782023-03-17 13:46:46 -07002022void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
2023 for (const sp<Layer>& child : mDrawingChildren) {
2024 visitor(child.get());
2025 }
2026}
2027
chaviw4b129c22018-04-09 16:19:43 -07002028LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
2029 const std::vector<Layer*>& layersInTree) {
2030 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2031 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07002032 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2033 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002034 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002035
chaviwfd462612018-05-31 16:11:27 -07002036 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07002037 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2038 sp<Layer> strongRelative = weakRelative.promote();
2039 // Only add relative layers that are also descendents of the top most parent of the tree.
2040 // If a relative layer is not a descendent, then it should be ignored.
2041 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
2042 traverse.add(strongRelative);
2043 }
2044 }
2045
2046 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07002047 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002048 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
2049 // descendent of the top most parent of the tree. If it's not a descendent, then just add
2050 // the child here since it won't be added later as a relative.
2051 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
2052 childState.zOrderRelativeOf.promote().get())) {
2053 continue;
2054 }
2055 traverse.add(child);
2056 }
2057
2058 return traverse;
2059}
2060
2061void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
2062 LayerVector::StateSet stateSet,
2063 const LayerVector::Visitor& visitor) {
2064 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07002065
2066 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07002067 for (; i < list.size(); i++) {
2068 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08002069 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07002070 break;
2071 }
chaviw4b129c22018-04-09 16:19:43 -07002072 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002073 }
chaviw4b129c22018-04-09 16:19:43 -07002074
chaviwa76b2712017-09-20 12:02:26 -07002075 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07002076 for (; i < list.size(); i++) {
2077 const auto& relative = list[i];
2078 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002079 }
2080}
2081
chaviw4b129c22018-04-09 16:19:43 -07002082std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2083 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2084 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2085
2086 std::vector<Layer*> layersInTree = {this};
2087 for (size_t i = 0; i < children.size(); i++) {
2088 const auto& child = children[i];
2089 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2090 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2091 }
2092
2093 return layersInTree;
2094}
2095
2096void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2097 const LayerVector::Visitor& visitor) {
2098 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2099 std::sort(layersInTree.begin(), layersInTree.end());
2100 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2101}
2102
Peiyong Linefefaac2018-08-17 12:27:51 -07002103ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08002104 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002105}
2106
Garfield Tan2c1782c2022-02-16 15:25:05 -08002107bool Layer::isTransformValid() const {
2108 float transformDet = getTransform().det();
2109 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2110}
2111
chaviw13fdc492017-06-27 12:40:18 -07002112half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002113 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002114
chaviw13fdc492017-06-27 12:40:18 -07002115 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2116 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002117}
Robert Carr6452f122017-03-21 10:41:29 -07002118
Vishnu Nair6213bd92020-05-08 17:42:25 -07002119ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002120 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002121 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2122 return fixedTransformHint;
2123 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002124 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002125 if (!p) return fixedTransformHint;
2126 return p->getFixedTransformHint();
2127}
2128
chaviw13fdc492017-06-27 12:40:18 -07002129half4 Layer::getColor() const {
2130 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002131 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002132}
Robert Carr6452f122017-03-21 10:41:29 -07002133
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002134int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002135 if (getDrawingState().backgroundBlurRadius == 0) {
2136 return 0;
2137 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002138
Vishnu Nair29810f72022-07-01 16:38:41 +00002139 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002140 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2141 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002142}
2143
Galia Peychevae0acf382021-04-12 21:22:34 +02002144const std::vector<BlurRegion> Layer::getBlurRegions() const {
2145 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002146 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002147 for (auto& region : regionsCopy) {
2148 region.alpha = region.alpha * layerAlpha;
2149 }
2150 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002151}
2152
Vishnu Naire14c6b32022-08-06 04:20:15 +00002153RoundedCornerState Layer::getRoundedCornerState() const {
Leon Scroggins IIIc1dbfcb2022-03-21 16:48:10 -04002154 // Today's DPUs cannot do rounded corners. If RenderEngine cannot render
2155 // protected content, remove rounded corners from protected content so it
2156 // can be rendered by the DPU.
2157 if (isProtected() && !mFlinger->getRenderEngine().supportsProtectedContent()) {
2158 return {};
2159 }
2160
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002161 // Get parent settings
2162 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002163 const auto& parent = mDrawingParent.promote();
2164 if (parent != nullptr) {
2165 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002166 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002167 ui::Transform t = getActiveTransform(getDrawingState());
2168 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002169 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002170 parentSettings.radius.x *= t.getScaleX();
2171 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002172 }
2173 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002174
2175 // Get layer settings
2176 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002177 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002178 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002179 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002180
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002181 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002182 // If the parent and the layer have rounded corner settings, use the parent settings if the
2183 // parent crop is entirely inside the layer crop.
2184 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2185 if (parentSettings.cropRect.left > layerCropRect.left &&
2186 parentSettings.cropRect.top > layerCropRect.top &&
2187 parentSettings.cropRect.right < layerCropRect.right &&
2188 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2189 return parentSettings;
2190 } else {
2191 return layerSettings;
2192 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002193 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002194 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002195 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002196 return parentSettings;
2197 }
2198 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002199}
2200
Robert Carr88b85e12022-03-21 15:47:35 -07002201bool Layer::findInHierarchy(const sp<Layer>& l) {
2202 if (l == this) {
2203 return true;
2204 }
2205 for (auto& child : mDrawingChildren) {
2206 if (child->findInHierarchy(l)) {
2207 return true;
2208 }
2209 }
2210 return false;
2211}
2212
Robert Carr1f0a16a2016-10-24 16:27:39 -07002213void Layer::commitChildList() {
2214 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2215 const auto& child = mCurrentChildren[i];
2216 child->commitChildList();
2217 }
2218 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002219 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002220 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2221 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2222 if (zOrderRelativeOf == nullptr) return;
2223 if (findInHierarchy(zOrderRelativeOf)) {
2224 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2225 zOrderRelativeOf->mName.c_str());
2226 ALOGE("Severing rel Z loop, potentially dangerous");
2227 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002228 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002229 }
2230 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002231}
2232
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002233
chaviw3277faf2021-05-19 16:45:23 -05002234void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002235 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002236 mDrawingState.touchableRegionCrop =
2237 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002238 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002239 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002240 setTransactionFlags(eTransactionNeeded);
2241}
2242
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002243perfetto::protos::LayerProto* Layer::writeToProto(perfetto::protos::LayersProto& layersProto,
2244 uint32_t traceFlags) {
2245 perfetto::protos::LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002246 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002247 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2248
Vishnu Nair00b90132021-11-05 14:03:40 -07002249 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nair2f65e972023-04-04 16:36:28 +00002250 ui::LayerStack layerStack =
2251 (mSnapshot) ? mSnapshot->outputFilter.layerStack : ui::INVALID_LAYER_STACK;
2252 writeCompositionStateToProto(layerProto, layerStack);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002253 }
2254
chaviw08f3cb22020-01-13 13:17:21 -08002255 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002256 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002257 }
chaviw6d89e2d2020-01-14 14:42:01 -08002258
2259 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002260}
2261
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002262void Layer::writeCompositionStateToProto(perfetto::protos::LayerProto* layerProto,
2263 ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002264 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002265 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +00002266
2267 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002268 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002269 const auto compositionType = getCompositionType(*display);
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002270 layerProto->set_hwc_composition_type(
2271 static_cast<perfetto::protos::HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +00002272 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +00002273 [&]() { return layerProto->mutable_visible_region(); });
2274 }
2275}
2276
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002277void Layer::writeToProtoDrawingState(perfetto::protos::LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002278 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002279 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002280 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002281 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002282 [&]() { return layerInfo->mutable_active_buffer(); });
2283 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2284 layerInfo->mutable_buffer_transform());
2285 }
2286 layerInfo->set_invalidate(contentDirty);
2287 layerInfo->set_is_protected(isProtected());
2288 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2289 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002290 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002291 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002292 layerInfo->set_corner_radius(
2293 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002294 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2295 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2296 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2297 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2298 [&]() { return layerInfo->mutable_position(); });
2299 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002300 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2301 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002302
Vishnu Nair00b90132021-11-05 14:03:40 -07002303 if (hasColorTransform()) {
2304 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002305 }
2306
Vishnu Nair60db8c02020-04-02 11:55:16 -07002307 LayerProtoHelper::writeToProto(mSourceBounds,
2308 [&]() { return layerInfo->mutable_source_bounds(); });
2309 LayerProtoHelper::writeToProto(mScreenBounds,
2310 [&]() { return layerInfo->mutable_screen_bounds(); });
2311 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2312 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2313 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002314}
2315
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002316void Layer::writeToProtoCommonState(perfetto::protos::LayerProto* layerInfo,
2317 LayerVector::StateSet stateSet, uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002318 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2319 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002320 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002321
chaviw766c9c52021-02-10 17:36:47 -08002322 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002323
Vishnu Nair00b90132021-11-05 14:03:40 -07002324 layerInfo->set_id(sequence);
2325 layerInfo->set_name(getName().c_str());
2326 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002327
Vishnu Nair00b90132021-11-05 14:03:40 -07002328 for (const auto& child : children) {
2329 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002330 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002331
Vishnu Nair00b90132021-11-05 14:03:40 -07002332 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2333 sp<Layer> strongRelative = weakRelative.promote();
2334 if (strongRelative != nullptr) {
2335 layerInfo->add_relatives(strongRelative->sequence);
2336 }
2337 }
2338
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002339 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002340 [&]() { return layerInfo->mutable_transparent_region(); });
2341
2342 layerInfo->set_layer_stack(getLayerStack().id);
2343 layerInfo->set_z(state.z);
2344
2345 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2346 return layerInfo->mutable_requested_position();
2347 });
2348
Vishnu Nair00b90132021-11-05 14:03:40 -07002349 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2350
2351 layerInfo->set_is_opaque(isOpaque(state));
2352
2353 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2354 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2355 LayerProtoHelper::writeToProto(state.color,
2356 [&]() { return layerInfo->mutable_requested_color(); });
2357 layerInfo->set_flags(state.flags);
2358
2359 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2360 layerInfo->mutable_requested_transform());
2361
2362 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2363 if (parent != nullptr) {
2364 layerInfo->set_parent(parent->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002365 }
2366
2367 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2368 if (zOrderRelativeOf != nullptr) {
2369 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002370 }
2371
2372 layerInfo->set_is_relative_of(state.isRelativeOf);
2373
2374 layerInfo->set_owner_uid(mOwnerUid);
2375
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002376 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002377 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002378 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002379 info = fillInputInfo(
2380 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002381 } else {
2382 info = state.inputInfo;
2383 }
2384
2385 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002386 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002387 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002388
Vishnu Nair00b90132021-11-05 14:03:40 -07002389 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002390 auto protoMap = layerInfo->mutable_metadata();
2391 for (const auto& entry : state.metadata.mMap) {
2392 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2393 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002394 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002395
2396 LayerProtoHelper::writeToProto(state.destinationFrame,
2397 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002398}
2399
Robert Carr2e102c92018-10-23 12:11:15 -07002400bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002401 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002402}
2403
Prabir Pradhan33da9462022-06-14 14:55:57 +00002404// Applies the given transform to the region, while protecting against overflows caused by any
2405// offsets. If applying the offset in the transform to any of the Rects in the region would result
2406// in an overflow, they are not added to the output Region.
2407static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2408 const std::string& debugWindowName) {
2409 // Round the translation using the same rounding strategy used by ui::Transform.
2410 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2411 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2412
2413 ui::Transform transformWithoutOffset = t;
2414 transformWithoutOffset.set(0.f, 0.f);
2415
2416 const Region transformed = transformWithoutOffset.transform(r);
2417
2418 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2419 Region ret;
2420 for (const auto& rect : transformed) {
2421 Rect newRect;
2422 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2423 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2424 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2425 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2426 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2427 debugWindowName.c_str());
2428 continue;
2429 }
2430 ret.orSelf(newRect);
2431 }
2432 return ret;
2433}
2434
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002435void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002436 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2437 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002438 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002439 }
2440
Chavi Weingarten7f019192023-08-08 20:39:01 +00002441 info.frame = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
chaviw1ff3d1e2020-07-01 15:53:47 -07002442
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002443 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002444 inputToLayer.set(inputBounds.left, inputBounds.top);
2445 const ui::Transform layerToScreen = getInputTransform();
2446 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002447
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002448 // InputDispatcher expects a display-to-input transform.
2449 info.transform = inputToDisplay.inverse();
2450
2451 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002452 info.touchableRegion =
2453 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002454}
2455
chaviw3277faf2021-05-19 16:45:23 -05002456void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002457 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002458 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002459 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002460 }
2461 if (p != nullptr) {
2462 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2463 }
2464}
2465
Vishnu Naira066d902021-09-13 18:40:17 -07002466gui::DropInputMode Layer::getDropInputMode() const {
2467 gui::DropInputMode mode = mDrawingState.dropInputMode;
2468 if (mode == gui::DropInputMode::ALL) {
2469 return mode;
2470 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002471 sp<Layer> parent = mDrawingParent.promote();
2472 if (parent) {
2473 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002474 if (parentMode != gui::DropInputMode::NONE) {
2475 return parentMode;
2476 }
2477 }
2478 return mode;
2479}
2480
2481void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002482 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002483 return;
2484 }
2485
2486 // Check if we need to drop input unconditionally
2487 gui::DropInputMode dropInputMode = getDropInputMode();
2488 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002489 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002490 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2491 return;
2492 }
2493
2494 // Check if we need to check if the window is obscured by parent
2495 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2496 return;
2497 }
2498
2499 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002500 sp<Layer> parent = mDrawingParent.promote();
2501 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002502 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002503 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2504 static_cast<float>(getAlpha()));
2505 }
2506
2507 // Check if the parent has cropped the buffer
2508 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2509 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002510 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002511 return;
2512 }
2513
2514 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2515 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2516 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2517 // match then the layer has not been cropped by its parents.
2518 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2519 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2520
2521 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002522 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002523 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2524 getDebugName());
2525 } else {
2526 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2527 // input if the window is obscured. This check should be done in surfaceflinger but the
2528 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2529 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002530 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002531 }
2532}
2533
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002534WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002535 if (!hasInputInfo()) {
2536 mDrawingState.inputInfo.name = getName();
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002537 mDrawingState.inputInfo.ownerUid = gui::Uid{mOwnerUid};
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00002538 mDrawingState.inputInfo.ownerPid = gui::Pid{mOwnerPid};
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002539 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002540 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002541 }
2542
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002543 const ui::Transform& displayTransform =
2544 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2545
chaviw3277faf2021-05-19 16:45:23 -05002546 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002547 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002548 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002549
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002550 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002551
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002552 if (displayArgs.transform == nullptr) {
2553 // Do not let the window receive touches if it is not associated with a valid display
2554 // transform. We still allow the window to receive keys and prevent ANRs.
2555 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2556 }
2557
Patrick Williams1caf3b72023-03-31 10:59:10 -05002558 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !isVisibleForInput());
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002559
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002560 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002561 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002562 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002563
Vishnu Nair16a938f2021-09-24 07:14:54 -07002564 // If the window will be blacked out on a display because the display does not have the secure
2565 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002566 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002567 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002568 }
2569
Vishnu Nairfed7c122023-03-18 01:54:43 +00002570 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002571 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002572 Rect inputBoundsInDisplaySpace;
2573 if (!cropLayer) {
2574 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2575 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2576 } else {
2577 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2578 inputBoundsInDisplaySpace =
2579 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2580 }
2581 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002582 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002583 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2584 Rect inputBoundsInDisplaySpace =
2585 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2586 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002587 }
2588
Winson Chunga30f7c92021-06-29 15:42:56 -07002589 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2590 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002591 if (isTrustedOverlay()) {
2592 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2593 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002594
chaviwaf87b3e2019-10-01 16:59:28 -07002595 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2596 // touches from going outside the cloned area.
2597 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002598 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002599 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2600 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002601 info.touchableRegion = info.touchableRegion.intersect(rect);
2602 }
2603 }
2604
Vishnu Nair494a2e42023-11-10 17:21:19 -08002605 Rect bufferSize = getBufferSize(getDrawingState());
2606 info.contentSize = Size(bufferSize.width(), bufferSize.height());
2607
Robert Carr720e5062018-07-30 17:45:14 -07002608 return info;
2609}
2610
Vishnu Nairfed7c122023-03-18 01:54:43 +00002611Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2612 const ui::Transform& screenToDisplay) {
2613 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2614 // frame and transform used for the layer, which determines the bounds and the coordinate space
2615 // within which the layer will receive input.
2616
2617 // Coordinate space definitions:
2618 // - display: The display device's coordinate space. Correlates to pixels on the display.
2619 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2620 // - layer: The coordinate space of this layer.
2621 // - input: The coordinate space in which this layer will receive input events. This could be
2622 // different than layer space if a surfaceInset is used, which changes the origin
2623 // of the input space.
2624
2625 // Crop the input bounds to ensure it is within the parent's bounds.
2626 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2627 const ui::Transform layerToScreen = getInputTransform();
2628 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2629 return Rect{layerToDisplay.transform(croppedInputBounds)};
2630}
2631
chaviwaf87b3e2019-10-01 16:59:28 -07002632sp<Layer> Layer::getClonedRoot() {
2633 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002634 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002635 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002636 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002637 return nullptr;
2638 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002639 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002640}
2641
Robert Carredd13602020-04-13 17:24:34 -07002642bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002643 return mDrawingState.inputInfo.token != nullptr ||
2644 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002645}
2646
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002647compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002648 const DisplayDevice* display) const {
2649 if (!display) return nullptr;
Lloyd Pique30db6402023-06-26 18:56:51 +00002650 if (!mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00002651 return display->getCompositionDisplay()->getOutputLayerForLayer(
2652 getCompositionEngineLayerFE());
2653 }
2654 sp<LayerFE> layerFE;
2655 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2656 for (auto& [p, layer] : mLayerFEs) {
2657 if (p == path) {
2658 layerFE = layer;
2659 }
2660 }
2661
2662 if (!layerFE) return nullptr;
2663 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002664}
2665
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002666compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
2667 const DisplayDevice* display, const frontend::LayerHierarchy::TraversalPath& path) const {
2668 if (!display) return nullptr;
Vishnu Naire9ee0002023-07-01 03:14:51 +00002669 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2670 return display->getCompositionDisplay()->getOutputLayerForLayer(
2671 getCompositionEngineLayerFE());
2672 }
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002673 sp<LayerFE> layerFE;
2674 for (auto& [p, layer] : mLayerFEs) {
2675 if (p == path) {
2676 layerFE = layer;
2677 }
2678 }
2679
2680 if (!layerFE) return nullptr;
2681 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
2682}
2683
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002684Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2685 const auto outputLayer = findOutputLayerForDisplay(display);
2686 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002687}
2688
Vishnu Nairde177252023-04-21 12:44:10 -07002689void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom, uint32_t mirrorRootId) {
2690 mSnapshot->path.id = clonedFrom->getSequence();
Vishnu Nair6f878312023-09-08 11:05:01 -07002691 mSnapshot->path.mirrorRootIds.emplace_back(mirrorRootId);
Vishnu Nairde177252023-04-21 12:44:10 -07002692
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002693 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002694 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002695 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2696 mPotentialCursor = clonedFrom->mPotentialCursor;
2697 mProtectedByApp = clonedFrom->mProtectedByApp;
2698 updateCloneBufferInfo();
2699}
2700
2701void Layer::updateCloneBufferInfo() {
2702 if (!isClone() || !isClonedFromAlive()) {
2703 return;
2704 }
2705
2706 sp<Layer> clonedFrom = getClonedFrom();
2707 mBufferInfo = clonedFrom->mBufferInfo;
2708 mSidebandStream = clonedFrom->mSidebandStream;
2709 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2710 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2711 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2712
2713 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2714 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2715 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2716 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2717 // the cloned drawingState again.
2718 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2719 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2720 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2721 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2722
2723 cloneDrawingState(clonedFrom.get());
2724
2725 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2726 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2727 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2728 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002729}
chaviw74b03172019-08-19 11:09:03 -07002730
Vishnu Nair3be61902023-04-26 19:47:29 -07002731bool Layer::updateMirrorInfo(const std::deque<Layer*>& cloneRootsPendingUpdates) {
chaviw74b03172019-08-19 11:09:03 -07002732 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2733 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2734 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2735 // that case, we want to delete the reference to the clone since we want it to get
2736 // destroyed. The root, this layer, will still be around since the client can continue
2737 // to hold a reference, but no cloned layers will be displayed.
2738 mClonedChild = nullptr;
Vishnu Nair3be61902023-04-26 19:47:29 -07002739 return true;
chaviw74b03172019-08-19 11:09:03 -07002740 }
2741
2742 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2743 // If the real layer exists and is in current state, add the clone as a child of the root.
2744 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2745 // copied to drawingState for the root layer. So the clonedChild is always removed from
2746 // drawingState and then needs to be added back each traversal.
2747 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2748 addChildToDrawing(mClonedChild);
2749 }
2750
2751 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002752 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002753 mClonedChild->updateClonedRelatives(clonedLayersMap);
Vishnu Nair3be61902023-04-26 19:47:29 -07002754
2755 for (Layer* root : cloneRootsPendingUpdates) {
2756 if (clonedLayersMap.find(sp<Layer>::fromExisting(root)) != clonedLayersMap.end()) {
2757 return false;
2758 }
2759 }
2760 return true;
chaviw74b03172019-08-19 11:09:03 -07002761}
2762
2763void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2764 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2765 // to the clone. If the real layer is no longer alive, continue traversing the children
2766 // since we may be able to pull out other children that are still alive.
2767 if (isClonedFromAlive()) {
2768 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002769 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002770 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002771 }
2772
2773 // The clone layer may have children in drawingState since they may have been created and
2774 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2775 // that already exist, since we can just re-use them.
2776 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2777 // not updated in the regular traversal. They are skipped since the root will lose the
2778 // reference to them when it copies its currentChildren to drawing.
2779 for (sp<Layer>& child : mDrawingChildren) {
2780 child->updateClonedDrawingState(clonedLayersMap);
2781 }
2782}
2783
2784void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2785 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2786 mDrawingChildren.clear();
2787
2788 if (!isClonedFromAlive()) {
2789 return;
2790 }
2791
2792 sp<Layer> clonedFrom = getClonedFrom();
2793 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2794 if (child == mirrorRoot) {
2795 // This is to avoid cyclical mirroring.
2796 continue;
2797 }
2798 sp<Layer> clonedChild = clonedLayersMap[child];
2799 if (clonedChild == nullptr) {
Vishnu Nairde177252023-04-21 12:44:10 -07002800 clonedChild = child->createClone(mirrorRoot->getSequence());
chaviw74b03172019-08-19 11:09:03 -07002801 clonedLayersMap[child] = clonedChild;
2802 }
2803 addChildToDrawing(clonedChild);
2804 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2805 }
2806}
2807
chaviwaf87b3e2019-10-01 16:59:28 -07002808void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2809 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2810 if (cropLayer != nullptr) {
2811 if (clonedLayersMap.count(cropLayer) == 0) {
2812 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2813 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002814 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002815 } else {
2816 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2817 mDrawingState.touchableRegionCrop = clonedCropLayer;
2818 }
2819 }
2820 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2821 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002822 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002823}
2824
2825void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002826 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002827 mDrawingState.zOrderRelatives.clear();
2828
2829 if (!isClonedFromAlive()) {
2830 return;
2831 }
2832
chaviwaf87b3e2019-10-01 16:59:28 -07002833 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002834 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002835 const sp<Layer>& relative = relativeWeak.promote();
2836 if (clonedLayersMap.count(relative) > 0) {
2837 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002838 mDrawingState.zOrderRelatives.add(clonedRelative);
2839 }
2840 }
2841
2842 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2843 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2844 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2845 // still traverse the children, but the layer with the missing relativeOf will not be shown
2846 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002847 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2848 if (clonedLayersMap.count(relativeOf) > 0) {
2849 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002850 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2851 }
2852
chaviwaf87b3e2019-10-01 16:59:28 -07002853 updateClonedInputInfo(clonedLayersMap);
2854
chaviw74b03172019-08-19 11:09:03 -07002855 for (sp<Layer>& child : mDrawingChildren) {
2856 child->updateClonedRelatives(clonedLayersMap);
2857 }
2858}
2859
2860void Layer::addChildToDrawing(const sp<Layer>& layer) {
2861 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002862 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002863}
2864
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002865bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002866 const State& s(mDrawingState);
2867 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2868 return true;
2869 }
2870
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002871 sp<Layer> parent = mDrawingParent.promote();
2872 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002873}
2874
Robert Carr6a0382d2021-07-01 15:57:17 -07002875void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2876 mClonedChild = clonedChild;
2877 mHadClonedChild = true;
Vishnu Nair3be61902023-04-26 19:47:29 -07002878 mFlinger->mLayerMirrorRoots.push_back(this);
Robert Carr6a0382d2021-07-01 15:57:17 -07002879}
2880
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002881bool Layer::setDropInputMode(gui::DropInputMode mode) {
2882 if (mDrawingState.dropInputMode == mode) {
2883 return false;
2884 }
2885 mDrawingState.dropInputMode = mode;
2886 return true;
2887}
2888
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002889void Layer::cloneDrawingState(const Layer* from) {
2890 mDrawingState = from->mDrawingState;
2891 // Skip callback info since they are not applicable for cloned layers.
2892 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002893 // TODO (b/238781169) currently broken for mirror layers because we do not
2894 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002895 mDrawingState.callbackHandles = {};
2896}
2897
Patrick Williamsbb25f802022-08-30 23:02:34 +00002898void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2899 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002900 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002901 if (!listener) {
2902 return;
2903 }
2904 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002905 uint32_t currentMaxAcquiredBufferCount =
2906 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002907 listener->onReleaseBuffer({buffer->getId(), framenumber},
2908 releaseFence ? releaseFence : Fence::NO_FENCE,
2909 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002910}
2911
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002912void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
2913 ui::LayerStack layerStack) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002914 // If we are displayed on multiple displays in a single composition cycle then we would
2915 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2916 // For example we can only use it if all the displays are client comp, and we need
2917 // to merge all the client comp fences. We could do this, but for now we just
2918 // disable the optimization when a layer is composed on multiple displays.
2919 if (mClearClientCompositionFenceOnLayerDisplayed) {
2920 mLastClientCompositionFence = nullptr;
2921 } else {
2922 mClearClientCompositionFenceOnLayerDisplayed = true;
2923 }
2924
2925 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2926 // buffer that was presented on this layer. The first transaction that came in this frame that
2927 // replaced the previous buffer on this layer needs this release fence, because the fence will
2928 // let the client know when that previous buffer is removed from the screen.
2929 //
2930 // Every other transaction on this layer does not need a release fence because no other
2931 // Transactions that were set on this layer this frame are going to have their preceding buffer
2932 // removed from the display this frame.
2933 //
2934 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2935 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2936 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2937 // the previous buffer will be released this frame. The third transaction also contains a
2938 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2939 // transaction will now no longer be presented so it is released immediately and the third
2940 // transaction doesn't need a previous release fence.
2941 sp<CallbackHandle> ch;
2942 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002943 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002944 ch = handle;
2945 break;
2946 }
2947 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002948 if (ch != nullptr) {
2949 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2950 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2951 ch->name = mName;
2952 }
Vishnu Nair316b7f42023-10-13 23:44:46 +00002953 if (mBufferInfo.mBuffer) {
2954 mPreviouslyPresentedLayerStacks.push_back(layerStack);
2955 }
Alec Mouri21d94322023-10-17 19:51:39 +00002956
2957 if (mDrawingState.frameNumber > 0) {
2958 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
2959 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002960}
2961
2962void Layer::onSurfaceFrameCreated(
2963 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2964 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2965 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2966 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2967 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002968 if (hasBufferOrSidebandStreamInDrawing()) {
2969 // Only log for layers with a buffer, since we expect the jank data to be drained for
2970 // these, while there may be no jank listeners for bufferless layers.
2971 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2972 mName.c_str());
2973 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2974 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2975 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002976 mPendingJankClassifications.pop_front();
2977 }
2978 mPendingJankClassifications.emplace_back(surfaceFrame);
2979}
2980
2981void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2982 for (const auto& handle : mDrawingState.callbackHandles) {
Lloyd Pique30db6402023-06-26 18:56:51 +00002983 if (mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -07002984 handle->transformHint = mTransformHint;
2985 } else {
2986 handle->transformHint = mSkipReportingTransformHint
2987 ? std::nullopt
2988 : std::make_optional<uint32_t>(mTransformHintLegacy);
2989 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002990 handle->dequeueReadyTime = dequeueReadyTime;
2991 handle->currentMaxAcquiredBufferCount =
2992 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2993 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2994 handle->previousReleaseCallbackId.framenumber);
2995 }
2996
2997 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002998 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002999 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
3000 break;
3001 }
3002 }
3003
3004 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01003005 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003006 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
3007 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003008 mDrawingState.callbackHandles = {};
3009}
3010
3011bool Layer::willPresentCurrentTransaction() const {
3012 // Returns true if the most recent Transaction applied to CurrentState will be presented.
3013 return (getSidebandStreamChanged() || getAutoRefresh() ||
3014 (mDrawingState.modified &&
3015 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
3016}
3017
3018bool Layer::setTransform(uint32_t transform) {
3019 if (mDrawingState.bufferTransform == transform) return false;
3020 mDrawingState.bufferTransform = transform;
3021 mDrawingState.modified = true;
3022 setTransactionFlags(eTransactionNeeded);
3023 return true;
3024}
3025
3026bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
3027 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
3028 mDrawingState.sequence++;
3029 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
3030 mDrawingState.modified = true;
3031 setTransactionFlags(eTransactionNeeded);
3032 return true;
3033}
3034
3035bool Layer::setBufferCrop(const Rect& bufferCrop) {
3036 if (mDrawingState.bufferCrop == bufferCrop) return false;
3037
3038 mDrawingState.sequence++;
3039 mDrawingState.bufferCrop = bufferCrop;
3040
3041 mDrawingState.modified = true;
3042 setTransactionFlags(eTransactionNeeded);
3043 return true;
3044}
3045
3046bool Layer::setDestinationFrame(const Rect& destinationFrame) {
3047 if (mDrawingState.destinationFrame == destinationFrame) return false;
3048
3049 mDrawingState.sequence++;
3050 mDrawingState.destinationFrame = destinationFrame;
3051
3052 mDrawingState.modified = true;
3053 setTransactionFlags(eTransactionNeeded);
3054 return true;
3055}
3056
3057// Translate destination frame into scale and position. If a destination frame is not set, use the
3058// provided scale and position
3059bool Layer::updateGeometry() {
3060 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
3061 mDrawingState.destinationFrame.isEmpty()) {
3062 // If destination frame is not set, use the requested transform set via
3063 // Layer::setPosition and Layer::setMatrix.
3064 return assignTransform(&mDrawingState.transform, mRequestedTransform);
3065 }
3066
3067 Rect destRect = mDrawingState.destinationFrame;
3068 int32_t destW = destRect.width();
3069 int32_t destH = destRect.height();
3070 if (destRect.left < 0) {
3071 destRect.left = 0;
3072 destRect.right = destW;
3073 }
3074 if (destRect.top < 0) {
3075 destRect.top = 0;
3076 destRect.bottom = destH;
3077 }
3078
3079 if (!mDrawingState.buffer) {
3080 ui::Transform t;
3081 t.set(destRect.left, destRect.top);
3082 return assignTransform(&mDrawingState.transform, t);
3083 }
3084
3085 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3086 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3087 // Undo any transformations on the buffer.
3088 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3089 std::swap(bufferWidth, bufferHeight);
3090 }
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003091 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003092 if (mDrawingState.transformToDisplayInverse) {
3093 if (invTransform & ui::Transform::ROT_90) {
3094 std::swap(bufferWidth, bufferHeight);
3095 }
3096 }
3097
3098 float sx = destW / static_cast<float>(bufferWidth);
3099 float sy = destH / static_cast<float>(bufferHeight);
3100 ui::Transform t;
3101 t.set(sx, 0, 0, sy);
3102 t.set(destRect.left, destRect.top);
3103 return assignTransform(&mDrawingState.transform, t);
3104}
3105
3106bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3107 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3108 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3109 return false;
3110 }
3111
3112 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3113
3114 mDrawingState.sequence++;
3115 mDrawingState.modified = true;
3116 setTransactionFlags(eTransactionNeeded);
3117
3118 return true;
3119}
3120
3121bool Layer::setPosition(float x, float y) {
3122 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3123 return false;
3124 }
3125
3126 mRequestedTransform.set(x, y);
3127
3128 mDrawingState.sequence++;
3129 mDrawingState.modified = true;
3130 setTransactionFlags(eTransactionNeeded);
3131
3132 return true;
3133}
3134
Dorin Drimuse5374e52023-08-02 17:52:43 +00003135void Layer::releasePreviousBuffer() {
3136 mReleasePreviousBuffer = true;
3137 if (!mBufferInfo.mBuffer ||
3138 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3139 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3140 // If mDrawingState has a buffer, and we are about to update again
3141 // before swapping to drawing state, then the first buffer will be
3142 // dropped and we should decrement the pending buffer count and
3143 // call any release buffer callbacks if set.
3144 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3145 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3146 mDrawingState.acquireFence);
3147 decrementPendingBufferCount();
3148 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3149 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3150 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX, systemTime());
3151 mDrawingState.bufferSurfaceFrameTX.reset();
3152 }
3153 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3154 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3155 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3156 mLastClientCompositionFence);
3157 mLastClientCompositionFence = nullptr;
3158 }
3159}
3160
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003161void Layer::resetDrawingStateBufferInfo() {
3162 mDrawingState.producerId = 0;
3163 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +00003164 mDrawingState.previousFrameNumber = 0;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003165 mDrawingState.releaseBufferListener = nullptr;
3166 mDrawingState.buffer = nullptr;
3167 mDrawingState.acquireFence = sp<Fence>::make(-1);
3168 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3169 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3170 mDrawingState.releaseBufferEndpoint = nullptr;
3171}
3172
Patrick Williamsbb25f802022-08-30 23:02:34 +00003173bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3174 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3175 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003176 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003177 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003178
3179 const bool frameNumberChanged =
3180 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3181 const uint64_t frameNumber =
3182 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003183 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003184
3185 if (mDrawingState.buffer) {
Dorin Drimuse5374e52023-08-02 17:52:43 +00003186 releasePreviousBuffer();
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003187 } else if (buffer) {
Vishnu Nairc09c0232023-03-02 03:22:35 +00003188 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3189 // we don't want to incorrectly classify a frame if we miss the desired present time.
3190 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003191 }
3192
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003193 mDrawingState.desiredPresentTime = desiredPresentTime;
3194 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3195 mDrawingState.latchedVsyncId = info.vsyncId;
Ady Abraham55269162023-05-09 11:26:06 -07003196 mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003197 mDrawingState.modified = true;
3198 if (!buffer) {
3199 resetDrawingStateBufferInfo();
3200 setTransactionFlags(eTransactionNeeded);
3201 mDrawingState.bufferSurfaceFrameTX = nullptr;
3202 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3203 return true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003204 } else {
3205 // release sideband stream if it exists and a non null buffer is being set
3206 if (mDrawingState.sidebandStream != nullptr) {
Dorin Drimus66ed1c42023-09-27 13:10:16 +00003207 setSidebandStream(nullptr, info, postTime);
Dorin Drimuse5374e52023-08-02 17:52:43 +00003208 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003209 }
3210
Vishnu Naird1f74982023-06-15 20:16:51 -07003211 if ((mDrawingState.producerId > bufferData.producerId) ||
3212 ((mDrawingState.producerId == bufferData.producerId) &&
3213 (mDrawingState.frameNumber > frameNumber))) {
3214 ALOGE("Out of order buffers detected for %s producedId=%d frameNumber=%" PRIu64
3215 " -> producedId=%d frameNumber=%" PRIu64,
3216 getDebugName(), mDrawingState.producerId, mDrawingState.frameNumber,
3217 bufferData.producerId, frameNumber);
3218 TransactionTraceWriter::getInstance().invoke("out_of_order_buffers_", /*overwrite=*/false);
3219 }
3220
liulijuneb489f62022-10-17 22:02:14 +08003221 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -07003222 mDrawingState.barrierProducerId =
3223 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003224 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -07003225 mDrawingState.barrierFrameNumber =
3226 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
3227
Patrick Williamsbb25f802022-08-30 23:02:34 +00003228 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3229 mDrawingState.buffer = std::move(buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003230 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3231 ? bufferData.acquireFence
3232 : Fence::NO_FENCE;
3233 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3234 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3235 // We latched this buffer unsiganled, so we need to pass the acquire fence
3236 // on the callback instead of just the acquire time, since it's unknown at
3237 // this point.
3238 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3239 } else {
3240 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3241 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003242 setTransactionFlags(eTransactionNeeded);
3243
3244 const int32_t layerId = getSequence();
3245 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3246 mOwnerUid, postTime, getGameMode());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003247
Lloyd Pique30db6402023-06-26 18:56:51 +00003248 if (mFlinger->mLegacyFrontEndEnabled) {
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003249 recordLayerHistoryBufferUpdate(getLayerProps(), systemTime());
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003250 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003251
3252 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3253
3254 if (dequeueTime && *dequeueTime != 0) {
3255 const uint64_t bufferId = mDrawingState.buffer->getId();
3256 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3257 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3258 FrameTracer::FrameEvent::DEQUEUE);
3259 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3260 FrameTracer::FrameEvent::QUEUE);
3261 }
3262
3263 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
Arthur Hungc70bee22023-06-02 01:35:52 +00003264
3265 // If the layer had been updated a TextureView, this would make sure the present time could be
3266 // same to TextureView update when it's a small dirty, and get the correct heuristic rate.
Jerry Chang36678002023-11-29 16:56:17 +00003267 if (mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00003268 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3269 mUsedVsyncIdForRefreshRateSelection = true;
3270 }
3271 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003272 return true;
3273}
3274
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003275void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3276 mDrawingState.desiredPresentTime = desiredPresentTime;
3277 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3278}
3279
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003280void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps, nsecs_t now) {
Ady Abraham55269162023-05-09 11:26:06 -07003281 ATRACE_CALL();
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003282 const nsecs_t presentTime = [&] {
Ady Abraham55269162023-05-09 11:26:06 -07003283 if (!mDrawingState.isAutoTimestamp) {
3284 ATRACE_FORMAT_INSTANT("desiredPresentTime");
3285 return mDrawingState.desiredPresentTime;
3286 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003287
Ady Abraham55269162023-05-09 11:26:06 -07003288 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3289 const auto prediction =
3290 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3291 mDrawingState.latchedVsyncId);
3292 if (prediction.has_value()) {
3293 ATRACE_FORMAT_INSTANT("predictedPresentTime");
Arthur Hungc70bee22023-06-02 01:35:52 +00003294 mMaxTimeForUseVsyncId = prediction->presentTime +
3295 scheduler::LayerHistory::kMaxPeriodForHistory.count();
Ady Abraham55269162023-05-09 11:26:06 -07003296 return prediction->presentTime;
3297 }
3298 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003299
Jerry Chang36678002023-11-29 16:56:17 +00003300 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00003301 return static_cast<nsecs_t>(0);
3302 }
3303
3304 // If the layer is not an application and didn't set an explicit rate or desiredPresentTime,
3305 // return "0" to tell the layer history that it will use the max refresh rate without
3306 // calculating the adaptive rate.
3307 if (mWindowType != WindowInfo::Type::APPLICATION &&
3308 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
3309 return static_cast<nsecs_t>(0);
3310 }
3311
3312 // Return the valid present time only when the layer potentially updated a TextureView so
3313 // LayerHistory could heuristically calculate the rate if the UI is continually updating.
3314 if (mUsedVsyncIdForRefreshRateSelection) {
3315 const auto prediction =
3316 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3317 mDrawingState.latchedVsyncId);
3318 if (prediction.has_value()) {
3319 if (mMaxTimeForUseVsyncId >= prediction->presentTime) {
3320 return prediction->presentTime;
3321 }
3322 mUsedVsyncIdForRefreshRateSelection = false;
3323 }
3324 }
3325
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003326 return static_cast<nsecs_t>(0);
3327 }();
Ady Abraham55269162023-05-09 11:26:06 -07003328
3329 if (ATRACE_ENABLED() && presentTime > 0) {
3330 const auto presentIn = TimePoint::fromNs(presentTime) - TimePoint::now();
3331 ATRACE_FORMAT_INSTANT("presentIn %s", to_string(presentIn).c_str());
3332 }
3333
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003334 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003335 scheduler::LayerHistory::LayerUpdateType::Buffer);
3336}
3337
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003338void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps, nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003339 const nsecs_t presentTime =
3340 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003341 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003342 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3343}
3344
Patrick Williamsbb25f802022-08-30 23:02:34 +00003345bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003346 if (mDrawingState.dataspace == dataspace) return false;
3347 mDrawingState.dataspace = dataspace;
3348 mDrawingState.modified = true;
3349 setTransactionFlags(eTransactionNeeded);
3350 return true;
3351}
3352
John Reck68796592023-01-25 13:47:12 -05003353bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07003354 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3355 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05003356 return false;
Sally Qi963049b2023-03-23 14:06:21 -07003357 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3358 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05003359 mDrawingState.modified = true;
3360 setTransactionFlags(eTransactionNeeded);
3361 return true;
3362}
3363
Alec Mourif4af03e2023-02-11 00:25:24 +00003364bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3365 if (mDrawingState.cachingHint == cachingHint) return false;
3366 mDrawingState.cachingHint = cachingHint;
3367 mDrawingState.modified = true;
3368 setTransactionFlags(eTransactionNeeded);
3369 return true;
3370}
3371
Patrick Williamsbb25f802022-08-30 23:02:34 +00003372bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3373 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3374 mDrawingState.hdrMetadata = hdrMetadata;
3375 mDrawingState.modified = true;
3376 setTransactionFlags(eTransactionNeeded);
3377 return true;
3378}
3379
3380bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003381 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003382 mDrawingState.surfaceDamageRegion = surfaceDamage;
3383 mDrawingState.modified = true;
3384 setTransactionFlags(eTransactionNeeded);
Arthur Hung69f95222023-10-04 07:39:02 +00003385 setIsSmallDirty(surfaceDamage, getTransform());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003386 return true;
3387}
3388
3389bool Layer::setApi(int32_t api) {
3390 if (mDrawingState.api == api) return false;
3391 mDrawingState.api = api;
3392 mDrawingState.modified = true;
3393 setTransactionFlags(eTransactionNeeded);
3394 return true;
3395}
3396
Dorin Drimuse5374e52023-08-02 17:52:43 +00003397bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream, const FrameTimelineInfo& info,
3398 nsecs_t postTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003399 if (mDrawingState.sidebandStream == sidebandStream) return false;
3400
3401 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3402 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3403 } else if (sidebandStream != nullptr) {
3404 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3405 }
3406
3407 mDrawingState.sidebandStream = sidebandStream;
3408 mDrawingState.modified = true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003409 if (sidebandStream != nullptr && mDrawingState.buffer != nullptr) {
3410 releasePreviousBuffer();
3411 resetDrawingStateBufferInfo();
3412 mDrawingState.bufferSurfaceFrameTX = nullptr;
3413 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3414 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003415 setTransactionFlags(eTransactionNeeded);
3416 if (!mSidebandStreamChanged.exchange(true)) {
3417 // mSidebandStreamChanged was false
3418 mFlinger->onLayerUpdate();
3419 }
3420 return true;
3421}
3422
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003423bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3424 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003425 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3426 if (handles.empty()) {
3427 mReleasePreviousBuffer = false;
3428 return false;
3429 }
3430
Pascal Muetschard81cef292023-02-06 12:18:52 +01003431 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003432 for (const auto& handle : handles) {
3433 // If this transaction set a buffer on this layer, release its previous buffer
3434 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3435
3436 // If this layer will be presented in this frame
3437 if (willPresent) {
3438 // If this transaction set an acquire fence on this layer, set its acquire time
3439 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3440 handle->frameNumber = mDrawingState.frameNumber;
Alec Mouri21d94322023-10-17 19:51:39 +00003441 handle->previousFrameNumber = mDrawingState.previousFrameNumber;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003442
3443 // Store so latched time and release fence can be set
3444 mDrawingState.callbackHandles.push_back(handle);
3445
3446 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003447 // Queue this handle to be notified below.
3448 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003449 }
3450 }
3451
Pascal Muetschard81cef292023-02-06 12:18:52 +01003452 if (!remainingHandles.empty()) {
3453 // Notify the transaction completed threads these handles are done. These are only the
3454 // handles that were not added to the mDrawingState, which will be notified later.
3455 std::vector<JankData> jankData;
3456 transferAvailableJankData(remainingHandles, jankData);
3457 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3458 }
3459
Patrick Williamsbb25f802022-08-30 23:02:34 +00003460 mReleasePreviousBuffer = false;
3461 mCallbackHandleAcquireTimeOrFence = -1;
3462
3463 return willPresent;
3464}
3465
3466Rect Layer::getBufferSize(const State& /*s*/) const {
3467 // for buffer state layers we use the display frame size as the buffer size.
3468
3469 if (mBufferInfo.mBuffer == nullptr) {
3470 return Rect::INVALID_RECT;
3471 }
3472
3473 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3474 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3475
3476 // Undo any transformations on the buffer and return the result.
3477 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3478 std::swap(bufWidth, bufHeight);
3479 }
3480
3481 if (getTransformToDisplayInverse()) {
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003482 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003483 if (invTransform & ui::Transform::ROT_90) {
3484 std::swap(bufWidth, bufHeight);
3485 }
3486 }
3487
3488 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3489}
3490
3491FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3492 if (mBufferInfo.mBuffer == nullptr) {
3493 return parentBounds;
3494 }
3495
3496 return getBufferSize(getDrawingState()).toFloatRect();
3497}
3498
3499bool Layer::fenceHasSignaled() const {
3500 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3501 return true;
3502 }
3503
3504 const bool fenceSignaled =
3505 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3506 if (!fenceSignaled) {
3507 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3508 TimeStats::LatchSkipReason::LateAcquire);
3509 }
3510
3511 return fenceSignaled;
3512}
3513
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003514void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003515 for (const auto& handle : mDrawingState.callbackHandles) {
3516 handle->refreshStartTime = refreshStartTime;
3517 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003518}
3519
3520void Layer::setAutoRefresh(bool autoRefresh) {
3521 mDrawingState.autoRefresh = autoRefresh;
3522}
3523
3524bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3525 // 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 +00003526 auto* snapshot = editLayerSnapshot();
3527 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003528
3529 if (mSidebandStreamChanged.exchange(false)) {
3530 const State& s(getDrawingState());
3531 // mSidebandStreamChanged was true
3532 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003533 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003534 if (mSidebandStream != nullptr) {
3535 setTransactionFlags(eTransactionNeeded);
3536 mFlinger->setTransactionFlags(eTraversalNeeded);
3537 }
3538 recomputeVisibleRegions = true;
3539
3540 return true;
3541 }
3542 return false;
3543}
3544
3545bool Layer::hasFrameUpdate() const {
3546 const State& c(getDrawingState());
3547 return (mDrawingStateModified || mDrawingState.modified) &&
3548 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3549}
3550
Vishnu Naird47bcee2023-02-24 18:08:51 +00003551void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003552 const State& s(getDrawingState());
3553
3554 if (!s.buffer) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003555 if (bgColorOnly || mBufferInfo.mBuffer) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003556 for (auto& handle : mDrawingState.callbackHandles) {
3557 handle->latchTime = latchTime;
3558 }
3559 }
3560 return;
3561 }
3562
3563 for (auto& handle : mDrawingState.callbackHandles) {
3564 if (handle->frameNumber == mDrawingState.frameNumber) {
3565 handle->latchTime = latchTime;
3566 }
3567 }
3568
3569 const int32_t layerId = getSequence();
3570 const uint64_t bufferId = mDrawingState.buffer->getId();
3571 const uint64_t frameNumber = mDrawingState.frameNumber;
3572 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3573 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3574 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3575
3576 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3577 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3578 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3579 FrameTracer::FrameEvent::LATCH);
3580
3581 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3582 if (bufferSurfaceFrame != nullptr &&
3583 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3584 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3585 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3586 // are processing the next state.
3587 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3588 mDrawingState.acquireFenceTime->getSignalTime(),
3589 latchTime);
3590 mDrawingState.bufferSurfaceFrameTX.reset();
3591 }
3592
3593 std::deque<sp<CallbackHandle>> remainingHandles;
3594 mFlinger->getTransactionCallbackInvoker()
3595 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3596 mDrawingState.callbackHandles = remainingHandles;
3597
3598 mDrawingStateModified = false;
3599}
3600
3601void Layer::gatherBufferInfo() {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003602 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3603 mPreviousReleaseBufferEndpoint = mBufferInfo.mReleaseBufferEndpoint;
3604 if (!mDrawingState.buffer) {
3605 mBufferInfo = {};
3606 return;
3607 }
3608
3609 if ((!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer))) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003610 decrementPendingBufferCount();
3611 }
3612
Patrick Williamsbb25f802022-08-30 23:02:34 +00003613 mBufferInfo.mBuffer = mDrawingState.buffer;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003614 mBufferInfo.mReleaseBufferEndpoint = mDrawingState.releaseBufferEndpoint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003615 mBufferInfo.mFence = mDrawingState.acquireFence;
3616 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3617 mBufferInfo.mPixelFormat =
3618 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3619 mBufferInfo.mFrameLatencyNeeded = true;
3620 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3621 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3622 mBufferInfo.mFence = mDrawingState.acquireFence;
3623 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3624 auto lastDataspace = mBufferInfo.mDataspace;
3625 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003626 if (mBufferInfo.mBuffer != nullptr) {
3627 auto& mapper = GraphicBufferMapper::get();
3628 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
3629 // and don't need to possibly remaps buffers.
3630 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
3631 status_t err = OK;
3632 {
3633 ATRACE_NAME("getDataspace");
3634 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
3635 }
3636 if (err != OK || dataspace != mBufferInfo.mDataspace) {
3637 {
3638 ATRACE_NAME("setDataspace");
3639 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
3640 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
3641 }
3642
3643 // Some GPU drivers may cache gralloc metadata which means before we composite we need
3644 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
3645 // compatible with old vendors, with a ticking clock.
3646 static const int32_t kVendorVersion =
Alec Mouri8a06fb72023-11-16 22:07:13 +00003647 base::GetIntProperty("ro.board.api_level", __ANDROID_API_FUTURE__);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003648 if (const auto format =
3649 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
3650 mBufferInfo.mBuffer->getPixelFormat());
3651 err == OK && kVendorVersion < __ANDROID_API_U__ &&
3652 (format ==
3653 aidl::android::hardware::graphics::common::PixelFormat::
3654 IMPLEMENTATION_DEFINED ||
3655 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
3656 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
3657 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
3658 mBufferInfo.mBuffer->remapBuffer();
3659 }
3660 }
3661 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003662 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003663 mFlinger->mHdrLayerInfoChanged = true;
3664 }
Sally Qi963049b2023-03-23 14:06:21 -07003665 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3666 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05003667 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003668 }
3669 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3670 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3671 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3672 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3673 mBufferInfo.mApi = mDrawingState.api;
3674 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003675}
3676
3677Rect Layer::computeBufferCrop(const State& s) {
3678 if (s.buffer && !s.bufferCrop.isEmpty()) {
3679 Rect bufferCrop;
3680 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3681 return bufferCrop;
3682 } else if (s.buffer) {
3683 return s.buffer->getBounds();
3684 } else {
3685 return s.bufferCrop;
3686 }
3687}
3688
Vishnu Nairde177252023-04-21 12:44:10 -07003689sp<Layer> Layer::createClone(uint32_t mirrorRootId) {
Kean Mariotti4ba343c2023-04-19 13:31:02 +00003690 surfaceflinger::LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0,
3691 LayerMetadata());
Patrick Williams83f36b22022-09-14 17:57:35 +00003692 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Vishnu Nairde177252023-04-21 12:44:10 -07003693 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this), mirrorRootId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003694 return layer;
3695}
3696
Patrick Williamsbb25f802022-08-30 23:02:34 +00003697void Layer::decrementPendingBufferCount() {
3698 int32_t pendingBuffers = --mPendingBufferTransactions;
3699 tracePendingBufferCount(pendingBuffers);
3700}
3701
3702void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3703 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3704}
3705
3706/*
3707 * We don't want to send the layer's transform to input, but rather the
3708 * parent's transform. This is because Layer's transform is
3709 * information about how the buffer is placed on screen. The parent's
3710 * transform makes more sense to send since it's information about how the
3711 * layer is placed on screen. This transform is used by input to determine
3712 * how to go from screen space back to window space.
3713 */
3714ui::Transform Layer::getInputTransform() const {
3715 if (!hasBufferOrSidebandStream()) {
3716 return getTransform();
3717 }
3718 sp<Layer> parent = mDrawingParent.promote();
3719 if (parent == nullptr) {
3720 return ui::Transform();
3721 }
3722
3723 return parent->getTransform();
3724}
3725
3726/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003727 * Returns the bounds used to fill the input frame and the touchable region.
3728 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003729 * Similar to getInputTransform, we need to update the bounds to include the transform.
3730 * This is because bounds don't include the buffer transform, where the input assumes
3731 * that's already included.
3732 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003733std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3734 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3735 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3736 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3737 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3738 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003739 }
3740
Vishnu Nairfed7c122023-03-18 01:54:43 +00003741 bool inputBoundsValid = croppedBufferSize.isValid();
3742 if (!inputBoundsValid) {
3743 /**
3744 * Input bounds are based on the layer crop or buffer size. But if we are using
3745 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3746 * we can use the parent bounds as the input bounds if the layer does not have buffer
3747 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3748 * use the parent bounds. A layer without a buffer can get input. So when a window is
3749 * initially added, its touchable region can fill its parent layer bounds and that can
3750 * have negative consequences.
3751 */
3752 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003753 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003754
3755 // Clamp surface inset to the input bounds.
3756 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3757 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3758 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3759
3760 // Apply the insets to the input bounds.
3761 inputBounds.left += xSurfaceInset;
3762 inputBounds.top += ySurfaceInset;
3763 inputBounds.right -= xSurfaceInset;
3764 inputBounds.bottom -= ySurfaceInset;
3765
3766 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003767}
3768
Ady Abraham005398b2023-06-05 13:59:41 -07003769bool Layer::isSimpleBufferUpdate(const layer_state_t& s) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003770 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3771
3772 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3773 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3774 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3775 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3776 layer_state_t::eReparent;
3777
Patrick Williamsbb25f802022-08-30 23:02:34 +00003778 if ((s.what & requiredFlags) != requiredFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003779 ATRACE_FORMAT_INSTANT("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3780 (s.what | requiredFlags) & ~s.what);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003781 return false;
3782 }
3783
3784 if (s.what & deniedFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003785 ATRACE_FORMAT_INSTANT("%s: false [has denied flags 0x%" PRIx64 "]", __func__,
3786 s.what & deniedFlags);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003787 return false;
3788 }
3789
Patrick Williamsbb25f802022-08-30 23:02:34 +00003790 if (s.what & layer_state_t::ePositionChanged) {
3791 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
Ady Abraham005398b2023-06-05 13:59:41 -07003792 ATRACE_FORMAT_INSTANT("%s: false [ePositionChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003793 return false;
3794 }
3795 }
3796
3797 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003798 if (mDrawingState.color.a != s.color.a) {
Ady Abraham005398b2023-06-05 13:59:41 -07003799 ATRACE_FORMAT_INSTANT("%s: false [eAlphaChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003800 return false;
3801 }
3802 }
3803
3804 if (s.what & layer_state_t::eColorTransformChanged) {
3805 if (mDrawingState.colorTransform != s.colorTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003806 ATRACE_FORMAT_INSTANT("%s: false [eColorTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003807 return false;
3808 }
3809 }
3810
3811 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003812 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Ady Abraham005398b2023-06-05 13:59:41 -07003813 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundColorChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003814 return false;
3815 }
3816 }
3817
3818 if (s.what & layer_state_t::eMatrixChanged) {
3819 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3820 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3821 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3822 mRequestedTransform.dsdy() != s.matrix.dsdy) {
Ady Abraham005398b2023-06-05 13:59:41 -07003823 ATRACE_FORMAT_INSTANT("%s: false [eMatrixChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003824 return false;
3825 }
3826 }
3827
3828 if (s.what & layer_state_t::eCornerRadiusChanged) {
3829 if (mDrawingState.cornerRadius != s.cornerRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003830 ATRACE_FORMAT_INSTANT("%s: false [eCornerRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003831 return false;
3832 }
3833 }
3834
3835 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3836 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
Ady Abraham005398b2023-06-05 13:59:41 -07003837 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003838 return false;
3839 }
3840 }
3841
Vishnu Nairbbceb462022-10-10 04:52:13 +00003842 if (s.what & layer_state_t::eBufferTransformChanged) {
3843 if (mDrawingState.bufferTransform != s.bufferTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003844 ATRACE_FORMAT_INSTANT("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003845 return false;
3846 }
3847 }
3848
3849 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3850 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
Ady Abraham005398b2023-06-05 13:59:41 -07003851 ATRACE_FORMAT_INSTANT("%s: false [eTransformToDisplayInverseChanged changed]",
3852 __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003853 return false;
3854 }
3855 }
3856
3857 if (s.what & layer_state_t::eCropChanged) {
3858 if (mDrawingState.crop != s.crop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003859 ATRACE_FORMAT_INSTANT("%s: false [eCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003860 return false;
3861 }
3862 }
3863
3864 if (s.what & layer_state_t::eDataspaceChanged) {
3865 if (mDrawingState.dataspace != s.dataspace) {
Ady Abraham005398b2023-06-05 13:59:41 -07003866 ATRACE_FORMAT_INSTANT("%s: false [eDataspaceChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003867 return false;
3868 }
3869 }
3870
3871 if (s.what & layer_state_t::eHdrMetadataChanged) {
3872 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
Ady Abraham005398b2023-06-05 13:59:41 -07003873 ATRACE_FORMAT_INSTANT("%s: false [eHdrMetadataChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003874 return false;
3875 }
3876 }
3877
3878 if (s.what & layer_state_t::eSidebandStreamChanged) {
3879 if (mDrawingState.sidebandStream != s.sidebandStream) {
Ady Abraham005398b2023-06-05 13:59:41 -07003880 ATRACE_FORMAT_INSTANT("%s: false [eSidebandStreamChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003881 return false;
3882 }
3883 }
3884
3885 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3886 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
Ady Abraham005398b2023-06-05 13:59:41 -07003887 ATRACE_FORMAT_INSTANT("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003888 return false;
3889 }
3890 }
3891
3892 if (s.what & layer_state_t::eShadowRadiusChanged) {
3893 if (mDrawingState.shadowRadius != s.shadowRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003894 ATRACE_FORMAT_INSTANT("%s: false [eShadowRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003895 return false;
3896 }
3897 }
3898
3899 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3900 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
Ady Abraham005398b2023-06-05 13:59:41 -07003901 ATRACE_FORMAT_INSTANT("%s: false [eFixedTransformHintChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003902 return false;
3903 }
3904 }
3905
3906 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3907 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
Ady Abraham005398b2023-06-05 13:59:41 -07003908 ATRACE_FORMAT_INSTANT("%s: false [eTrustedOverlayChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003909 return false;
3910 }
3911 }
3912
3913 if (s.what & layer_state_t::eStretchChanged) {
3914 StretchEffect temp = s.stretchEffect;
3915 temp.sanitize();
3916 if (mDrawingState.stretchEffect != temp) {
Ady Abraham005398b2023-06-05 13:59:41 -07003917 ATRACE_FORMAT_INSTANT("%s: false [eStretchChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003918 return false;
3919 }
3920 }
3921
3922 if (s.what & layer_state_t::eBufferCropChanged) {
3923 if (mDrawingState.bufferCrop != s.bufferCrop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003924 ATRACE_FORMAT_INSTANT("%s: false [eBufferCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003925 return false;
3926 }
3927 }
3928
3929 if (s.what & layer_state_t::eDestinationFrameChanged) {
3930 if (mDrawingState.destinationFrame != s.destinationFrame) {
Ady Abraham005398b2023-06-05 13:59:41 -07003931 ATRACE_FORMAT_INSTANT("%s: false [eDestinationFrameChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003932 return false;
3933 }
3934 }
3935
3936 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3937 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
Ady Abraham005398b2023-06-05 13:59:41 -07003938 ATRACE_FORMAT_INSTANT("%s: false [eDimmingEnabledChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003939 return false;
3940 }
3941 }
3942
John Reck68796592023-01-25 13:47:12 -05003943 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07003944 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
3945 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
Ady Abraham005398b2023-06-05 13:59:41 -07003946 ATRACE_FORMAT_INSTANT("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05003947 return false;
3948 }
3949 }
3950
Patrick Williamsbb25f802022-08-30 23:02:34 +00003951 return true;
3952}
3953
Vishnu Naire14c6b32022-08-06 04:20:15 +00003954sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003955 // 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 +00003956 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003957}
3958
Vishnu Naire14c6b32022-08-06 04:20:15 +00003959const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003960 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003961}
3962
Vishnu Naire14c6b32022-08-06 04:20:15 +00003963LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003964 return mSnapshot.get();
3965}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003966
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003967std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3968 return std::move(mSnapshot);
3969}
3970
3971void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3972 mSnapshot = std::move(snapshot);
3973}
3974
Patrick Williamsbb25f802022-08-30 23:02:34 +00003975const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003976 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003977}
3978
Patrick Williams7584c6a2022-10-29 02:10:58 +00003979sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003980 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003981 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3982 return result;
3983}
3984
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003985sp<LayerFE> Layer::getCompositionEngineLayerFE(
3986 const frontend::LayerHierarchy::TraversalPath& path) {
3987 for (auto& [p, layerFE] : mLayerFEs) {
3988 if (p == path) {
3989 return layerFE;
3990 }
3991 }
3992 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3993 mLayerFEs.emplace_back(path, layerFE);
3994 return layerFE;
3995}
3996
Patrick Williamsbb25f802022-08-30 23:02:34 +00003997void Layer::useSurfaceDamage() {
3998 if (mFlinger->mForceFullDamage) {
3999 surfaceDamageRegion = Region::INVALID_REGION;
4000 } else {
4001 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
4002 }
4003}
4004
4005void Layer::useEmptyDamage() {
4006 surfaceDamageRegion.clear();
4007}
4008
4009bool Layer::isOpaque(const Layer::State& s) const {
4010 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
4011 // layer's opaque flag.
4012 if (!hasSomethingToDraw()) {
4013 return false;
4014 }
4015
4016 // if the layer has the opaque flag, then we're always opaque
4017 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
4018 return true;
4019 }
4020
4021 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004022 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004023 return true;
4024 }
4025
4026 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
4027 return fillsColor() && getAlpha() == 1.0_hf;
4028}
4029
4030bool Layer::canReceiveInput() const {
4031 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
4032}
4033
4034bool Layer::isVisible() const {
4035 if (!hasSomethingToDraw()) {
4036 return false;
4037 }
4038
4039 if (isHiddenByPolicy()) {
4040 return false;
4041 }
4042
4043 return getAlpha() > 0.0f || hasBlur();
4044}
4045
Leon Scroggins III5b581492023-10-31 14:29:41 -04004046void Layer::onCompositionPresented(const DisplayDevice* display,
4047 const std::shared_ptr<FenceTime>& glDoneFence,
4048 const std::shared_ptr<FenceTime>& presentFence,
4049 const CompositorTiming& compositorTiming) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004050 // mFrameLatencyNeeded is true when a new frame was latched for the
4051 // composition.
4052 if (!mBufferInfo.mFrameLatencyNeeded) return;
4053
4054 for (const auto& handle : mDrawingState.callbackHandles) {
4055 handle->gpuCompositionDoneFence = glDoneFence;
4056 handle->compositorTiming = compositorTiming;
4057 }
4058
4059 // Update mFrameTracker.
4060 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
4061 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
4062
4063 const int32_t layerId = getSequence();
4064 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
4065
4066 const auto outputLayer = findOutputLayerForDisplay(display);
4067 if (outputLayer && outputLayer->requiresClientComposition()) {
4068 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
4069 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4070 clientCompositionTimestamp,
4071 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
4072 // Update the SurfaceFrames in the drawing state
4073 if (mDrawingState.bufferSurfaceFrameTX) {
4074 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
4075 }
4076 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
4077 surfaceFrame->setGpuComposition();
4078 }
4079 }
4080
4081 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
4082 if (frameReadyFence->isValid()) {
4083 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
4084 } else {
4085 // There was no fence for this frame, so assume that it was ready
4086 // to be presented at the desired present time.
4087 mFrameTracker.setFrameReadyTime(desiredPresentTime);
4088 }
4089
4090 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08004091 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004092 const std::optional<Fps> renderRate =
4093 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
4094
Alec Mouri7c1d8b52023-08-29 20:14:46 +00004095 const auto vote = frameRateToSetFrameRateVotePayload(getFrameRateForLayerTree());
Patrick Williamsbb25f802022-08-30 23:02:34 +00004096 const auto gameMode = getGameMode();
4097
4098 if (presentFence->isValid()) {
4099 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
4100 refreshRate, renderRate, vote, gameMode);
4101 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4102 presentFence,
4103 FrameTracer::FrameEvent::PRESENT_FENCE);
4104 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
4105 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
4106 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04004107 // The HWC doesn't support present fences, so use the present timestamp instead.
4108 const nsecs_t presentTimestamp =
4109 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
4110
4111 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
4112 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
4113 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
4114
Patrick Williamsbb25f802022-08-30 23:02:34 +00004115 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
4116 refreshRate, renderRate, vote, gameMode);
4117 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
4118 mCurrentFrameNumber, actualPresentTime,
4119 FrameTracer::FrameEvent::PRESENT_FENCE);
4120 mFrameTracker.setActualPresentTime(actualPresentTime);
4121 }
4122 }
4123
4124 mFrameTracker.advanceFrame();
4125 mBufferInfo.mFrameLatencyNeeded = false;
4126}
4127
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004128bool Layer::willReleaseBufferOnLatch() const {
4129 return !mDrawingState.buffer && mBufferInfo.mBuffer;
4130}
4131
Patrick Williamsbb25f802022-08-30 23:02:34 +00004132bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00004133 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
4134 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
4135}
4136
4137bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004138 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
4139 getDrawingState().frameNumber);
4140
4141 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
4142
4143 if (refreshRequired) {
4144 return refreshRequired;
4145 }
4146
4147 // If the head buffer's acquire fence hasn't signaled yet, return and
4148 // try again later
4149 if (!fenceHasSignaled()) {
4150 ATRACE_NAME("!fenceHasSignaled()");
4151 mFlinger->onLayerUpdate();
4152 return false;
4153 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00004154 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004155
4156 // Capture the old state of the layer for comparisons later
4157 BufferInfo oldBufferInfo = mBufferInfo;
4158 const bool oldOpacity = isOpaque(mDrawingState);
4159 mPreviousFrameNumber = mCurrentFrameNumber;
4160 mCurrentFrameNumber = mDrawingState.frameNumber;
4161 gatherBufferInfo();
4162
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004163 if (mBufferInfo.mBuffer) {
4164 // We latched a buffer that will be presented soon. Clear the previously presented layer
4165 // stack list.
4166 mPreviouslyPresentedLayerStacks.clear();
4167 }
4168
4169 if (mDrawingState.buffer == nullptr) {
4170 const bool bufferReleased = oldBufferInfo.mBuffer != nullptr;
4171 recomputeVisibleRegions = bufferReleased;
4172 return bufferReleased;
4173 }
4174
Patrick Williamsbb25f802022-08-30 23:02:34 +00004175 if (oldBufferInfo.mBuffer == nullptr) {
4176 // the first time we receive a buffer, we need to trigger a
4177 // geometry invalidation.
4178 recomputeVisibleRegions = true;
4179 }
4180
4181 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
4182 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
4183 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
4184 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
4185 recomputeVisibleRegions = true;
4186 }
4187
4188 if (oldBufferInfo.mBuffer != nullptr) {
4189 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
4190 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
4191 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
4192 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
4193 recomputeVisibleRegions = true;
4194 }
4195 }
4196
4197 if (oldOpacity != isOpaque(mDrawingState)) {
4198 recomputeVisibleRegions = true;
4199 }
4200
4201 return true;
4202}
4203
4204bool Layer::hasReadyFrame() const {
4205 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4206}
4207
4208bool Layer::isProtected() const {
4209 return (mBufferInfo.mBuffer != nullptr) &&
4210 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4211}
4212
Patrick Williamsbb25f802022-08-30 23:02:34 +00004213void Layer::latchAndReleaseBuffer() {
4214 if (hasReadyFrame()) {
4215 bool ignored = false;
4216 latchBuffer(ignored, systemTime());
4217 }
4218 releasePendingBuffer(systemTime());
4219}
4220
4221PixelFormat Layer::getPixelFormat() const {
4222 return mBufferInfo.mPixelFormat;
4223}
4224
4225bool Layer::getTransformToDisplayInverse() const {
4226 return mBufferInfo.mTransformToDisplayInverse;
4227}
4228
4229Rect Layer::getBufferCrop() const {
4230 // this is the crop rectangle that applies to the buffer
4231 // itself (as opposed to the window)
4232 if (!mBufferInfo.mCrop.isEmpty()) {
4233 // if the buffer crop is defined, we use that
4234 return mBufferInfo.mCrop;
4235 } else if (mBufferInfo.mBuffer != nullptr) {
4236 // otherwise we use the whole buffer
4237 return mBufferInfo.mBuffer->getBounds();
4238 } else {
4239 // if we don't have a buffer yet, we use an empty/invalid crop
4240 return Rect();
4241 }
4242}
4243
4244uint32_t Layer::getBufferTransform() const {
4245 return mBufferInfo.mTransform;
4246}
4247
4248ui::Dataspace Layer::getDataSpace() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004249 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4250}
4251
Alec Mouri89f5d4e2023-10-20 17:12:49 +00004252bool Layer::isFrontBuffered() const {
4253 if (mBufferInfo.mBuffer == nullptr) {
4254 return false;
4255 }
4256
4257 return mBufferInfo.mBuffer->getUsage() & AHARDWAREBUFFER_USAGE_FRONT_BUFFER;
4258}
4259
Patrick Williamsbb25f802022-08-30 23:02:34 +00004260ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4261 ui::Dataspace updatedDataspace = dataspace;
4262 // translate legacy dataspaces to modern dataspaces
4263 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00004264 // Treat unknown dataspaces as V0_sRGB
4265 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00004266 case ui::Dataspace::SRGB:
4267 updatedDataspace = ui::Dataspace::V0_SRGB;
4268 break;
4269 case ui::Dataspace::SRGB_LINEAR:
4270 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4271 break;
4272 case ui::Dataspace::JFIF:
4273 updatedDataspace = ui::Dataspace::V0_JFIF;
4274 break;
4275 case ui::Dataspace::BT601_625:
4276 updatedDataspace = ui::Dataspace::V0_BT601_625;
4277 break;
4278 case ui::Dataspace::BT601_525:
4279 updatedDataspace = ui::Dataspace::V0_BT601_525;
4280 break;
4281 case ui::Dataspace::BT709:
4282 updatedDataspace = ui::Dataspace::V0_BT709;
4283 break;
4284 default:
4285 break;
4286 }
4287
4288 return updatedDataspace;
4289}
4290
4291sp<GraphicBuffer> Layer::getBuffer() const {
4292 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4293}
4294
Vishnu Nairb76d99a2023-03-19 18:22:31 -07004295void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4296 mTransformHintLegacy = getFixedTransformHint();
4297 if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4298 mTransformHintLegacy = displayTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004299 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004300 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004301}
4302
4303const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4304 return mBufferInfo.mBuffer;
4305}
4306
4307bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004308 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004309 return false;
4310 }
4311
4312 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004313 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004314 mDrawingState.modified = true;
4315 setTransactionFlags(eTransactionNeeded);
4316 return true;
4317}
4318
4319bool Layer::fillsColor() const {
4320 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4321 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4322}
4323
4324bool Layer::hasBlur() const {
4325 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4326}
4327
Vishnu Nairba354102022-08-01 00:14:18 +00004328void Layer::updateSnapshot(bool updateGeometry) {
4329 if (!getCompositionEngineLayerFE()) {
4330 return;
4331 }
4332
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004333 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004334 if (updateGeometry) {
4335 prepareBasicGeometryCompositionState();
4336 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004337 snapshot->roundedCorner = getRoundedCornerState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004338 snapshot->transformedBounds = mScreenBounds;
4339 if (mEffectiveShadowRadius > 0.f) {
4340 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4341
4342 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4343 // it if transparent regions are present. This may not be necessary since shadows are
4344 // typically cast by layers without transparent regions.
4345 snapshot->shadowSettings.boundaries = mBounds;
4346
4347 const float casterAlpha = snapshot->alpha;
4348 const bool casterIsOpaque =
4349 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4350
4351 // If the casting layer is translucent, we need to fill in the shadow underneath the
4352 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4353 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4354 snapshot->shadowSettings.ambientColor *= casterAlpha;
4355 snapshot->shadowSettings.spotColor *= casterAlpha;
4356 }
4357 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004358 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004359 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004360 snapshot->layerOpaqueFlagSet =
4361 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004362 sp<Layer> p = mDrawingParent.promote();
4363 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004364 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004365 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004366 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004367 }
4368 snapshot->bufferSize = getBufferSize(mDrawingState);
4369 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004370 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004371 preparePerFrameCompositionState();
4372}
4373
Vishnu Naire14c6b32022-08-06 04:20:15 +00004374void Layer::updateChildrenSnapshots(bool updateGeometry) {
4375 for (const sp<Layer>& child : mDrawingChildren) {
4376 child->updateSnapshot(updateGeometry);
4377 child->updateChildrenSnapshots(updateGeometry);
4378 }
4379}
4380
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004381void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4382 mSnapshot->layerMetadata = parentMetadata;
4383 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4384 for (const sp<Layer>& child : mDrawingChildren) {
4385 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4386 }
4387}
4388
4389void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4390 std::unordered_set<Layer*>& visited) {
4391 if (visited.find(this) != visited.end()) {
4392 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4393 return;
4394 }
4395 visited.insert(this);
4396
4397 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4398
4399 if (mDrawingState.zOrderRelatives.empty()) {
4400 return;
4401 }
4402 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4403 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4404 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4405 sp<Layer> relative = weakRelative.promote();
4406 if (!relative) {
4407 continue;
4408 }
4409 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4410 }
4411}
4412
Chavi Weingarten328a8312023-01-26 21:17:52 +00004413bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004414 TrustedPresentationListener const& listener) {
4415 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4416 mTrustedPresentationListener = listener;
4417 mTrustedPresentationThresholds = thresholds;
4418 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4419 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4420 mFlinger->mNumTrustedPresentationListeners++;
4421 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4422 mFlinger->mNumTrustedPresentationListeners--;
4423 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004424
4425 // Reset trusted presentation states to ensure we start the time again.
4426 mEnteredTrustedPresentationStateTime = -1;
4427 mLastReportedTrustedPresentationState = false;
4428 mLastComputedTrustedPresentationState = false;
4429
4430 // If there's a new trusted presentation listener, the code needs to go through the composite
4431 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4432 // we're already in the requested state.
4433 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004434}
4435
Vishnu Naira156f482023-02-22 00:23:38 +00004436void Layer::updateLastLatchTime(nsecs_t latchTime) {
4437 mLastLatchTime = latchTime;
4438}
4439
Arthur Hung69f95222023-10-04 07:39:02 +00004440void Layer::setIsSmallDirty(const Region& damageRegion,
4441 const ui::Transform& layerToDisplayTransform) {
4442 mSmallDirty = false;
Jerry Chang36678002023-11-29 16:56:17 +00004443 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00004444 return;
4445 }
4446
4447 if (mWindowType != WindowInfo::Type::APPLICATION &&
4448 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
4449 return;
4450 }
Arthur Hung69f95222023-10-04 07:39:02 +00004451
4452 Rect bounds = damageRegion.getBounds();
Arthur Hungc70bee22023-06-02 01:35:52 +00004453 if (!bounds.isValid()) {
4454 return;
4455 }
4456
Arthur Hung69f95222023-10-04 07:39:02 +00004457 // Transform to screen space.
4458 bounds = layerToDisplayTransform.transform(bounds);
4459
Arthur Hungc70bee22023-06-02 01:35:52 +00004460 // If the damage region is a small dirty, this could give the hint for the layer history that
4461 // it could suppress the heuristic rate when calculating.
Tony Huangf3621102023-09-04 17:14:22 +08004462 mSmallDirty = mFlinger->mScheduler->isSmallDirtyArea(mOwnerAppId,
Tony Huang9ac5e6e2023-08-24 09:01:44 +00004463 bounds.getWidth() * bounds.getHeight());
Arthur Hungc70bee22023-06-02 01:35:52 +00004464}
4465
Arthur Hung69f95222023-10-04 07:39:02 +00004466void Layer::setIsSmallDirty(frontend::LayerSnapshot* snapshot) {
4467 setIsSmallDirty(snapshot->surfaceDamage, snapshot->localTransform);
4468 snapshot->isSmallDirty = mSmallDirty;
4469}
4470
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004471} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004472
4473#if defined(__gl_h_)
4474#error "don't include gl/gl.h in this file"
4475#endif
4476
4477#if defined(__gl2_h_)
4478#error "don't include gl2/gl2.h in this file"
4479#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004480
4481// TODO(b/129481165): remove the #pragma below and fix conversion issues
4482#pragma clang diagnostic pop // ignored "-Wconversion"