blob: e758741afb272a4c0e21f5bb8f717d4e5c549837 [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
Melody Hsue4ef87f2024-03-26 23:54:45 +000018
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080019#pragma clang diagnostic push
20#pragma clang diagnostic ignored "-Wconversion"
21
Dan Stoza9e56aa02015-11-02 13:00:03 -080022//#define LOG_NDEBUG 0
23#undef LOG_TAG
24#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080025#define ATRACE_TAG ATRACE_TAG_GRAPHICS
26
[1;3C2b9fc252021-02-04 16:16:50 -080027#include <android-base/properties.h>
Yiwei Zhang5434a782018-12-05 18:06:32 -080028#include <android-base/stringprintf.h>
Vishnu Nair0f085c62019-08-30 08:49:12 -070029#include <binder/IPCThreadState.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000030#include <compositionengine/CompositionEngine.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080031#include <compositionengine/Display.h>
Lloyd Piquea83776c2019-01-29 18:42:32 -080032#include <compositionengine/LayerFECompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080033#include <compositionengine/OutputLayer.h>
34#include <compositionengine/impl/OutputLayerCompositionState.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070035#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070036#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070037#include <cutils/properties.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070038#include <ftl/enum.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080039#include <ftl/fake_guard.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080040#include <gui/BufferItem.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080041#include <gui/Surface.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000042#include <gui/TraceUtils.h>
Alec Mourie60041e2019-06-14 18:59:51 -070043#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070044#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080045#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070046#include <stdint.h>
47#include <stdlib.h>
48#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000049#include <system/graphics-base-v1.0.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080050#include <ui/DebugUtils.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000051#include <ui/FloatRect.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080052#include <ui/GraphicBuffer.h>
Sally Qif6918d42023-08-07 15:28:30 -070053#include <ui/HdrRenderTypeUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080054#include <ui/PixelFormat.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000055#include <ui/Rect.h>
56#include <ui/Transform.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#include <utils/Errors.h>
58#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080059#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080061#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Alec Mourie60041e2019-06-14 18:59:51 -070063#include <algorithm>
64#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070065#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070066#include <sstream>
67
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070068#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080069#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070070#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070071#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +000072#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000073#include "FrontEnd/LayerHandle.h"
Melody Hsue4ef87f2024-03-26 23:54:45 +000074#include "Layer.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080075#include "LayerProtoHelper.h"
Josh Gao194ff392022-09-08 16:19:29 -070076#include "MutexUtils.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080078#include "TimeStats/TimeStats.h"
Melody Hsue4ef87f2024-03-26 23:54:45 +000079#include "TransactionCallbackInvoker.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070080#include "TunnelModeEnabledReporter.h"
Alec Mouri9892aac2023-12-11 21:16:59 +000081#include "Utils/FenceUtils.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070082
David Sodman41fdfc92017-11-06 16:09:56 -080083#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000084#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086namespace android {
Alec Mouri9892aac2023-12-11 21:16:59 +000087using namespace std::chrono_literals;
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010088namespace {
89constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000090
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000091const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000092
Linnan Li13bf76a2024-05-05 19:18:02 +080093ui::LogicalDisplayId toLogicalDisplayId(const ui::LayerStack& layerStack) {
94 return ui::LogicalDisplayId{static_cast<int32_t>(layerStack.id)};
95}
96
Patrick Williamsbb25f802022-08-30 23:02:34 +000097bool assignTransform(ui::Transform* dst, ui::Transform& from) {
98 if (*dst == from) {
99 return false;
100 }
101 *dst = from;
102 return true;
103}
104
105TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
106 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
107 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
108 const auto frameRateCompatibility = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700109 switch (frameRate.vote.type) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000110 case Layer::FrameRateCompatibility::Default:
111 return FrameRateCompatibility::Default;
112 case Layer::FrameRateCompatibility::ExactOrMultiple:
113 return FrameRateCompatibility::ExactOrMultiple;
114 default:
115 return FrameRateCompatibility::Undefined;
116 }
117 }();
118
119 const auto seamlessness = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700120 switch (frameRate.vote.seamlessness) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000121 case scheduler::Seamlessness::OnlySeamless:
122 return Seamlessness::ShouldBeSeamless;
123 case scheduler::Seamlessness::SeamedAndSeamless:
124 return Seamlessness::NotRequired;
125 default:
126 return Seamlessness::Undefined;
127 }
128 }();
129
Rachel Leece6e0042023-06-27 11:22:54 -0700130 return TimeStats::SetFrameRateVote{.frameRate = frameRate.vote.rate.getValue(),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000131 .frameRateCompatibility = frameRateCompatibility,
132 .seamlessness = seamlessness};
133}
134
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100135} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800136
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700137using namespace ftl::flag_operators;
138
Yiwei Zhang5434a782018-12-05 18:06:32 -0800139using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000140using frontend::LayerSnapshot;
141using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800142using gui::GameMode;
143using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500144using gui::WindowInfo;
Vishnu Nair494a2e42023-11-10 17:21:19 -0800145using ui::Size;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800146
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700147using PresentState = frametimeline::SurfaceFrame::PresentState;
148
Kean Mariotti4ba343c2023-04-19 13:31:02 +0000149Layer::Layer(const surfaceflinger::LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000150 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700151 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000152 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700153 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800154 mWindowType(static_cast<WindowInfo::Type>(
155 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000156 mLayerCreationFlags(args.flags),
Lloyd Pique70ddc672024-04-30 18:20:40 -0700157 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName, this)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000158 ALOGV("Creating Layer %s", getDebugName());
159
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700160 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700161 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
162 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
163 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700164 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
165 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700166 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700167 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700168 mDrawingState.z = 0;
169 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700170 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700171 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700172 mDrawingState.transform.set(0, 0);
173 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +0000174 mDrawingState.previousFrameNumber = 0;
Vishnu Nair63221212023-04-06 15:17:37 -0700175 mDrawingState.barrierFrameNumber = 0;
176 mDrawingState.producerId = 0;
177 mDrawingState.barrierProducerId = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700178 mDrawingState.bufferTransform = 0;
179 mDrawingState.transformToDisplayInverse = false;
Robert Carr6a160312021-05-17 12:08:20 -0700180 mDrawingState.acquireFence = sp<Fence>::make(-1);
181 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
Alec Mouri74c7ae12023-03-26 02:57:47 +0000182 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Robert Carr6a160312021-05-17 12:08:20 -0700183 mDrawingState.hdrMetadata.validTypes = 0;
184 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
185 mDrawingState.cornerRadius = 0.0f;
186 mDrawingState.backgroundBlurRadius = 0;
187 mDrawingState.api = -1;
188 mDrawingState.hasColorTransform = false;
189 mDrawingState.colorSpaceAgnostic = false;
190 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
191 mDrawingState.metadata = args.metadata;
192 mDrawingState.shadowRadius = 0.f;
193 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
194 mDrawingState.frameTimelineInfo = {};
195 mDrawingState.postTime = -1;
196 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000197 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700198 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700199 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000200 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Rachel Lee70f7b692023-11-22 11:24:02 -0800201 mDrawingState.frameRateSelectionStrategy = FrameRateSelectionStrategy::Propagate;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700202
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700203 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
204 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700205 mDrawingState.color.r = -1.0_hf;
206 mDrawingState.color.g = -1.0_hf;
207 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700208 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700209
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500210 mFrameTracker.setDisplayRefreshPeriod(
211 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700212
Vishnu Naircb8be502022-10-12 19:03:23 +0000213 mOwnerUid = args.ownerUid;
214 mOwnerPid = args.ownerPid;
Tony Huangf3621102023-09-04 17:14:22 +0800215 mOwnerAppId = mOwnerUid % PER_USER_RANGE;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000216
217 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
218 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
219 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000220
221 mSnapshot->sequence = sequence;
222 mSnapshot->name = getDebugName();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000223 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000224 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800225}
226
227void Layer::onFirstRef() {
228 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700229}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700230
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700231Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000232 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
233 "Layer destructor called off the main thread.");
234
Patrick Williamsbb25f802022-08-30 23:02:34 +0000235 // The original layer and the clone layer share the same texture and buffer. Therefore, only
236 // one of the layers, in this case the original layer, needs to handle the deletion. The
237 // original layer and the clone should be removed at the same time so there shouldn't be any
238 // issue with the clone layer trying to use the texture.
239 if (mBufferInfo.mBuffer != nullptr) {
240 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
241 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800242 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000243 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000244 const int32_t layerId = getSequence();
245 mFlinger->mTimeStats->onDestroy(layerId);
246 mFlinger->mFrameTracer->onDestroy(layerId);
247
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000248 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700249 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700250
251 if (mDrawingState.sidebandStream != nullptr) {
252 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
253 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700254 if (mHadClonedChild) {
Vishnu Nair3be61902023-04-26 19:47:29 -0700255 auto& roots = mFlinger->mLayerMirrorRoots;
256 roots.erase(std::remove(roots.begin(), roots.end(), this), roots.end());
Robert Carr6a0382d2021-07-01 15:57:17 -0700257 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000258 if (hasTrustedPresentationListener()) {
259 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000260 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000261 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700262}
263
Mathias Agopian13127d82013-03-05 17:47:11 -0800264// ---------------------------------------------------------------------------
265// callbacks
266// ---------------------------------------------------------------------------
267
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700268void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700269 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700270 return;
271 }
Robert Carr2e102c92018-10-23 12:11:15 -0700272
Robert Carr6a160312021-05-17 12:08:20 -0700273 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700274 if (strongRelative == nullptr) {
275 setZOrderRelativeOf(nullptr);
276 return;
277 }
278
279 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700280 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700281 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800282 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700283 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700284}
285
286void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700287 if (!mRemovedFromDrawingState) {
288 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700289 mFlinger->mScheduler->deregisterLayer(this);
290 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000291 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000292
Ady Abrahamd11bade2022-08-01 16:18:03 -0700293 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700294}
Chia-I Wu38512252017-05-17 14:36:16 -0700295
chaviw68d4dab2020-06-08 15:07:32 -0700296sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000297 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700298 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700299 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700300 }
301 return parent->getRootLayer();
302}
303
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700304void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700305 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
306 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700307 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700308
Josh Gao194ff392022-09-08 16:19:29 -0700309 REQUIRE_MUTEX(mFlinger->mStateLock);
310 traverse(LayerVector::StateSet::Current,
311 [&](Layer* layer) REQUIRES(layer->mFlinger->mStateLock) {
312 layer->removeFromCurrentState();
313 layer->removeRelativeZ(layersInTree);
314 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700315}
316
chaviw61626f22018-11-15 16:26:27 -0800317void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700318 if (mRemovedFromDrawingState) {
319 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700320 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700321 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700322 }
chaviw61626f22018-11-15 16:26:27 -0800323
324 for (const auto& child : mCurrentChildren) {
325 child->addToCurrentState();
326 }
327}
328
Mathias Agopian13127d82013-03-05 17:47:11 -0800329// ---------------------------------------------------------------------------
330// set-up
331// ---------------------------------------------------------------------------
332
chaviw13fdc492017-06-27 12:40:18 -0700333bool Layer::getPremultipledAlpha() const {
334 return mPremultipliedAlpha;
335}
336
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700337sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800338 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700339 if (mGetHandleCalled) {
340 ALOGE("Get handle called twice" );
341 return nullptr;
342 }
343 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700344 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000345 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800346}
347
348// ---------------------------------------------------------------------------
349// h/w composer set-up
350// ---------------------------------------------------------------------------
351
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700352static Rect reduce(const Rect& win, const Region& exclude) {
353 if (CC_LIKELY(exclude.isEmpty())) {
354 return win;
355 }
356 if (exclude.isRect()) {
357 return win.reduce(exclude.getBounds());
358 }
359 return Region(win).subtract(exclude).getBounds();
360}
361
Dan Stoza80d61162017-12-20 15:57:52 -0800362static FloatRect reduce(const FloatRect& win, const Region& exclude) {
363 if (CC_LIKELY(exclude.isEmpty())) {
364 return win;
365 }
366 // Convert through Rect (by rounding) for lack of FloatRegion
367 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
368}
369
Vishnu Nair4351ad52019-02-11 14:13:02 -0800370Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800371 if (!reduceTransparentRegion) {
372 return Rect{mScreenBounds};
373 }
374
375 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800376 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800377 // Transform to screen space.
378 bounds = t.transform(bounds);
379 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700380}
381
Vishnu Nair4351ad52019-02-11 14:13:02 -0800382FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000383 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800384 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700385}
386
Vishnu Nairf0c28512019-02-08 12:40:28 -0800387FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
388 // Subtract the transparent region and snap to the bounds.
389 return reduce(mBounds, activeTransparentRegion);
390}
391
Chavi Weingarten076acac2023-01-19 17:20:43 +0000392// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000393void Layer::updateTrustedPresentationState(const DisplayDevice* display,
394 const frontend::LayerSnapshot* snapshot,
395 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000396 if (!hasTrustedPresentationListener()) {
397 return;
398 }
399 const bool lastState = mLastComputedTrustedPresentationState;
400 mLastComputedTrustedPresentationState = false;
401
402 if (!leaveState) {
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000403 const auto outputLayer = findOutputLayerForDisplay(display, snapshot->path);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000404 if (outputLayer != nullptr) {
405 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
406 Region coveredRegion =
407 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
408 mLastComputedTrustedPresentationState =
409 computeTrustedPresentationState(snapshot->geomLayerBounds,
410 snapshot->sourceBounds(), coveredRegion,
411 snapshot->transformedBounds,
412 snapshot->alpha,
413 snapshot->geomLayerTransform,
414 mTrustedPresentationThresholds);
415 } else {
416 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
417 "TrustedPresentationState",
418 getDebugName());
419 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000420 }
421 }
422 const bool newState = mLastComputedTrustedPresentationState;
423 if (lastState && !newState) {
424 // We were in the trusted presentation state, but now we left it,
425 // emit the callback if needed
426 if (mLastReportedTrustedPresentationState) {
427 mLastReportedTrustedPresentationState = false;
428 mTrustedPresentationListener.invoke(false);
429 }
430 // Reset the timer
431 mEnteredTrustedPresentationStateTime = -1;
432 } else if (!lastState && newState) {
433 // We were not in the trusted presentation state, but we entered it, begin the timer
434 // and make sure this gets called at least once more!
435 mEnteredTrustedPresentationStateTime = time_in_ms;
436 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
437 }
438
439 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
440 if (!mLastReportedTrustedPresentationState && newState &&
441 (time_in_ms - mEnteredTrustedPresentationStateTime >
442 mTrustedPresentationThresholds.stabilityRequirementMs)) {
443 mLastReportedTrustedPresentationState = true;
444 mTrustedPresentationListener.invoke(true);
445 }
446}
447
448/**
449 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
450 * of how the parameters and thresholds are interpreted. The general spirit is
451 * to produce an upper bound on the amount of the buffer which was presented.
452 */
453bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
454 const Region& coveredRegion,
455 const FloatRect& screenBounds, float alpha,
456 const ui::Transform& effectiveTransform,
457 const TrustedPresentationThresholds& thresholds) {
458 if (alpha < thresholds.minAlpha) {
459 return false;
460 }
461 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
462 return false;
463 }
464 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
465 return false;
466 }
467
468 const float sx = effectiveTransform.dsdx();
469 const float sy = effectiveTransform.dsdy();
470 float fractionRendered = std::min(sx * sy, 1.0f);
471
472 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
473 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
474 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
475
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000476 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
477 // Compute the size of all the rects since they may be disconnected.
478 float coveredSize = 0;
479 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
480 float size = rect->width() * rect->height();
481 coveredSize += size;
482 }
483
484 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000485
486 if (fractionRendered < thresholds.minFractionRendered) {
487 return false;
488 }
489
490 return true;
491}
492
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700493void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
494 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800495 const State& s(getDrawingState());
496
497 // Calculate effective layer transform
498 mEffectiveTransform = parentTransform * getActiveTransform(s);
499
Garfield Tan2c1782c2022-02-16 15:25:05 -0800500 if (CC_UNLIKELY(!isTransformValid())) {
501 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
502 getDebugName());
503 return;
504 }
505
Vishnu Nair4351ad52019-02-11 14:13:02 -0800506 // Transform parent bounds to layer space
507 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
508
Vishnu Nairc652ff82019-03-15 12:48:54 -0700509 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800510 mSourceBounds = computeSourceBounds(parentBounds);
511
512 // Calculate bounds by croping diplay frame with layer crop and parent bounds
513 FloatRect bounds = mSourceBounds;
514 const Rect layerCrop = getCrop(s);
515 if (!layerCrop.isEmpty()) {
516 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
517 }
518 bounds = bounds.intersect(parentBounds);
519
520 mBounds = bounds;
521 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700522
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700523 // Use the layer's own shadow radius if set. Otherwise get the radius from
524 // parent.
525 if (s.shadowRadius > 0.f) {
526 mEffectiveShadowRadius = s.shadowRadius;
527 } else {
528 mEffectiveShadowRadius = parentShadowRadius;
529 }
530
531 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
532 // don't pass it to its children.
533 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
534
Vishnu Nair4351ad52019-02-11 14:13:02 -0800535 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700536 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800537 }
Vishnu Nairba354102022-08-01 00:14:18 +0000538
539 if (mPotentialCursor) {
540 prepareCursorCompositionState();
541 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800542}
543
Vishnu Nair60356342018-11-13 13:00:45 -0800544Rect Layer::getCroppedBufferSize(const State& s) const {
545 Rect size = getBufferSize(s);
546 Rect crop = getCrop(s);
547 if (!crop.isEmpty() && size.isValid()) {
548 size.intersect(crop, &size);
549 } else if (!crop.isEmpty()) {
550 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700551 }
Vishnu Nair60356342018-11-13 13:00:45 -0800552 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800553}
554
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700555void Layer::setupRoundedCornersCropCoordinates(Rect win,
556 const FloatRect& roundedCornersCrop) const {
557 // Translate win by the rounded corners rect coordinates, to have all values in
558 // layer coordinate space.
559 win.left -= roundedCornersCrop.left;
560 win.right -= roundedCornersCrop.left;
561 win.top -= roundedCornersCrop.top;
562 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700563}
564
Lloyd Piquede196652020-01-22 17:29:58 -0800565void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800566 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800567 const auto alpha = static_cast<float>(getAlpha());
568 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700569 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800570
571 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
572 if (!opaque || alpha != 1.0f) {
573 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
574 : Hwc2::IComposerClient::BlendMode::COVERAGE;
575 }
576
Alec Mourif4af03e2023-02-11 00:25:24 +0000577 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000578 auto* snapshot = editLayerSnapshot();
579 snapshot->outputFilter = getOutputFilter();
580 snapshot->isVisible = isVisible();
581 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
Vishnu Naird9e4f462023-10-06 04:05:45 +0000582 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800583
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000584 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800585 contentDirty = false;
586
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000587 snapshot->geomLayerBounds = mBounds;
588 snapshot->geomLayerTransform = getTransform();
589 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
590 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000591 snapshot->localTransform = getActiveTransform(drawingState);
592 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000593 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
594 snapshot->alpha = alpha;
Vishnu Nairc6384702023-07-31 12:22:20 -0700595 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
596 snapshot->blurRegions = getBlurRegions();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000597 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800598}
599
Lloyd Piquede196652020-01-22 17:29:58 -0800600void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800601 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000602 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700603
Alec Mourif4af03e2023-02-11 00:25:24 +0000604 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000605 snapshot->geomBufferSize = getBufferSize(drawingState);
606 snapshot->geomContentCrop = getBufferCrop();
607 snapshot->geomCrop = getCrop(drawingState);
608 snapshot->geomBufferTransform = getBufferTransform();
609 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
610 snapshot->geomUsesSourceCrop = usesSourceCrop();
611 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800612
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000613 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800614 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
615 for (const auto& [key, mandatory] : supportedMetadata) {
616 const auto& genericLayerMetadataCompatibilityMap =
617 mFlinger->getGenericLayerMetadataKeyMap();
618 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
619 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
620 continue;
621 }
622 const uint32_t id = compatIter->second;
623
624 auto it = drawingState.metadata.mMap.find(id);
625 if (it == std::end(drawingState.metadata.mMap)) {
626 continue;
627 }
628
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000629 snapshot->metadata.emplace(key,
630 compositionengine::GenericLayerMetadataEntry{mandatory,
631 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800632 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800633}
David Sodmanba340492018-08-05 21:51:33 -0700634
Lloyd Piquede196652020-01-22 17:29:58 -0800635void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800636 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000637 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000638 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800639
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000640 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800641
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000642 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
643 snapshot->dataspace = getDataSpace();
644 snapshot->colorTransform = getColorTransform();
645 snapshot->colorTransformIsIdentity = !hasColorTransform();
646 snapshot->surfaceDamage = surfaceDamageRegion;
647 snapshot->hasProtectedContent = isProtected();
648 snapshot->dimmingEnabled = isDimmingEnabled();
Sally Qi963049b2023-03-23 14:06:21 -0700649 snapshot->currentHdrSdrRatio = getCurrentHdrSdrRatio();
650 snapshot->desiredHdrSdrRatio = getDesiredHdrSdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000651 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800652
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700653 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700654
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000655 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800656
657 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400658 // Rounded corners no longer force client composition, since we may use a
659 // hole punch so that the layer will appear to have rounded corners.
Alec Mouri994761f2023-08-04 21:50:55 +0000660 if (drawShadows() || snapshot->stretchEffect.hasEffect()) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000661 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800662 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700663 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairc6384702023-07-31 12:22:20 -0700664 snapshot->blurRegions = getBlurRegions();
665 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400666
667 // Layer framerate is used in caching decisions.
668 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
669 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000670 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000671
672 if (hasBufferOrSidebandStream()) {
673 preparePerFrameBufferCompositionState();
674 } else {
675 preparePerFrameEffectsCompositionState();
676 }
677}
678
679void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000680 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000681 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000682 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000683 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
684 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000685 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
686 return;
687 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000688 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000689 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800690 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
691 snapshot->compositionType =
692 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000693 } else {
694 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000695 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
696 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000697 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
698 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
699 }
700
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000701 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000702 snapshot->acquireFence = mBufferInfo.mFence;
703 snapshot->frameNumber = mBufferInfo.mFrameNumber;
704 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000705}
706
707void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000708 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000709 auto* snapshot = editLayerSnapshot();
710 snapshot->color = getColor();
711 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000712 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800713}
714
Lloyd Piquede196652020-01-22 17:29:58 -0800715void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800716 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000717 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000718 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800719
720 // Apply the layer's transform, followed by the display's global transform
721 // Here we're guaranteed that the layer's transform preserves rects
722 Rect win = getCroppedBufferSize(drawingState);
723 // Subtract the transparent region and snap to the bounds
724 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
725 Rect frame(getTransform().transform(bounds));
726
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000727 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800728}
729
Lloyd Piquea83776c2019-01-29 18:42:32 -0800730const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700731 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800732}
733
Mathias Agopian13127d82013-03-05 17:47:11 -0800734// ---------------------------------------------------------------------------
735// drawing...
736// ---------------------------------------------------------------------------
737
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500738aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
739 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700740 const auto outputLayer = findOutputLayerForDisplay(&display);
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000741 return getCompositionType(outputLayer);
742}
743
744aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
745 const compositionengine::OutputLayer* outputLayer) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -0800746 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500747 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800748 }
749 if (outputLayer->getState().hwc) {
750 return (*outputLayer->getState().hwc).hwcCompositionType;
751 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500752 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800753 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800754}
755
Mathias Agopian13127d82013-03-05 17:47:11 -0800756// ----------------------------------------------------------------------------
757// local state
758// ----------------------------------------------------------------------------
759
David Sodman41fdfc92017-11-06 16:09:56 -0800760bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800761 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700762 if (s.flags & layer_state_t::eLayerSecure) {
763 return true;
764 }
765
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000766 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700767 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700768}
769
Mathias Agopian13127d82013-03-05 17:47:11 -0800770// ----------------------------------------------------------------------------
771// transaction
772// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800773
Vishnu Naira156f482023-02-22 00:23:38 +0000774uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700775 ATRACE_CALL();
776
Robert Carr0758e5d2021-03-11 22:15:04 -0800777 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700778 mDrawingStateModified = mDrawingState.modified;
779 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700780
Alec Mourib416efd2018-09-06 21:01:59 +0000781 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700782
Robert Carr6a160312021-05-17 12:08:20 -0700783 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800784 // invalidate and recompute the visible regions if needed
785 flags |= Layer::eVisibleRegion;
786 }
787
Robert Carr6a160312021-05-17 12:08:20 -0700788 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800789 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000790 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800791 flags |= eVisibleRegion;
792 this->contentDirty = true;
793
794 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700795 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800796 }
797
Arthur Hung9ed43392022-05-27 06:31:57 +0000798 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
799 mFlinger->mUpdateInputInfo = true;
800 }
801
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700802 commitTransaction();
Robert Carra1257842020-01-31 13:48:28 -0800803
Mathias Agopian13127d82013-03-05 17:47:11 -0800804 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800805}
806
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700807void Layer::commitTransaction() {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000808 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
809 // bufferSurfaceFrameTX will be presented in latchBuffer.
810 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
811 if (surfaceFrame->getPresentState() != PresentState::Presented) {
812 // With applyPendingStates, we could end up having presented surfaceframes from previous
813 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800814 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000815 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
816 }
817 }
Robert Carr6a160312021-05-17 12:08:20 -0700818 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700819}
820
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700821uint32_t Layer::clearTransactionFlags(uint32_t mask) {
822 const auto flags = mTransactionFlags & mask;
823 mTransactionFlags &= ~mask;
824 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800825}
826
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700827void Layer::setTransactionFlags(uint32_t mask) {
828 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800829}
830
Robert Carr1f0a16a2016-10-24 16:27:39 -0700831bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
832 ssize_t idx = mCurrentChildren.indexOf(childLayer);
833 if (idx < 0) {
834 return false;
835 }
836 if (childLayer->setLayer(z)) {
837 mCurrentChildren.removeAt(idx);
838 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800839 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700840 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800841 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700842}
843
Robert Carr503c7042017-09-27 15:06:08 -0700844bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
845 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
846 ssize_t idx = mCurrentChildren.indexOf(childLayer);
847 if (idx < 0) {
848 return false;
849 }
850 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
851 mCurrentChildren.removeAt(idx);
852 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800853 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700854 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800855 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700856}
857
Robert Carrae060832016-11-28 10:51:00 -0800858bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700859 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
860 mDrawingState.sequence++;
861 mDrawingState.z = z;
862 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700863
Robert Carra70e91c2021-06-11 13:59:52 -0700864 mFlinger->mSomeChildrenChanged = true;
865
Robert Carrdb66e622017-04-10 16:55:57 -0700866 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700867 if (mDrawingState.zOrderRelativeOf != nullptr) {
868 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700869 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700870 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700871 }
chaviw606e5cf2019-03-01 10:12:10 -0800872 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700873 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800874 setTransactionFlags(eTransactionNeeded);
875 return true;
876}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700877
Robert Carrdb66e622017-04-10 16:55:57 -0700878void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700879 mDrawingState.zOrderRelatives.remove(relative);
880 mDrawingState.sequence++;
881 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700882 setTransactionFlags(eTransactionNeeded);
883}
884
885void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700886 mDrawingState.zOrderRelatives.add(relative);
887 mDrawingState.modified = true;
888 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700889 setTransactionFlags(eTransactionNeeded);
890}
891
chaviw606e5cf2019-03-01 10:12:10 -0800892void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700893 mDrawingState.zOrderRelativeOf = relativeOf;
894 mDrawingState.sequence++;
895 mDrawingState.modified = true;
896 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700897
chaviw606e5cf2019-03-01 10:12:10 -0800898 setTransactionFlags(eTransactionNeeded);
899}
900
Robert Carr503d2bd2017-12-04 15:49:47 -0800901bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000902 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700903 if (relative == nullptr) {
904 return false;
905 }
906
Robert Carr6a160312021-05-17 12:08:20 -0700907 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
908 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800909 return false;
910 }
911
Robert Carr88b85e12022-03-21 15:47:35 -0700912 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
913 (relative->mDrawingState.zOrderRelativeOf == this)) {
914 ALOGE("Detected relative layer loop between %s and %s",
915 mName.c_str(), relative->mName.c_str());
916 ALOGE("Ignoring new call to set relative layer");
917 return false;
918 }
919
Robert Carra70e91c2021-06-11 13:59:52 -0700920 mFlinger->mSomeChildrenChanged = true;
921
Robert Carr6a160312021-05-17 12:08:20 -0700922 mDrawingState.sequence++;
923 mDrawingState.modified = true;
924 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700925
Robert Carr6a160312021-05-17 12:08:20 -0700926 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700927 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700928 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700929 }
chaviw606e5cf2019-03-01 10:12:10 -0800930 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700931 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700932
933 setTransactionFlags(eTransactionNeeded);
934
935 return true;
936}
937
Winson Chunga30f7c92021-06-29 15:42:56 -0700938bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
939 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
940 mDrawingState.isTrustedOverlay = isTrustedOverlay;
941 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000942 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700943 setTransactionFlags(eTransactionNeeded);
944 return true;
945}
946
947bool Layer::isTrustedOverlay() const {
948 if (getDrawingState().isTrustedOverlay) {
949 return true;
950 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000951 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700952 return (p != nullptr) && p->isTrustedOverlay();
953}
954
Dan Stoza9e56aa02015-11-02 13:00:03 -0800955bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700956 if (mDrawingState.color.a == alpha) return false;
957 mDrawingState.sequence++;
958 mDrawingState.color.a = alpha;
959 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800960 setTransactionFlags(eTransactionNeeded);
961 return true;
962}
chaviw13fdc492017-06-27 12:40:18 -0700963
Valerie Haudd0b7572019-01-29 14:59:27 -0800964bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700965 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700966 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800967 }
Robert Carr6a160312021-05-17 12:08:20 -0700968 mDrawingState.sequence++;
969 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800970 setTransactionFlags(eTransactionNeeded);
971
Robert Carr6a160312021-05-17 12:08:20 -0700972 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -0800973 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -0800974 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700975 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -0700976 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Kean Mariotti4ba343c2023-04-19 13:31:02 +0000977 surfaceflinger::LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
978 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -0700979
Valerie Haudd0b7572019-01-29 14:59:27 -0800980 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -0700981 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -0800982 mFlinger->mLayersAdded = true;
983 // set up SF to handle added color layer
984 if (isRemovedFromCurrentState()) {
Josh Gao194ff392022-09-08 16:19:29 -0700985 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -0700986 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -0800987 }
988 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -0700989 } else if (mDrawingState.bgColorLayer && alpha == 0) {
Josh Gao194ff392022-09-08 16:19:29 -0700990 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -0700991 mDrawingState.bgColorLayer->reparent(nullptr);
992 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -0800993 return true;
994 }
995
Robert Carr6a160312021-05-17 12:08:20 -0700996 mDrawingState.bgColorLayer->setColor(color);
997 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
998 mDrawingState.bgColorLayer->setAlpha(alpha);
999 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001000
chaviw13fdc492017-06-27 12:40:18 -07001001 return true;
1002}
1003
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001004bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001005 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001006
Robert Carr6a160312021-05-17 12:08:20 -07001007 mDrawingState.sequence++;
1008 mDrawingState.cornerRadius = cornerRadius;
1009 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001010 setTransactionFlags(eTransactionNeeded);
1011 return true;
1012}
1013
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001014bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001015 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001016 // If we start or stop drawing blur then the layer's visibility state may change so increment
1017 // the magic sequence number.
1018 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1019 mDrawingState.sequence++;
1020 }
Robert Carr6a160312021-05-17 12:08:20 -07001021 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1022 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001023 setTransactionFlags(eTransactionNeeded);
1024 return true;
1025}
Marissa Wall61c58622018-07-18 10:12:20 -07001026
Mathias Agopian13127d82013-03-05 17:47:11 -08001027bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001028 mDrawingState.sequence++;
1029 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001030 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001031 setTransactionFlags(eTransactionNeeded);
1032 return true;
1033}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001034
Lucas Dupinc3800b82020-10-02 16:24:48 -07001035bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001036 // If we start or stop drawing blur then the layer's visibility state may change so increment
1037 // the magic sequence number.
1038 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1039 mDrawingState.sequence++;
1040 }
Robert Carr6a160312021-05-17 12:08:20 -07001041 mDrawingState.blurRegions = blurRegions;
1042 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001043 setTransactionFlags(eTransactionNeeded);
1044 return true;
1045}
1046
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001047bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001048 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1049 if (mDrawingState.flags == newFlags) return false;
1050 mDrawingState.sequence++;
1051 mDrawingState.flags = newFlags;
1052 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001053 setTransactionFlags(eTransactionNeeded);
1054 return true;
1055}
Robert Carr99e27f02016-06-16 15:18:02 -07001056
chaviw25714502021-02-11 10:01:08 -08001057bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001058 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001059 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001060 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001061
Robert Carr6a160312021-05-17 12:08:20 -07001062 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001063 setTransactionFlags(eTransactionNeeded);
1064 return true;
1065}
Robert Carr8d5227b2017-03-16 15:41:03 -07001066
Evan Roskyef876c92019-01-25 17:46:06 -08001067bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001068 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1069 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001070 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001071 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001072}
1073
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001074bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001075 if (mDrawingState.layerStack == layerStack) return false;
1076 mDrawingState.sequence++;
1077 mDrawingState.layerStack = layerStack;
1078 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001079 setTransactionFlags(eTransactionNeeded);
1080 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001081}
1082
Peiyong Linc502cb72019-03-01 15:00:23 -08001083bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001084 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001085 return false;
1086 }
Robert Carr6a160312021-05-17 12:08:20 -07001087 mDrawingState.sequence++;
1088 mDrawingState.colorSpaceAgnostic = agnostic;
1089 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001090 setTransactionFlags(eTransactionNeeded);
1091 return true;
1092}
1093
Sally Qi81d95e62022-03-21 19:41:33 -07001094bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1095 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1096
1097 mDrawingState.sequence++;
1098 mDrawingState.dimmingEnabled = dimmingEnabled;
1099 mDrawingState.modified = true;
1100 setTransactionFlags(eTransactionNeeded);
1101 return true;
1102}
1103
Ana Krulecc84d09b2019-11-02 23:10:29 +01001104bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001105 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1106 mDrawingState.frameRateSelectionPriority = priority;
1107 mDrawingState.sequence++;
1108 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001109 setTransactionFlags(eTransactionNeeded);
1110 return true;
1111}
1112
1113int32_t Layer::getFrameRateSelectionPriority() const {
1114 // Check if layer has priority set.
1115 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1116 return mDrawingState.frameRateSelectionPriority;
1117 }
1118 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001119 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001120 if (parent != nullptr) {
1121 return parent->getFrameRateSelectionPriority();
1122 }
1123
1124 return Layer::PRIORITY_UNSET;
1125}
1126
Andy Labrada096227e2022-06-15 16:58:11 +00001127bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1128 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1129 mDrawingState.defaultFrameRateCompatibility = compatibility;
1130 mDrawingState.modified = true;
Vishnu Nair80e8cfe2023-09-29 17:03:45 -07001131 mFlinger->mScheduler->setDefaultFrameRateCompatibility(sequence, compatibility);
Andy Labrada096227e2022-06-15 16:58:11 +00001132 setTransactionFlags(eTransactionNeeded);
1133 return true;
1134}
1135
Vishnu Nair3fbe3262023-09-29 17:07:00 -07001136scheduler::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
Andy Labrada096227e2022-06-15 16:58:11 +00001137 return mDrawingState.defaultFrameRateCompatibility;
1138}
1139
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001140bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1141 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1142};
1143
Vishnu Nair73908d12022-10-24 21:46:42 -07001144ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1145 bool useDrawing = state == LayerVector::StateSet::Drawing;
1146 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1147 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001148 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001149 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001150 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001151}
1152
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001153bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001154 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001155 return false;
1156 }
1157
Robert Carr6a160312021-05-17 12:08:20 -07001158 mDrawingState.sequence++;
1159 mDrawingState.shadowRadius = shadowRadius;
1160 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001161 setTransactionFlags(eTransactionNeeded);
1162 return true;
1163}
1164
Vishnu Nair6213bd92020-05-08 17:42:25 -07001165bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001166 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001167 return false;
1168 }
1169
Robert Carr6a160312021-05-17 12:08:20 -07001170 mDrawingState.sequence++;
1171 mDrawingState.fixedTransformHint = fixedTransformHint;
1172 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001173 setTransactionFlags(eTransactionNeeded);
1174 return true;
1175}
1176
John Reckcdb4ed72021-02-04 13:39:33 -05001177bool Layer::setStretchEffect(const StretchEffect& effect) {
1178 StretchEffect temp = effect;
1179 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001180 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001181 return false;
1182 }
Robert Carr6a160312021-05-17 12:08:20 -07001183 mDrawingState.sequence++;
1184 mDrawingState.stretchEffect = temp;
1185 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001186 setTransactionFlags(eTransactionNeeded);
1187 return true;
1188}
1189
John Reckc00c6692021-02-16 11:37:33 -05001190StretchEffect Layer::getStretchEffect() const {
1191 if (mDrawingState.stretchEffect.hasEffect()) {
1192 return mDrawingState.stretchEffect;
1193 }
1194
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001195 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001196 if (parent != nullptr) {
1197 auto effect = parent->getStretchEffect();
1198 if (effect.hasEffect()) {
1199 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1200 return effect;
1201 }
1202 }
1203 return StretchEffect{};
1204}
1205
Rachel Lee0faad6c2023-09-08 13:34:34 -07001206bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool overrideChildren,
1207 bool* transactionNeeded) {
1208 // Gets the frame rate to propagate to children.
Ady Abrahama850c182021-08-04 13:04:37 -07001209 const auto frameRate = [&] {
Rachel Lee0faad6c2023-09-08 13:34:34 -07001210 if (overrideChildren && parentFrameRate.isValid()) {
1211 return parentFrameRate;
1212 }
1213
Rachel Leece6e0042023-06-27 11:22:54 -07001214 if (mDrawingState.frameRate.isValid()) {
Ady Abrahama850c182021-08-04 13:04:37 -07001215 return mDrawingState.frameRate;
1216 }
1217
1218 return parentFrameRate;
1219 }();
1220
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001221 auto now = systemTime();
1222 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate, now);
Ady Abrahama850c182021-08-04 13:04:37 -07001223
Rachel Leea021bb02023-11-20 21:51:09 -08001224 // The frame rate is propagated to the children by default, but some properties may override it.
Ady Abrahama850c182021-08-04 13:04:37 -07001225 bool childrenHaveFrameRate = false;
Rachel Leea021bb02023-11-20 21:51:09 -08001226 const bool overrideChildrenFrameRate = overrideChildren || shouldOverrideChildrenFrameRate();
1227 const bool canPropagateFrameRate = shouldPropagateFrameRate() || overrideChildrenFrameRate;
Ady Abrahama850c182021-08-04 13:04:37 -07001228 for (const sp<Layer>& child : mCurrentChildren) {
1229 childrenHaveFrameRate |=
Rachel Leea021bb02023-11-20 21:51:09 -08001230 child->propagateFrameRateForLayerTree(canPropagateFrameRate ? frameRate
1231 : FrameRate(),
1232 overrideChildrenFrameRate, transactionNeeded);
Ady Abrahama850c182021-08-04 13:04:37 -07001233 }
1234
Rachel Leece6e0042023-06-27 11:22:54 -07001235 // If we don't have a valid frame rate specification, but the children do, we set this
Ady Abrahama850c182021-08-04 13:04:37 -07001236 // layer as NoVote to allow the children to control the refresh rate
Rachel Leece6e0042023-06-27 11:22:54 -07001237 if (!frameRate.isValid() && childrenHaveFrameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001238 *transactionNeeded |=
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001239 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote),
1240 now);
Ady Abrahama850c182021-08-04 13:04:37 -07001241 }
1242
Rachel Leece6e0042023-06-27 11:22:54 -07001243 // We return whether this layer or its children has a vote. We ignore ExactOrMultiple votes for
Ady Abrahama850c182021-08-04 13:04:37 -07001244 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001245 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001246 const auto layerVotedWithDefaultCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001247 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Default;
1248 const auto layerVotedWithNoVote = frameRate.vote.type == FrameRateCompatibility::NoVote;
1249 const auto layerVotedWithCategory = frameRate.category != FrameRateCategory::Default;
Ady Abrahama850c182021-08-04 13:04:37 -07001250 const auto layerVotedWithExactCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001251 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Exact;
1252 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote || layerVotedWithCategory ||
Ady Abrahama850c182021-08-04 13:04:37 -07001253 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1254}
1255
Ady Abraham60e42ea2020-03-09 19:17:31 -07001256void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001257 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001258 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001259 while (auto parent = layer->getParent()) {
1260 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001261 }
Ady Abrahama850c182021-08-04 13:04:37 -07001262 return layer;
1263 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001264
Ady Abraham60e42ea2020-03-09 19:17:31 -07001265 bool transactionNeeded = false;
Rachel Lee0faad6c2023-09-08 13:34:34 -07001266 root->propagateFrameRateForLayerTree({}, false, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001267
Ady Abrahama850c182021-08-04 13:04:37 -07001268 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001269 if (transactionNeeded) {
1270 mFlinger->setTransactionFlags(eTraversalNeeded);
1271 }
1272}
1273
Rachel Leece6e0042023-06-27 11:22:54 -07001274bool Layer::setFrameRate(FrameRate::FrameRateVote frameRateVote) {
1275 if (mDrawingState.frameRate.vote == frameRateVote) {
Steven Thomas3172e202020-01-06 19:25:30 -08001276 return false;
1277 }
1278
Robert Carr6a160312021-05-17 12:08:20 -07001279 mDrawingState.sequence++;
Rachel Leece6e0042023-06-27 11:22:54 -07001280 mDrawingState.frameRate.vote = frameRateVote;
1281 mDrawingState.modified = true;
1282
1283 updateTreeHasFrameRateVote();
1284
1285 setTransactionFlags(eTransactionNeeded);
1286 return true;
1287}
1288
Rachel Lee67afbea2023-09-28 15:35:07 -07001289bool Layer::setFrameRateCategory(FrameRateCategory category, bool smoothSwitchOnly) {
1290 if (mDrawingState.frameRate.category == category &&
1291 mDrawingState.frameRate.categorySmoothSwitchOnly == smoothSwitchOnly) {
Rachel Leece6e0042023-06-27 11:22:54 -07001292 return false;
1293 }
1294
1295 mDrawingState.sequence++;
1296 mDrawingState.frameRate.category = category;
Rachel Lee67afbea2023-09-28 15:35:07 -07001297 mDrawingState.frameRate.categorySmoothSwitchOnly = smoothSwitchOnly;
Robert Carr6a160312021-05-17 12:08:20 -07001298 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001299
1300 updateTreeHasFrameRateVote();
1301
Steven Thomas3172e202020-01-06 19:25:30 -08001302 setTransactionFlags(eTransactionNeeded);
1303 return true;
1304}
1305
Rachel Lee58cc90d2023-09-05 18:50:20 -07001306bool Layer::setFrameRateSelectionStrategy(FrameRateSelectionStrategy strategy) {
1307 if (mDrawingState.frameRateSelectionStrategy == strategy) return false;
1308 mDrawingState.frameRateSelectionStrategy = strategy;
1309 mDrawingState.sequence++;
1310 mDrawingState.modified = true;
Rachel Leed7479502023-09-25 17:02:35 -07001311
1312 updateTreeHasFrameRateVote();
Rachel Lee58cc90d2023-09-05 18:50:20 -07001313 setTransactionFlags(eTransactionNeeded);
1314 return true;
1315}
1316
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001317void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1318 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001319 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001320
1321 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1322 // there are two transactions with the same token, the first one without a buffer and the
1323 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1324 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001325 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1326 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001327 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001328 mDrawingState.bufferSurfaceFrameTX = it->second;
1329 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1330 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1331 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001332 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001333 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001334 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1335 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001336
1337 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001338}
1339
1340void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1341 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001342 mDrawingState.frameTimelineInfo = info;
1343 mDrawingState.postTime = postTime;
1344 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001345 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001346
Robert Carr6a160312021-05-17 12:08:20 -07001347 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001348 bufferSurfaceFrameTX != nullptr) {
1349 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1350 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1351 // being used for BufferSurfaceFrame, don't create a new one.
1352 return;
1353 }
1354 }
1355 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1356 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1357 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001358 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1359 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001360 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001361 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001362 } else {
1363 if (it->second->getPresentState() == PresentState::Presented) {
1364 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1365 // have been from previous vsync.
1366 it->second = createSurfaceFrameForTransaction(info, postTime);
1367 }
1368 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001369
1370 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001371}
1372
1373void Layer::addSurfaceFrameDroppedForBuffer(
Ady Abraham5a3e3562023-06-07 10:32:08 -07001374 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t dropTime) {
1375 surfaceFrame->setDropTime(dropTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001376 surfaceFrame->setPresentState(PresentState::Dropped);
1377 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1378}
1379
1380void Layer::addSurfaceFramePresentedForBuffer(
1381 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1382 nsecs_t currentLatchTime) {
1383 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1384 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1385 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001386 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001387}
1388
1389std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1390 const FrameTimelineInfo& info, nsecs_t postTime) {
1391 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001392 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1393 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001394 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001395 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001396 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001397 // For Transactions, the post time is considered to be both queue and acquire fence time.
1398 surfaceFrame->setActualQueueTime(postTime);
1399 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001400 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1401 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001402 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001403 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001404 return surfaceFrame;
1405}
1406
1407std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1408 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1409 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001410 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001411 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001412 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001413 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001414 // For buffers, acquire fence time will set during latch.
1415 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001416 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1417 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001418 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001419 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001420 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001421}
1422
Ady Abraham5a3e3562023-06-07 10:32:08 -07001423void Layer::setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
1424 std::string debugName) {
1425 if (info.skippedFrameVsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
1426 return;
1427 }
1428
1429 FrameTimelineInfo skippedFrameTimelineInfo = info;
1430 skippedFrameTimelineInfo.vsyncId = info.skippedFrameVsyncId;
1431
1432 auto surfaceFrame =
1433 mFlinger->mFrameTimeline->createSurfaceFrameForToken(skippedFrameTimelineInfo,
1434 mOwnerPid, mOwnerUid,
1435 getSequence(), mName, debugName,
1436 /*isBuffer*/ false, getGameMode());
1437 surfaceFrame->setActualStartTime(skippedFrameTimelineInfo.skippedFrameStartTimeNanos);
1438 // For Transactions, the post time is considered to be both queue and acquire fence time.
1439 surfaceFrame->setActualQueueTime(postTime);
1440 surfaceFrame->setAcquireFenceTime(postTime);
1441 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1442 if (fps) {
1443 surfaceFrame->setRenderRate(*fps);
1444 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001445 addSurfaceFrameDroppedForBuffer(surfaceFrame, postTime);
1446}
1447
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001448bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate, nsecs_t now) {
Ady Abrahama850c182021-08-04 13:04:37 -07001449 if (mDrawingState.frameRateForLayerTree == frameRate) {
1450 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001451 }
1452
Ady Abrahama850c182021-08-04 13:04:37 -07001453 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001454
Ady Abrahama850c182021-08-04 13:04:37 -07001455 // TODO(b/195668952): we probably don't need to dirty visible regions here
1456 // or even store frameRateForLayerTree in mDrawingState
1457 mDrawingState.sequence++;
1458 mDrawingState.modified = true;
1459 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001460
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001461 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001462 ->recordLayerHistory(sequence, getLayerProps(), now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001463 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1464 return true;
1465}
Ady Abrahama850c182021-08-04 13:04:37 -07001466
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001467bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps,
1468 nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001469 if (mDrawingState.frameRateForLayerTree == frameRate) {
1470 return false;
1471 }
1472
1473 mDrawingState.frameRateForLayerTree = frameRate;
1474 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001475 ->recordLayerHistory(sequence, layerProps, now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001476 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001477 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001478}
1479
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001480Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1481 return getDrawingState().frameRateForLayerTree;
1482}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001483
Robert Carr1f0a16a2016-10-24 16:27:39 -07001484bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001485 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001486 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001487 if (parent != nullptr && parent->isHiddenByPolicy()) {
1488 return true;
1489 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001490 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1491 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1492 if (zOrderRelativeOf != nullptr) {
1493 if (zOrderRelativeOf->isHiddenByPolicy()) {
1494 return true;
1495 }
1496 }
1497 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001498 if (CC_UNLIKELY(!isTransformValid())) {
1499 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1500 return true;
1501 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001502 return s.flags & layer_state_t::eLayerHidden;
1503}
1504
David Sodman41fdfc92017-11-06 16:09:56 -08001505uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001506 // TODO: should we do something special if mSecure is set?
1507 if (mProtectedByApp) {
1508 // need a hardware-protected path to external video sink
1509 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001510 }
Riley Andrews03414a12014-07-01 14:22:59 -07001511 if (mPotentialCursor) {
1512 usage |= GraphicBuffer::USAGE_CURSOR;
1513 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001514 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001515 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001516}
1517
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001518void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1519 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1520 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001521 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001522
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001523 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001524}
1525
Mathias Agopian13127d82013-03-05 17:47:11 -08001526// ----------------------------------------------------------------------------
1527// debugging
1528// ----------------------------------------------------------------------------
1529
Yiwei Zhang5434a782018-12-05 18:06:32 -08001530void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001531 result.append(kDumpTableRowLength, '-');
1532 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001533 result.append(" Layer name\n");
1534 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001535 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001536 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001537 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001538 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001539 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001540 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1541 result.append(kDumpTableRowLength, '-');
1542 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001543}
1544
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001545void Layer::miniDumpLegacy(std::string& result, const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001546 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001547 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001548 return;
1549 }
1550
Yiwei Zhang5434a782018-12-05 18:06:32 -08001551 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001552 if (mName.length() > 77) {
1553 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001554 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001555 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001556 shortened.append(mName, mName.length() - 36);
1557 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001558 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001559 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001560 }
1561
Yiwei Zhang5434a782018-12-05 18:06:32 -08001562 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001563
Alec Mourib416efd2018-09-06 21:01:59 +00001564 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001565 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001566
Chia-I Wu1e043612018-03-01 09:45:09 -08001567 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001568 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001569 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001570 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001571 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001572 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001573 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001574 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1575 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001576 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001577 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001578 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001579 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001580 const auto frameRate = getFrameRateForLayerTree();
Rachel Leece6e0042023-06-27 11:22:54 -07001581 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
1582 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.vote.rate).c_str(),
1583 ftl::enum_string(frameRate.vote.type).c_str(),
1584 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001585 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001586 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001587 }
Dan Stozae22aec72016-08-01 13:20:59 -07001588
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001589 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1590 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1591
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001592 result.append(kDumpTableRowLength, '-');
1593 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001594}
Dan Stozae22aec72016-08-01 13:20:59 -07001595
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001596void Layer::miniDump(std::string& result, const frontend::LayerSnapshot& snapshot,
1597 const DisplayDevice& display) const {
1598 const auto outputLayer = findOutputLayerForDisplay(&display, snapshot.path);
1599 if (!outputLayer) {
1600 return;
1601 }
1602
1603 StringAppendF(&result, " %s\n", snapshot.debugName.c_str());
1604 StringAppendF(&result, " %10zu | ", snapshot.globalZ);
1605 StringAppendF(&result, " %10d | ",
1606 snapshot.layerMetadata.getInt32(gui::METADATA_WINDOW_TYPE, 0));
1607 StringAppendF(&result, "%10s | ", toString(getCompositionType(outputLayer)).c_str());
1608 const auto& outputLayerState = outputLayer->getState();
1609 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1610 const Rect& frame = outputLayerState.displayFrame;
1611 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1612 const FloatRect& crop = outputLayerState.sourceCrop;
1613 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
1614 crop.bottom);
1615 const auto frameRate = snapshot.frameRate;
Ady Abraham77d406d2023-11-22 15:00:23 -08001616 std::string frameRateStr;
1617 if (frameRate.vote.rate.isValid()) {
1618 StringAppendF(&frameRateStr, "%.2f", frameRate.vote.rate.getValue());
1619 }
Rachel Leece6e0042023-06-27 11:22:54 -07001620 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
Ady Abraham77d406d2023-11-22 15:00:23 -08001621 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
Rachel Leece6e0042023-06-27 11:22:54 -07001622 ftl::enum_string(frameRate.vote.type).c_str(),
1623 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abraham77d406d2023-11-22 15:00:23 -08001624 } else if (frameRate.category != FrameRateCategory::Default) {
1625 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
1626 (std::string("Cat::") + ftl::enum_string(frameRate.category)).c_str(),
1627 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001628 } else {
1629 result.append(41, ' ');
1630 }
1631
1632 const auto focused = isLayerFocusedBasedOnPriority(snapshot.frameRateSelectionPriority);
1633 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1634
1635 result.append(kDumpTableRowLength, '-');
1636 result.append("\n");
1637}
1638
Yiwei Zhang5434a782018-12-05 18:06:32 -08001639void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001640 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001641}
1642
Svetoslavd85084b2014-03-20 10:28:31 -07001643void Layer::clearFrameStats() {
1644 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001645}
1646
Jamie Gennis6547ff42013-07-16 20:12:42 -07001647void Layer::logFrameStats() {
1648 mFrameTracker.logAndResetStats(mName);
1649}
1650
Svetoslavd85084b2014-03-20 10:28:31 -07001651void Layer::getFrameStats(FrameStats* outStats) const {
1652 mFrameTracker.getStats(outStats);
1653}
1654
Vishnu Nair76554eb2022-12-09 03:38:36 +00001655void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1656 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
Vishnu Nair3be61902023-04-26 19:47:29 -07001657 StringAppendF(&result, "Layer %s%s pid:%d uid:%d%s\n", getName().c_str(), hasBuffer.c_str(),
1658 mOwnerPid, mOwnerUid, isHandleAlive() ? " handleAlive" : "");
Vishnu Nair0f085c62019-08-30 08:49:12 -07001659}
1660
Brian Anderson5ea5e592016-12-01 16:54:33 -08001661void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001662 const int32_t layerId = getSequence();
1663 mFlinger->mTimeStats->onDestroy(layerId);
1664 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001665}
1666
Vishnu Nair787aa782023-03-17 13:46:46 -07001667size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001668 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001669 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001670 count += 1 + child->getChildrenCount();
1671 }
1672 return count;
1673}
1674
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001675void Layer::setGameModeForTree(GameMode gameMode) {
1676 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001677 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1678 gameMode =
1679 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001680 }
1681 setGameMode(gameMode);
1682 for (const sp<Layer>& child : mCurrentChildren) {
1683 child->setGameModeForTree(gameMode);
1684 }
1685}
1686
Robert Carr1f0a16a2016-10-24 16:27:39 -07001687void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001688 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001689 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001690
Robert Carr1f0a16a2016-10-24 16:27:39 -07001691 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001692 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001693 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001694 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001695}
1696
1697ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001698 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001699 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001700
Robert Carr1323c952019-01-28 18:13:27 -08001701 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001702 const auto removeResult = mCurrentChildren.remove(layer);
1703
1704 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001705 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001706 layer->updateTreeHasFrameRateVote();
1707
1708 return removeResult;
1709}
1710
Robert Carr15eae092018-03-23 13:43:53 -07001711void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001712 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001713 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001714 const float parentShadowRadius =
1715 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001716 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001717 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001718 }
1719}
1720
chaviwf1961f72017-09-18 16:41:07 -07001721bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001722 sp<Layer> newParent;
1723 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001724 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001725 if (newParent == nullptr) {
1726 ALOGE("Unable to promote Layer handle");
1727 return false;
1728 }
1729 if (newParent == this) {
1730 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1731 return false;
1732 }
1733 }
1734
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001735 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001736 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001737 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001738 }
1739
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001740 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001741 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001742 if (!newParent->isRemovedFromCurrentState()) {
1743 addToCurrentState();
1744 } else {
1745 onRemovedFromCurrentState();
1746 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001747 } else {
1748 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001749 }
1750
chaviw06178942017-07-27 10:25:59 -07001751 return true;
1752}
1753
Peiyong Lind3788632018-09-18 16:01:31 -07001754bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001755 static const mat4 identityMatrix = mat4();
1756
Robert Carr6a160312021-05-17 12:08:20 -07001757 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001758 return false;
1759 }
Robert Carr6a160312021-05-17 12:08:20 -07001760 ++mDrawingState.sequence;
1761 mDrawingState.colorTransform = matrix;
1762 mDrawingState.hasColorTransform = matrix != identityMatrix;
1763 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001764 setTransactionFlags(eTransactionNeeded);
1765 return true;
1766}
1767
chaviwf66724d2018-11-28 16:35:21 -08001768mat4 Layer::getColorTransform() const {
1769 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001770 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001771 colorTransform = parent->getColorTransform() * colorTransform;
1772 }
1773 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001774}
1775
1776bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001777 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001778 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001779 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1780 }
1781 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001782}
1783
Chia-I Wu11481472018-05-04 10:43:19 -07001784bool Layer::isLegacyDataSpace() const {
1785 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001786 return !(getDataSpace() &
1787 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1788 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001789}
1790
Robert Carr1f0a16a2016-10-24 16:27:39 -07001791void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001792 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001793}
1794
Robert Carr6a160312021-05-17 12:08:20 -07001795int32_t Layer::getZ(LayerVector::StateSet) const {
1796 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001797}
1798
Robert Carr1c5481e2019-07-01 14:42:27 -07001799bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001800 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001801 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001802 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001803}
1804
David Sodman41fdfc92017-11-06 16:09:56 -08001805__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001806 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001807 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1808 "makeTraversalList received invalid stateSet");
1809 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1810 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001811 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001812
Robert Carr29abff82017-12-04 13:51:20 -08001813 if (state.zOrderRelatives.size() == 0) {
1814 *outSkipRelativeZUsers = true;
1815 return children;
1816 }
1817
chaviwfd462612018-05-31 16:11:27 -07001818 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001819 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001820 sp<Layer> strongRelative = weakRelative.promote();
1821 if (strongRelative != nullptr) {
1822 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001823 }
1824 }
1825
Dan Stoza412903f2017-04-27 13:42:17 -07001826 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001827 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001828 continue;
1829 }
Robert Carrdb66e622017-04-10 16:55:57 -07001830 traverse.add(child);
1831 }
1832
1833 return traverse;
1834}
1835
Robert Carr1f0a16a2016-10-24 16:27:39 -07001836/**
Robert Carrdb66e622017-04-10 16:55:57 -07001837 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001838 */
Dan Stoza412903f2017-04-27 13:42:17 -07001839void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001840 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1841 // produce a new list for traversing, including our relatives, and not including our children
1842 // who are relatives of another surface. In the case that there are no relative Z,
1843 // makeTraversalList returns our children directly to avoid significant overhead.
1844 // However in this case we need to take the responsibility for filtering children which
1845 // are relatives of another surface here.
1846 bool skipRelativeZUsers = false;
1847 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001848
Robert Carr1f0a16a2016-10-24 16:27:39 -07001849 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001850 for (; i < list.size(); i++) {
1851 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001852 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1853 continue;
1854 }
1855
chaviw301b1d82019-11-06 13:15:09 -08001856 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001857 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001858 }
Dan Stoza412903f2017-04-27 13:42:17 -07001859 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001860 }
Robert Carr29abff82017-12-04 13:51:20 -08001861
Dan Stoza412903f2017-04-27 13:42:17 -07001862 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001863 for (; i < list.size(); i++) {
1864 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001865
Robert Carr29abff82017-12-04 13:51:20 -08001866 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1867 continue;
1868 }
Dan Stoza412903f2017-04-27 13:42:17 -07001869 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001870 }
1871}
1872
1873/**
Robert Carrdb66e622017-04-10 16:55:57 -07001874 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001875 */
Dan Stoza412903f2017-04-27 13:42:17 -07001876void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1877 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001878 // See traverseInZOrder for documentation.
1879 bool skipRelativeZUsers = false;
1880 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001881
Robert Carr1f0a16a2016-10-24 16:27:39 -07001882 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001883 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001884 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001885
1886 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1887 continue;
1888 }
1889
chaviw301b1d82019-11-06 13:15:09 -08001890 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001891 break;
1892 }
Dan Stoza412903f2017-04-27 13:42:17 -07001893 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001894 }
Dan Stoza412903f2017-04-27 13:42:17 -07001895 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001896 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001897 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001898
1899 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1900 continue;
1901 }
1902
Dan Stoza412903f2017-04-27 13:42:17 -07001903 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001904 }
1905}
1906
Edgar Arriaga844fa672020-01-16 14:21:42 -08001907void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1908 visitor(this);
1909 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001910 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001911 for (const sp<Layer>& child : children) {
1912 child->traverse(state, visitor);
1913 }
1914}
1915
Vishnu Nair787aa782023-03-17 13:46:46 -07001916void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
1917 for (const sp<Layer>& child : mDrawingChildren) {
1918 visitor(child.get());
1919 }
1920}
1921
chaviw4b129c22018-04-09 16:19:43 -07001922LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1923 const std::vector<Layer*>& layersInTree) {
1924 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1925 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001926 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1927 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001928 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001929
chaviwfd462612018-05-31 16:11:27 -07001930 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001931 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1932 sp<Layer> strongRelative = weakRelative.promote();
1933 // Only add relative layers that are also descendents of the top most parent of the tree.
1934 // If a relative layer is not a descendent, then it should be ignored.
1935 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1936 traverse.add(strongRelative);
1937 }
1938 }
1939
1940 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001941 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001942 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1943 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1944 // the child here since it won't be added later as a relative.
1945 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1946 childState.zOrderRelativeOf.promote().get())) {
1947 continue;
1948 }
1949 traverse.add(child);
1950 }
1951
1952 return traverse;
1953}
1954
1955void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1956 LayerVector::StateSet stateSet,
1957 const LayerVector::Visitor& visitor) {
1958 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001959
1960 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001961 for (; i < list.size(); i++) {
1962 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001963 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001964 break;
1965 }
chaviw4b129c22018-04-09 16:19:43 -07001966 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001967 }
chaviw4b129c22018-04-09 16:19:43 -07001968
chaviwa76b2712017-09-20 12:02:26 -07001969 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001970 for (; i < list.size(); i++) {
1971 const auto& relative = list[i];
1972 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001973 }
1974}
1975
chaviw4b129c22018-04-09 16:19:43 -07001976std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1977 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1978 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1979
1980 std::vector<Layer*> layersInTree = {this};
1981 for (size_t i = 0; i < children.size(); i++) {
1982 const auto& child = children[i];
1983 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1984 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1985 }
1986
1987 return layersInTree;
1988}
1989
1990void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1991 const LayerVector::Visitor& visitor) {
1992 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1993 std::sort(layersInTree.begin(), layersInTree.end());
1994 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1995}
1996
Peiyong Linefefaac2018-08-17 12:27:51 -07001997ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001998 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001999}
2000
Garfield Tan2c1782c2022-02-16 15:25:05 -08002001bool Layer::isTransformValid() const {
2002 float transformDet = getTransform().det();
2003 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2004}
2005
chaviw13fdc492017-06-27 12:40:18 -07002006half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002007 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002008
chaviw13fdc492017-06-27 12:40:18 -07002009 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2010 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002011}
Robert Carr6452f122017-03-21 10:41:29 -07002012
Vishnu Nair6213bd92020-05-08 17:42:25 -07002013ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002014 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002015 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2016 return fixedTransformHint;
2017 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002018 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002019 if (!p) return fixedTransformHint;
2020 return p->getFixedTransformHint();
2021}
2022
chaviw13fdc492017-06-27 12:40:18 -07002023half4 Layer::getColor() const {
2024 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002025 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002026}
Robert Carr6452f122017-03-21 10:41:29 -07002027
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002028int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002029 if (getDrawingState().backgroundBlurRadius == 0) {
2030 return 0;
2031 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002032
Vishnu Nair29810f72022-07-01 16:38:41 +00002033 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002034 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2035 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002036}
2037
Galia Peychevae0acf382021-04-12 21:22:34 +02002038const std::vector<BlurRegion> Layer::getBlurRegions() const {
2039 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002040 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002041 for (auto& region : regionsCopy) {
2042 region.alpha = region.alpha * layerAlpha;
2043 }
2044 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002045}
2046
Vishnu Naire14c6b32022-08-06 04:20:15 +00002047RoundedCornerState Layer::getRoundedCornerState() const {
Leon Scroggins IIIc1dbfcb2022-03-21 16:48:10 -04002048 // Today's DPUs cannot do rounded corners. If RenderEngine cannot render
2049 // protected content, remove rounded corners from protected content so it
2050 // can be rendered by the DPU.
2051 if (isProtected() && !mFlinger->getRenderEngine().supportsProtectedContent()) {
2052 return {};
2053 }
2054
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002055 // Get parent settings
2056 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002057 const auto& parent = mDrawingParent.promote();
2058 if (parent != nullptr) {
2059 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002060 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002061 ui::Transform t = getActiveTransform(getDrawingState());
2062 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002063 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002064 parentSettings.radius.x *= t.getScaleX();
2065 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002066 }
2067 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002068
2069 // Get layer settings
2070 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002071 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002072 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002073 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002074
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002075 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002076 // If the parent and the layer have rounded corner settings, use the parent settings if the
2077 // parent crop is entirely inside the layer crop.
2078 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2079 if (parentSettings.cropRect.left > layerCropRect.left &&
2080 parentSettings.cropRect.top > layerCropRect.top &&
2081 parentSettings.cropRect.right < layerCropRect.right &&
2082 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2083 return parentSettings;
2084 } else {
2085 return layerSettings;
2086 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002087 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002088 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002089 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002090 return parentSettings;
2091 }
2092 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002093}
2094
Robert Carr88b85e12022-03-21 15:47:35 -07002095bool Layer::findInHierarchy(const sp<Layer>& l) {
2096 if (l == this) {
2097 return true;
2098 }
2099 for (auto& child : mDrawingChildren) {
2100 if (child->findInHierarchy(l)) {
2101 return true;
2102 }
2103 }
2104 return false;
2105}
2106
Robert Carr1f0a16a2016-10-24 16:27:39 -07002107void Layer::commitChildList() {
2108 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2109 const auto& child = mCurrentChildren[i];
2110 child->commitChildList();
2111 }
2112 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002113 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002114 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2115 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2116 if (zOrderRelativeOf == nullptr) return;
2117 if (findInHierarchy(zOrderRelativeOf)) {
2118 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2119 zOrderRelativeOf->mName.c_str());
2120 ALOGE("Severing rel Z loop, potentially dangerous");
2121 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002122 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002123 }
2124 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002125}
2126
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002127
chaviw3277faf2021-05-19 16:45:23 -05002128void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002129 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002130 mDrawingState.touchableRegionCrop =
2131 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002132 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002133 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002134 setTransactionFlags(eTransactionNeeded);
2135}
2136
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002137perfetto::protos::LayerProto* Layer::writeToProto(perfetto::protos::LayersProto& layersProto,
2138 uint32_t traceFlags) {
2139 perfetto::protos::LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002140 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002141 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2142
Vishnu Nair00b90132021-11-05 14:03:40 -07002143 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nair2f65e972023-04-04 16:36:28 +00002144 ui::LayerStack layerStack =
2145 (mSnapshot) ? mSnapshot->outputFilter.layerStack : ui::INVALID_LAYER_STACK;
2146 writeCompositionStateToProto(layerProto, layerStack);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002147 }
2148
chaviw08f3cb22020-01-13 13:17:21 -08002149 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002150 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002151 }
chaviw6d89e2d2020-01-14 14:42:01 -08002152
2153 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002154}
2155
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002156void Layer::writeCompositionStateToProto(perfetto::protos::LayerProto* layerProto,
2157 ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002158 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002159 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +00002160
2161 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002162 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002163 const auto compositionType = getCompositionType(*display);
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002164 layerProto->set_hwc_composition_type(
2165 static_cast<perfetto::protos::HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +00002166 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +00002167 [&]() { return layerProto->mutable_visible_region(); });
2168 }
2169}
2170
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002171void Layer::writeToProtoDrawingState(perfetto::protos::LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002172 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002173 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002174 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002175 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002176 [&]() { return layerInfo->mutable_active_buffer(); });
2177 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2178 layerInfo->mutable_buffer_transform());
2179 }
2180 layerInfo->set_invalidate(contentDirty);
2181 layerInfo->set_is_protected(isProtected());
2182 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2183 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002184 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002185 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002186 layerInfo->set_corner_radius(
2187 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002188 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2189 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2190 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2191 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2192 [&]() { return layerInfo->mutable_position(); });
2193 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002194 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2195 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002196
Vishnu Nair00b90132021-11-05 14:03:40 -07002197 if (hasColorTransform()) {
2198 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002199 }
2200
Vishnu Nair60db8c02020-04-02 11:55:16 -07002201 LayerProtoHelper::writeToProto(mSourceBounds,
2202 [&]() { return layerInfo->mutable_source_bounds(); });
2203 LayerProtoHelper::writeToProto(mScreenBounds,
2204 [&]() { return layerInfo->mutable_screen_bounds(); });
2205 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2206 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2207 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002208}
2209
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002210void Layer::writeToProtoCommonState(perfetto::protos::LayerProto* layerInfo,
2211 LayerVector::StateSet stateSet, uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002212 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2213 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002214 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002215
chaviw766c9c52021-02-10 17:36:47 -08002216 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002217
Vishnu Nair00b90132021-11-05 14:03:40 -07002218 layerInfo->set_id(sequence);
2219 layerInfo->set_name(getName().c_str());
2220 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002221
Vishnu Nair00b90132021-11-05 14:03:40 -07002222 for (const auto& child : children) {
2223 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002224 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002225
Vishnu Nair00b90132021-11-05 14:03:40 -07002226 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2227 sp<Layer> strongRelative = weakRelative.promote();
2228 if (strongRelative != nullptr) {
2229 layerInfo->add_relatives(strongRelative->sequence);
2230 }
2231 }
2232
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002233 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002234 [&]() { return layerInfo->mutable_transparent_region(); });
2235
2236 layerInfo->set_layer_stack(getLayerStack().id);
2237 layerInfo->set_z(state.z);
2238
2239 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2240 return layerInfo->mutable_requested_position();
2241 });
2242
Vishnu Nair00b90132021-11-05 14:03:40 -07002243 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2244
2245 layerInfo->set_is_opaque(isOpaque(state));
2246
2247 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2248 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2249 LayerProtoHelper::writeToProto(state.color,
2250 [&]() { return layerInfo->mutable_requested_color(); });
2251 layerInfo->set_flags(state.flags);
2252
2253 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2254 layerInfo->mutable_requested_transform());
2255
2256 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2257 if (parent != nullptr) {
2258 layerInfo->set_parent(parent->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002259 }
2260
2261 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2262 if (zOrderRelativeOf != nullptr) {
2263 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002264 }
2265
2266 layerInfo->set_is_relative_of(state.isRelativeOf);
2267
2268 layerInfo->set_owner_uid(mOwnerUid);
2269
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002270 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002271 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002272 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002273 info = fillInputInfo(
2274 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002275 } else {
2276 info = state.inputInfo;
2277 }
2278
2279 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002280 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002281 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002282
Vishnu Nair00b90132021-11-05 14:03:40 -07002283 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002284 auto protoMap = layerInfo->mutable_metadata();
2285 for (const auto& entry : state.metadata.mMap) {
2286 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2287 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002288 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002289
2290 LayerProtoHelper::writeToProto(state.destinationFrame,
2291 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002292}
2293
Robert Carr2e102c92018-10-23 12:11:15 -07002294bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002295 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002296}
2297
Prabir Pradhan33da9462022-06-14 14:55:57 +00002298// Applies the given transform to the region, while protecting against overflows caused by any
2299// offsets. If applying the offset in the transform to any of the Rects in the region would result
2300// in an overflow, they are not added to the output Region.
2301static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2302 const std::string& debugWindowName) {
2303 // Round the translation using the same rounding strategy used by ui::Transform.
2304 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2305 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2306
2307 ui::Transform transformWithoutOffset = t;
2308 transformWithoutOffset.set(0.f, 0.f);
2309
2310 const Region transformed = transformWithoutOffset.transform(r);
2311
2312 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2313 Region ret;
2314 for (const auto& rect : transformed) {
2315 Rect newRect;
2316 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2317 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2318 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2319 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2320 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2321 debugWindowName.c_str());
2322 continue;
2323 }
2324 ret.orSelf(newRect);
2325 }
2326 return ret;
2327}
2328
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002329void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002330 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2331 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002332 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002333 }
2334
Chavi Weingarten7f019192023-08-08 20:39:01 +00002335 info.frame = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
chaviw1ff3d1e2020-07-01 15:53:47 -07002336
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002337 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002338 inputToLayer.set(inputBounds.left, inputBounds.top);
2339 const ui::Transform layerToScreen = getInputTransform();
2340 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002341
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002342 // InputDispatcher expects a display-to-input transform.
2343 info.transform = inputToDisplay.inverse();
2344
2345 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002346 info.touchableRegion =
2347 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002348}
2349
chaviw3277faf2021-05-19 16:45:23 -05002350void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002351 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002352 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002353 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002354 }
2355 if (p != nullptr) {
2356 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2357 }
2358}
2359
Vishnu Naira066d902021-09-13 18:40:17 -07002360gui::DropInputMode Layer::getDropInputMode() const {
2361 gui::DropInputMode mode = mDrawingState.dropInputMode;
2362 if (mode == gui::DropInputMode::ALL) {
2363 return mode;
2364 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002365 sp<Layer> parent = mDrawingParent.promote();
2366 if (parent) {
2367 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002368 if (parentMode != gui::DropInputMode::NONE) {
2369 return parentMode;
2370 }
2371 }
2372 return mode;
2373}
2374
2375void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002376 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002377 return;
2378 }
2379
2380 // Check if we need to drop input unconditionally
2381 gui::DropInputMode dropInputMode = getDropInputMode();
2382 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002383 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002384 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2385 return;
2386 }
2387
2388 // Check if we need to check if the window is obscured by parent
2389 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2390 return;
2391 }
2392
2393 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002394 sp<Layer> parent = mDrawingParent.promote();
2395 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002396 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002397 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2398 static_cast<float>(getAlpha()));
2399 }
2400
2401 // Check if the parent has cropped the buffer
2402 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2403 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002404 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002405 return;
2406 }
2407
2408 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2409 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2410 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2411 // match then the layer has not been cropped by its parents.
2412 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2413 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2414
2415 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002416 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002417 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2418 getDebugName());
2419 } else {
2420 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2421 // input if the window is obscured. This check should be done in surfaceflinger but the
2422 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2423 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002424 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002425 }
2426}
2427
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002428WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002429 if (!hasInputInfo()) {
2430 mDrawingState.inputInfo.name = getName();
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002431 mDrawingState.inputInfo.ownerUid = gui::Uid{mOwnerUid};
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00002432 mDrawingState.inputInfo.ownerPid = gui::Pid{mOwnerPid};
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002433 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Linnan Li13bf76a2024-05-05 19:18:02 +08002434 mDrawingState.inputInfo.displayId = toLogicalDisplayId(getLayerStack());
chaviw7e72caf2020-12-02 16:50:43 -08002435 }
2436
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002437 const ui::Transform& displayTransform =
2438 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2439
chaviw3277faf2021-05-19 16:45:23 -05002440 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002441 info.id = sequence;
Linnan Li13bf76a2024-05-05 19:18:02 +08002442 info.displayId = toLogicalDisplayId(getLayerStack());
chaviw7e72caf2020-12-02 16:50:43 -08002443
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002444 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002445
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002446 if (displayArgs.transform == nullptr) {
2447 // Do not let the window receive touches if it is not associated with a valid display
2448 // transform. We still allow the window to receive keys and prevent ANRs.
2449 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2450 }
2451
Patrick Williams1caf3b72023-03-31 10:59:10 -05002452 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !isVisibleForInput());
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002453
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002454 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002455 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002456 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002457
Vishnu Nair16a938f2021-09-24 07:14:54 -07002458 // If the window will be blacked out on a display because the display does not have the secure
2459 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002460 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002461 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002462 }
2463
Vishnu Nairfed7c122023-03-18 01:54:43 +00002464 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002465 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002466 Rect inputBoundsInDisplaySpace;
2467 if (!cropLayer) {
2468 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2469 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2470 } else {
2471 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2472 inputBoundsInDisplaySpace =
2473 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2474 }
2475 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002476 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002477 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2478 Rect inputBoundsInDisplaySpace =
2479 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2480 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002481 }
2482
Winson Chunga30f7c92021-06-29 15:42:56 -07002483 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2484 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002485 if (isTrustedOverlay()) {
2486 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2487 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002488
chaviwaf87b3e2019-10-01 16:59:28 -07002489 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2490 // touches from going outside the cloned area.
2491 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002492 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002493 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2494 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002495 info.touchableRegion = info.touchableRegion.intersect(rect);
2496 }
2497 }
2498
Vishnu Nair494a2e42023-11-10 17:21:19 -08002499 Rect bufferSize = getBufferSize(getDrawingState());
2500 info.contentSize = Size(bufferSize.width(), bufferSize.height());
2501
Robert Carr720e5062018-07-30 17:45:14 -07002502 return info;
2503}
2504
Vishnu Nairfed7c122023-03-18 01:54:43 +00002505Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2506 const ui::Transform& screenToDisplay) {
2507 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2508 // frame and transform used for the layer, which determines the bounds and the coordinate space
2509 // within which the layer will receive input.
2510
2511 // Coordinate space definitions:
2512 // - display: The display device's coordinate space. Correlates to pixels on the display.
2513 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2514 // - layer: The coordinate space of this layer.
2515 // - input: The coordinate space in which this layer will receive input events. This could be
2516 // different than layer space if a surfaceInset is used, which changes the origin
2517 // of the input space.
2518
2519 // Crop the input bounds to ensure it is within the parent's bounds.
2520 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2521 const ui::Transform layerToScreen = getInputTransform();
2522 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2523 return Rect{layerToDisplay.transform(croppedInputBounds)};
2524}
2525
chaviwaf87b3e2019-10-01 16:59:28 -07002526sp<Layer> Layer::getClonedRoot() {
2527 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002528 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002529 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002530 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002531 return nullptr;
2532 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002533 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002534}
2535
Robert Carredd13602020-04-13 17:24:34 -07002536bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002537 return mDrawingState.inputInfo.token != nullptr ||
2538 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002539}
2540
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002541compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002542 const DisplayDevice* display) const {
2543 if (!display) return nullptr;
Lloyd Pique30db6402023-06-26 18:56:51 +00002544 if (!mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00002545 return display->getCompositionDisplay()->getOutputLayerForLayer(
2546 getCompositionEngineLayerFE());
2547 }
2548 sp<LayerFE> layerFE;
2549 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2550 for (auto& [p, layer] : mLayerFEs) {
2551 if (p == path) {
2552 layerFE = layer;
2553 }
2554 }
2555
2556 if (!layerFE) return nullptr;
2557 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002558}
2559
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002560compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
2561 const DisplayDevice* display, const frontend::LayerHierarchy::TraversalPath& path) const {
2562 if (!display) return nullptr;
Vishnu Naire9ee0002023-07-01 03:14:51 +00002563 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2564 return display->getCompositionDisplay()->getOutputLayerForLayer(
2565 getCompositionEngineLayerFE());
2566 }
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002567 sp<LayerFE> layerFE;
2568 for (auto& [p, layer] : mLayerFEs) {
2569 if (p == path) {
2570 layerFE = layer;
2571 }
2572 }
2573
2574 if (!layerFE) return nullptr;
2575 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
2576}
2577
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002578Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2579 const auto outputLayer = findOutputLayerForDisplay(display);
2580 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002581}
2582
Patrick Williamsbb25f802022-08-30 23:02:34 +00002583void Layer::updateCloneBufferInfo() {
2584 if (!isClone() || !isClonedFromAlive()) {
2585 return;
2586 }
2587
2588 sp<Layer> clonedFrom = getClonedFrom();
2589 mBufferInfo = clonedFrom->mBufferInfo;
2590 mSidebandStream = clonedFrom->mSidebandStream;
2591 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2592 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2593 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2594
2595 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2596 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2597 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2598 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2599 // the cloned drawingState again.
2600 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2601 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2602 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2603 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2604
2605 cloneDrawingState(clonedFrom.get());
2606
2607 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2608 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2609 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2610 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002611}
chaviw74b03172019-08-19 11:09:03 -07002612
Vishnu Nair3be61902023-04-26 19:47:29 -07002613bool Layer::updateMirrorInfo(const std::deque<Layer*>& cloneRootsPendingUpdates) {
chaviw74b03172019-08-19 11:09:03 -07002614 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2615 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2616 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2617 // that case, we want to delete the reference to the clone since we want it to get
2618 // destroyed. The root, this layer, will still be around since the client can continue
2619 // to hold a reference, but no cloned layers will be displayed.
2620 mClonedChild = nullptr;
Vishnu Nair3be61902023-04-26 19:47:29 -07002621 return true;
chaviw74b03172019-08-19 11:09:03 -07002622 }
2623
2624 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2625 // If the real layer exists and is in current state, add the clone as a child of the root.
2626 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2627 // copied to drawingState for the root layer. So the clonedChild is always removed from
2628 // drawingState and then needs to be added back each traversal.
2629 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2630 addChildToDrawing(mClonedChild);
2631 }
2632
2633 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002634 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002635 mClonedChild->updateClonedRelatives(clonedLayersMap);
Vishnu Nair3be61902023-04-26 19:47:29 -07002636
2637 for (Layer* root : cloneRootsPendingUpdates) {
2638 if (clonedLayersMap.find(sp<Layer>::fromExisting(root)) != clonedLayersMap.end()) {
2639 return false;
2640 }
2641 }
2642 return true;
chaviw74b03172019-08-19 11:09:03 -07002643}
2644
2645void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2646 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2647 // to the clone. If the real layer is no longer alive, continue traversing the children
2648 // since we may be able to pull out other children that are still alive.
2649 if (isClonedFromAlive()) {
2650 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002651 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002652 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002653 }
2654
2655 // The clone layer may have children in drawingState since they may have been created and
2656 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2657 // that already exist, since we can just re-use them.
2658 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2659 // not updated in the regular traversal. They are skipped since the root will lose the
2660 // reference to them when it copies its currentChildren to drawing.
2661 for (sp<Layer>& child : mDrawingChildren) {
2662 child->updateClonedDrawingState(clonedLayersMap);
2663 }
2664}
2665
2666void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2667 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2668 mDrawingChildren.clear();
2669
2670 if (!isClonedFromAlive()) {
2671 return;
2672 }
2673
2674 sp<Layer> clonedFrom = getClonedFrom();
2675 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2676 if (child == mirrorRoot) {
2677 // This is to avoid cyclical mirroring.
2678 continue;
2679 }
2680 sp<Layer> clonedChild = clonedLayersMap[child];
2681 if (clonedChild == nullptr) {
Melody Hsu12ecd082024-04-17 19:03:13 +00002682 clonedChild = child->createClone();
chaviw74b03172019-08-19 11:09:03 -07002683 clonedLayersMap[child] = clonedChild;
2684 }
2685 addChildToDrawing(clonedChild);
2686 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2687 }
2688}
2689
chaviwaf87b3e2019-10-01 16:59:28 -07002690void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2691 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2692 if (cropLayer != nullptr) {
2693 if (clonedLayersMap.count(cropLayer) == 0) {
2694 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2695 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002696 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002697 } else {
2698 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2699 mDrawingState.touchableRegionCrop = clonedCropLayer;
2700 }
2701 }
2702 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2703 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002704 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002705}
2706
2707void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002708 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002709 mDrawingState.zOrderRelatives.clear();
2710
2711 if (!isClonedFromAlive()) {
2712 return;
2713 }
2714
chaviwaf87b3e2019-10-01 16:59:28 -07002715 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002716 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002717 const sp<Layer>& relative = relativeWeak.promote();
2718 if (clonedLayersMap.count(relative) > 0) {
2719 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002720 mDrawingState.zOrderRelatives.add(clonedRelative);
2721 }
2722 }
2723
2724 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2725 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2726 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2727 // still traverse the children, but the layer with the missing relativeOf will not be shown
2728 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002729 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2730 if (clonedLayersMap.count(relativeOf) > 0) {
2731 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002732 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2733 }
2734
chaviwaf87b3e2019-10-01 16:59:28 -07002735 updateClonedInputInfo(clonedLayersMap);
2736
chaviw74b03172019-08-19 11:09:03 -07002737 for (sp<Layer>& child : mDrawingChildren) {
2738 child->updateClonedRelatives(clonedLayersMap);
2739 }
2740}
2741
2742void Layer::addChildToDrawing(const sp<Layer>& layer) {
2743 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002744 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002745}
2746
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002747bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002748 const State& s(mDrawingState);
2749 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2750 return true;
2751 }
2752
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002753 sp<Layer> parent = mDrawingParent.promote();
2754 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002755}
2756
Robert Carr6a0382d2021-07-01 15:57:17 -07002757void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2758 mClonedChild = clonedChild;
2759 mHadClonedChild = true;
Vishnu Nair3be61902023-04-26 19:47:29 -07002760 mFlinger->mLayerMirrorRoots.push_back(this);
Robert Carr6a0382d2021-07-01 15:57:17 -07002761}
2762
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002763bool Layer::setDropInputMode(gui::DropInputMode mode) {
2764 if (mDrawingState.dropInputMode == mode) {
2765 return false;
2766 }
2767 mDrawingState.dropInputMode = mode;
2768 return true;
2769}
2770
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002771void Layer::cloneDrawingState(const Layer* from) {
2772 mDrawingState = from->mDrawingState;
2773 // Skip callback info since they are not applicable for cloned layers.
2774 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002775 // TODO (b/238781169) currently broken for mirror layers because we do not
2776 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002777 mDrawingState.callbackHandles = {};
2778}
2779
Patrick Williamsbb25f802022-08-30 23:02:34 +00002780void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2781 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002782 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002783 if (!listener) {
2784 return;
2785 }
2786 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002787 uint32_t currentMaxAcquiredBufferCount =
2788 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002789 listener->onReleaseBuffer({buffer->getId(), framenumber},
2790 releaseFence ? releaseFence : Fence::NO_FENCE,
2791 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002792}
2793
Melody Hsu793f8362024-01-08 20:00:35 +00002794sp<CallbackHandle> Layer::findCallbackHandle() {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002795 // If we are displayed on multiple displays in a single composition cycle then we would
2796 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2797 // For example we can only use it if all the displays are client comp, and we need
2798 // to merge all the client comp fences. We could do this, but for now we just
2799 // disable the optimization when a layer is composed on multiple displays.
2800 if (mClearClientCompositionFenceOnLayerDisplayed) {
2801 mLastClientCompositionFence = nullptr;
2802 } else {
2803 mClearClientCompositionFenceOnLayerDisplayed = true;
2804 }
2805
2806 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2807 // buffer that was presented on this layer. The first transaction that came in this frame that
2808 // replaced the previous buffer on this layer needs this release fence, because the fence will
2809 // let the client know when that previous buffer is removed from the screen.
2810 //
2811 // Every other transaction on this layer does not need a release fence because no other
2812 // Transactions that were set on this layer this frame are going to have their preceding buffer
2813 // removed from the display this frame.
2814 //
2815 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2816 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2817 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2818 // the previous buffer will be released this frame. The third transaction also contains a
2819 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2820 // transaction will now no longer be presented so it is released immediately and the third
2821 // transaction doesn't need a previous release fence.
2822 sp<CallbackHandle> ch;
2823 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002824 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002825 ch = handle;
2826 break;
2827 }
2828 }
Melody Hsu793f8362024-01-08 20:00:35 +00002829 return ch;
2830}
2831
2832void Layer::prepareReleaseCallbacks(ftl::Future<FenceResult> futureFenceResult,
2833 ui::LayerStack layerStack) {
2834 sp<CallbackHandle> ch = findCallbackHandle();
2835
2836 if (ch != nullptr) {
2837 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2838 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2839 ch->name = mName;
2840 } else {
Melody Hsue4ef87f2024-03-26 23:54:45 +00002841 // If we didn't get a release callback yet (e.g. some scenarios when capturing
2842 // screenshots asynchronously) then make sure we don't drop the fence.
2843 // Older fences for the same layer stack can be dropped when a new fence arrives.
2844 // An assumption here is that RenderEngine performs work sequentially, so an
2845 // incoming fence will not fire before an existing fence.
2846 mAdditionalPreviousReleaseFences.emplace_or_replace(layerStack,
2847 std::move(futureFenceResult));
Melody Hsu793f8362024-01-08 20:00:35 +00002848 }
2849
2850 if (mBufferInfo.mBuffer) {
2851 mPreviouslyPresentedLayerStacks.push_back(layerStack);
2852 }
2853
2854 if (mDrawingState.frameNumber > 0) {
2855 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
2856 }
2857}
2858
2859void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
2860 ui::LayerStack layerStack,
2861 std::function<FenceResult(FenceResult)>&& continuation) {
2862 sp<CallbackHandle> ch = findCallbackHandle();
Alec Mouri9892aac2023-12-11 21:16:59 +00002863
2864 if (!FlagManager::getInstance().screenshot_fence_preservation() && continuation) {
2865 futureFenceResult = ftl::Future(futureFenceResult).then(std::move(continuation)).share();
2866 }
2867
Patrick Williamsbb25f802022-08-30 23:02:34 +00002868 if (ch != nullptr) {
2869 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
Melody Hsu793f8362024-01-08 20:00:35 +00002870 ch->previousSharedReleaseFences.emplace_back(std::move(futureFenceResult));
Patrick Williamsbb25f802022-08-30 23:02:34 +00002871 ch->name = mName;
Alec Mouri9892aac2023-12-11 21:16:59 +00002872 } else if (FlagManager::getInstance().screenshot_fence_preservation()) {
2873 // If we didn't get a release callback yet, e.g. some scenarios when capturing screenshots
2874 // asynchronously, then make sure we don't drop the fence.
Melody Hsu793f8362024-01-08 20:00:35 +00002875 mPreviousReleaseFenceAndContinuations.emplace_back(std::move(futureFenceResult),
2876 std::move(continuation));
Alec Mouri9892aac2023-12-11 21:16:59 +00002877 std::vector<FenceAndContinuation> mergedFences;
2878 sp<Fence> prevFence = nullptr;
2879 // For a layer that's frequently screenshotted, try to merge fences to make sure we don't
2880 // grow unbounded.
Melody Hsu793f8362024-01-08 20:00:35 +00002881 for (const auto& futureAndContinuation : mPreviousReleaseFenceAndContinuations) {
2882 auto result = futureAndContinuation.future.wait_for(0s);
Alec Mouri9892aac2023-12-11 21:16:59 +00002883 if (result != std::future_status::ready) {
Melody Hsu793f8362024-01-08 20:00:35 +00002884 mergedFences.emplace_back(futureAndContinuation);
Alec Mouri9892aac2023-12-11 21:16:59 +00002885 continue;
2886 }
2887
Melody Hsu793f8362024-01-08 20:00:35 +00002888 mergeFence(getDebugName(),
2889 futureAndContinuation.chain().get().value_or(Fence::NO_FENCE), prevFence);
Alec Mouri9892aac2023-12-11 21:16:59 +00002890 }
2891 if (prevFence != nullptr) {
2892 mergedFences.emplace_back(ftl::yield(FenceResult(std::move(prevFence))).share());
2893 }
2894
Melody Hsu793f8362024-01-08 20:00:35 +00002895 mPreviousReleaseFenceAndContinuations.swap(mergedFences);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002896 }
Alec Mouri9892aac2023-12-11 21:16:59 +00002897
Vishnu Nair316b7f42023-10-13 23:44:46 +00002898 if (mBufferInfo.mBuffer) {
2899 mPreviouslyPresentedLayerStacks.push_back(layerStack);
2900 }
Alec Mouri21d94322023-10-17 19:51:39 +00002901
2902 if (mDrawingState.frameNumber > 0) {
2903 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
2904 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002905}
2906
Patrick Williamsbb25f802022-08-30 23:02:34 +00002907void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2908 for (const auto& handle : mDrawingState.callbackHandles) {
Melody Hsu9af30702024-04-17 18:23:43 +00002909 handle->transformHint = mTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002910 handle->dequeueReadyTime = dequeueReadyTime;
2911 handle->currentMaxAcquiredBufferCount =
2912 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2913 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2914 handle->previousReleaseCallbackId.framenumber);
2915 }
2916
2917 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002918 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002919 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2920 break;
2921 }
2922 }
2923
Pascal Mütschardd56514e2024-05-24 17:37:13 +02002924 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002925 mDrawingState.callbackHandles = {};
2926}
2927
2928bool Layer::willPresentCurrentTransaction() const {
2929 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2930 return (getSidebandStreamChanged() || getAutoRefresh() ||
2931 (mDrawingState.modified &&
2932 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2933}
2934
2935bool Layer::setTransform(uint32_t transform) {
2936 if (mDrawingState.bufferTransform == transform) return false;
2937 mDrawingState.bufferTransform = transform;
2938 mDrawingState.modified = true;
2939 setTransactionFlags(eTransactionNeeded);
2940 return true;
2941}
2942
2943bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2944 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2945 mDrawingState.sequence++;
2946 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2947 mDrawingState.modified = true;
2948 setTransactionFlags(eTransactionNeeded);
2949 return true;
2950}
2951
2952bool Layer::setBufferCrop(const Rect& bufferCrop) {
2953 if (mDrawingState.bufferCrop == bufferCrop) return false;
2954
2955 mDrawingState.sequence++;
2956 mDrawingState.bufferCrop = bufferCrop;
2957
2958 mDrawingState.modified = true;
2959 setTransactionFlags(eTransactionNeeded);
2960 return true;
2961}
2962
2963bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2964 if (mDrawingState.destinationFrame == destinationFrame) return false;
2965
2966 mDrawingState.sequence++;
2967 mDrawingState.destinationFrame = destinationFrame;
2968
2969 mDrawingState.modified = true;
2970 setTransactionFlags(eTransactionNeeded);
2971 return true;
2972}
2973
2974// Translate destination frame into scale and position. If a destination frame is not set, use the
2975// provided scale and position
2976bool Layer::updateGeometry() {
2977 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2978 mDrawingState.destinationFrame.isEmpty()) {
2979 // If destination frame is not set, use the requested transform set via
2980 // Layer::setPosition and Layer::setMatrix.
2981 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2982 }
2983
2984 Rect destRect = mDrawingState.destinationFrame;
2985 int32_t destW = destRect.width();
2986 int32_t destH = destRect.height();
2987 if (destRect.left < 0) {
2988 destRect.left = 0;
2989 destRect.right = destW;
2990 }
2991 if (destRect.top < 0) {
2992 destRect.top = 0;
2993 destRect.bottom = destH;
2994 }
2995
2996 if (!mDrawingState.buffer) {
2997 ui::Transform t;
2998 t.set(destRect.left, destRect.top);
2999 return assignTransform(&mDrawingState.transform, t);
3000 }
3001
3002 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3003 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3004 // Undo any transformations on the buffer.
3005 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3006 std::swap(bufferWidth, bufferHeight);
3007 }
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003008 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003009 if (mDrawingState.transformToDisplayInverse) {
3010 if (invTransform & ui::Transform::ROT_90) {
3011 std::swap(bufferWidth, bufferHeight);
3012 }
3013 }
3014
3015 float sx = destW / static_cast<float>(bufferWidth);
3016 float sy = destH / static_cast<float>(bufferHeight);
3017 ui::Transform t;
3018 t.set(sx, 0, 0, sy);
3019 t.set(destRect.left, destRect.top);
3020 return assignTransform(&mDrawingState.transform, t);
3021}
3022
3023bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3024 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3025 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3026 return false;
3027 }
3028
3029 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3030
3031 mDrawingState.sequence++;
3032 mDrawingState.modified = true;
3033 setTransactionFlags(eTransactionNeeded);
3034
3035 return true;
3036}
3037
3038bool Layer::setPosition(float x, float y) {
3039 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3040 return false;
3041 }
3042
3043 mRequestedTransform.set(x, y);
3044
3045 mDrawingState.sequence++;
3046 mDrawingState.modified = true;
3047 setTransactionFlags(eTransactionNeeded);
3048
3049 return true;
3050}
3051
Dorin Drimuse5374e52023-08-02 17:52:43 +00003052void Layer::releasePreviousBuffer() {
3053 mReleasePreviousBuffer = true;
3054 if (!mBufferInfo.mBuffer ||
3055 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3056 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3057 // If mDrawingState has a buffer, and we are about to update again
3058 // before swapping to drawing state, then the first buffer will be
3059 // dropped and we should decrement the pending buffer count and
3060 // call any release buffer callbacks if set.
3061 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3062 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3063 mDrawingState.acquireFence);
3064 decrementPendingBufferCount();
3065 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3066 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3067 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX, systemTime());
3068 mDrawingState.bufferSurfaceFrameTX.reset();
3069 }
3070 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3071 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3072 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3073 mLastClientCompositionFence);
3074 mLastClientCompositionFence = nullptr;
3075 }
3076}
3077
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003078void Layer::resetDrawingStateBufferInfo() {
3079 mDrawingState.producerId = 0;
3080 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +00003081 mDrawingState.previousFrameNumber = 0;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003082 mDrawingState.releaseBufferListener = nullptr;
3083 mDrawingState.buffer = nullptr;
3084 mDrawingState.acquireFence = sp<Fence>::make(-1);
3085 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3086 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3087 mDrawingState.releaseBufferEndpoint = nullptr;
3088}
3089
Patrick Williamsbb25f802022-08-30 23:02:34 +00003090bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3091 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
Nergi Rahardi39f510f2024-05-23 15:16:54 +09003092 bool isAutoTimestamp, const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003093 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003094
3095 const bool frameNumberChanged =
3096 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3097 const uint64_t frameNumber =
3098 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003099 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003100
3101 if (mDrawingState.buffer) {
Dorin Drimuse5374e52023-08-02 17:52:43 +00003102 releasePreviousBuffer();
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003103 } else if (buffer) {
Vishnu Nairc09c0232023-03-02 03:22:35 +00003104 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3105 // we don't want to incorrectly classify a frame if we miss the desired present time.
3106 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003107 }
3108
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003109 mDrawingState.desiredPresentTime = desiredPresentTime;
3110 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3111 mDrawingState.latchedVsyncId = info.vsyncId;
Ady Abraham55269162023-05-09 11:26:06 -07003112 mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003113 mDrawingState.modified = true;
3114 if (!buffer) {
3115 resetDrawingStateBufferInfo();
3116 setTransactionFlags(eTransactionNeeded);
3117 mDrawingState.bufferSurfaceFrameTX = nullptr;
3118 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3119 return true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003120 } else {
3121 // release sideband stream if it exists and a non null buffer is being set
3122 if (mDrawingState.sidebandStream != nullptr) {
Dorin Drimus66ed1c42023-09-27 13:10:16 +00003123 setSidebandStream(nullptr, info, postTime);
Dorin Drimuse5374e52023-08-02 17:52:43 +00003124 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003125 }
3126
Vishnu Naird1f74982023-06-15 20:16:51 -07003127 if ((mDrawingState.producerId > bufferData.producerId) ||
3128 ((mDrawingState.producerId == bufferData.producerId) &&
3129 (mDrawingState.frameNumber > frameNumber))) {
3130 ALOGE("Out of order buffers detected for %s producedId=%d frameNumber=%" PRIu64
3131 " -> producedId=%d frameNumber=%" PRIu64,
3132 getDebugName(), mDrawingState.producerId, mDrawingState.frameNumber,
3133 bufferData.producerId, frameNumber);
3134 TransactionTraceWriter::getInstance().invoke("out_of_order_buffers_", /*overwrite=*/false);
3135 }
3136
liulijuneb489f62022-10-17 22:02:14 +08003137 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -07003138 mDrawingState.barrierProducerId =
3139 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003140 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -07003141 mDrawingState.barrierFrameNumber =
3142 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
3143
Patrick Williamsbb25f802022-08-30 23:02:34 +00003144 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3145 mDrawingState.buffer = std::move(buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003146 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3147 ? bufferData.acquireFence
3148 : Fence::NO_FENCE;
3149 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3150 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3151 // We latched this buffer unsiganled, so we need to pass the acquire fence
3152 // on the callback instead of just the acquire time, since it's unknown at
3153 // this point.
3154 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3155 } else {
3156 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3157 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003158 setTransactionFlags(eTransactionNeeded);
3159
3160 const int32_t layerId = getSequence();
3161 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3162 mOwnerUid, postTime, getGameMode());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003163
Patrick Williamsbb25f802022-08-30 23:02:34 +00003164 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3165
Nergi Rahardi39f510f2024-05-23 15:16:54 +09003166 if (bufferData.dequeueTime > 0) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003167 const uint64_t bufferId = mDrawingState.buffer->getId();
3168 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
Nergi Rahardi39f510f2024-05-23 15:16:54 +09003169 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber,
3170 bufferData.dequeueTime,
Patrick Williamsbb25f802022-08-30 23:02:34 +00003171 FrameTracer::FrameEvent::DEQUEUE);
3172 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3173 FrameTracer::FrameEvent::QUEUE);
3174 }
3175
3176 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
Arthur Hungc70bee22023-06-02 01:35:52 +00003177
3178 // If the layer had been updated a TextureView, this would make sure the present time could be
3179 // same to TextureView update when it's a small dirty, and get the correct heuristic rate.
Jerry Chang36678002023-11-29 16:56:17 +00003180 if (mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00003181 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3182 mUsedVsyncIdForRefreshRateSelection = true;
3183 }
3184 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003185 return true;
3186}
3187
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003188void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3189 mDrawingState.desiredPresentTime = desiredPresentTime;
3190 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3191}
3192
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003193void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps, nsecs_t now) {
Ady Abraham55269162023-05-09 11:26:06 -07003194 ATRACE_CALL();
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003195 const nsecs_t presentTime = [&] {
Ady Abraham55269162023-05-09 11:26:06 -07003196 if (!mDrawingState.isAutoTimestamp) {
3197 ATRACE_FORMAT_INSTANT("desiredPresentTime");
3198 return mDrawingState.desiredPresentTime;
3199 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003200
Ady Abraham55269162023-05-09 11:26:06 -07003201 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3202 const auto prediction =
3203 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3204 mDrawingState.latchedVsyncId);
3205 if (prediction.has_value()) {
3206 ATRACE_FORMAT_INSTANT("predictedPresentTime");
Arthur Hungc70bee22023-06-02 01:35:52 +00003207 mMaxTimeForUseVsyncId = prediction->presentTime +
3208 scheduler::LayerHistory::kMaxPeriodForHistory.count();
Ady Abraham55269162023-05-09 11:26:06 -07003209 return prediction->presentTime;
3210 }
3211 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003212
Jerry Chang36678002023-11-29 16:56:17 +00003213 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00003214 return static_cast<nsecs_t>(0);
3215 }
3216
3217 // If the layer is not an application and didn't set an explicit rate or desiredPresentTime,
3218 // return "0" to tell the layer history that it will use the max refresh rate without
3219 // calculating the adaptive rate.
3220 if (mWindowType != WindowInfo::Type::APPLICATION &&
3221 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
3222 return static_cast<nsecs_t>(0);
3223 }
3224
3225 // Return the valid present time only when the layer potentially updated a TextureView so
3226 // LayerHistory could heuristically calculate the rate if the UI is continually updating.
3227 if (mUsedVsyncIdForRefreshRateSelection) {
3228 const auto prediction =
3229 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3230 mDrawingState.latchedVsyncId);
3231 if (prediction.has_value()) {
3232 if (mMaxTimeForUseVsyncId >= prediction->presentTime) {
3233 return prediction->presentTime;
3234 }
3235 mUsedVsyncIdForRefreshRateSelection = false;
3236 }
3237 }
3238
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003239 return static_cast<nsecs_t>(0);
3240 }();
Ady Abraham55269162023-05-09 11:26:06 -07003241
3242 if (ATRACE_ENABLED() && presentTime > 0) {
3243 const auto presentIn = TimePoint::fromNs(presentTime) - TimePoint::now();
3244 ATRACE_FORMAT_INSTANT("presentIn %s", to_string(presentIn).c_str());
3245 }
3246
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003247 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003248 scheduler::LayerHistory::LayerUpdateType::Buffer);
3249}
3250
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003251void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps, nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003252 const nsecs_t presentTime =
3253 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003254 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003255 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3256}
3257
Patrick Williamsbb25f802022-08-30 23:02:34 +00003258bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003259 if (mDrawingState.dataspace == dataspace) return false;
3260 mDrawingState.dataspace = dataspace;
3261 mDrawingState.modified = true;
3262 setTransactionFlags(eTransactionNeeded);
3263 return true;
3264}
3265
John Reck68796592023-01-25 13:47:12 -05003266bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07003267 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3268 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05003269 return false;
Sally Qi963049b2023-03-23 14:06:21 -07003270 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3271 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05003272 mDrawingState.modified = true;
3273 setTransactionFlags(eTransactionNeeded);
3274 return true;
3275}
3276
Alec Mouri1b0d4e12024-02-12 22:27:19 +00003277bool Layer::setDesiredHdrHeadroom(float desiredRatio) {
3278 if (mDrawingState.desiredHdrSdrRatio == desiredRatio) return false;
3279 mDrawingState.desiredHdrSdrRatio = desiredRatio;
3280 mDrawingState.modified = true;
3281 setTransactionFlags(eTransactionNeeded);
3282 return true;
3283}
3284
Alec Mourif4af03e2023-02-11 00:25:24 +00003285bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3286 if (mDrawingState.cachingHint == cachingHint) return false;
3287 mDrawingState.cachingHint = cachingHint;
3288 mDrawingState.modified = true;
3289 setTransactionFlags(eTransactionNeeded);
3290 return true;
3291}
3292
Patrick Williamsbb25f802022-08-30 23:02:34 +00003293bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3294 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3295 mDrawingState.hdrMetadata = hdrMetadata;
3296 mDrawingState.modified = true;
3297 setTransactionFlags(eTransactionNeeded);
3298 return true;
3299}
3300
3301bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003302 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003303 mDrawingState.surfaceDamageRegion = surfaceDamage;
3304 mDrawingState.modified = true;
3305 setTransactionFlags(eTransactionNeeded);
Arthur Hung69f95222023-10-04 07:39:02 +00003306 setIsSmallDirty(surfaceDamage, getTransform());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003307 return true;
3308}
3309
3310bool Layer::setApi(int32_t api) {
3311 if (mDrawingState.api == api) return false;
3312 mDrawingState.api = api;
3313 mDrawingState.modified = true;
3314 setTransactionFlags(eTransactionNeeded);
3315 return true;
3316}
3317
Dorin Drimuse5374e52023-08-02 17:52:43 +00003318bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream, const FrameTimelineInfo& info,
3319 nsecs_t postTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003320 if (mDrawingState.sidebandStream == sidebandStream) return false;
3321
3322 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3323 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3324 } else if (sidebandStream != nullptr) {
3325 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3326 }
3327
3328 mDrawingState.sidebandStream = sidebandStream;
3329 mDrawingState.modified = true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003330 if (sidebandStream != nullptr && mDrawingState.buffer != nullptr) {
3331 releasePreviousBuffer();
3332 resetDrawingStateBufferInfo();
3333 mDrawingState.bufferSurfaceFrameTX = nullptr;
3334 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3335 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003336 setTransactionFlags(eTransactionNeeded);
3337 if (!mSidebandStreamChanged.exchange(true)) {
3338 // mSidebandStreamChanged was false
3339 mFlinger->onLayerUpdate();
3340 }
3341 return true;
3342}
3343
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003344bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3345 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003346 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3347 if (handles.empty()) {
3348 mReleasePreviousBuffer = false;
3349 return false;
3350 }
3351
Pascal Muetschard81cef292023-02-06 12:18:52 +01003352 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003353 for (const auto& handle : handles) {
3354 // If this transaction set a buffer on this layer, release its previous buffer
3355 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3356
3357 // If this layer will be presented in this frame
3358 if (willPresent) {
3359 // If this transaction set an acquire fence on this layer, set its acquire time
3360 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3361 handle->frameNumber = mDrawingState.frameNumber;
Alec Mouri21d94322023-10-17 19:51:39 +00003362 handle->previousFrameNumber = mDrawingState.previousFrameNumber;
Melody Hsu793f8362024-01-08 20:00:35 +00003363 if (FlagManager::getInstance().ce_fence_promise() &&
Alec Mouri9892aac2023-12-11 21:16:59 +00003364 mPreviousReleaseBufferEndpoint == handle->listener) {
Melody Hsue4ef87f2024-03-26 23:54:45 +00003365 // Add fence from previous screenshot now so that it can be dispatched to the
Alec Mouri9892aac2023-12-11 21:16:59 +00003366 // client.
Melody Hsue4ef87f2024-03-26 23:54:45 +00003367 for (auto& [_, future] : mAdditionalPreviousReleaseFences) {
3368 handle->previousReleaseFences.emplace_back(std::move(future));
Alec Mouri9892aac2023-12-11 21:16:59 +00003369 }
3370 mAdditionalPreviousReleaseFences.clear();
Melody Hsu793f8362024-01-08 20:00:35 +00003371 } else if (FlagManager::getInstance().screenshot_fence_preservation() &&
3372 mPreviousReleaseBufferEndpoint == handle->listener) {
3373 // Add fences from previous screenshots now so that they can be dispatched to the
3374 // client.
3375 for (const auto& futureAndContinution : mPreviousReleaseFenceAndContinuations) {
3376 handle->previousSharedReleaseFences.emplace_back(futureAndContinution.chain());
3377 }
3378 mPreviousReleaseFenceAndContinuations.clear();
Alec Mouri9892aac2023-12-11 21:16:59 +00003379 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003380 // Store so latched time and release fence can be set
3381 mDrawingState.callbackHandles.push_back(handle);
3382
3383 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003384 // Queue this handle to be notified below.
3385 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003386 }
3387 }
3388
Pascal Muetschard81cef292023-02-06 12:18:52 +01003389 if (!remainingHandles.empty()) {
3390 // Notify the transaction completed threads these handles are done. These are only the
3391 // handles that were not added to the mDrawingState, which will be notified later.
Pascal Mütschardd56514e2024-05-24 17:37:13 +02003392 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles);
Pascal Muetschard81cef292023-02-06 12:18:52 +01003393 }
3394
Patrick Williamsbb25f802022-08-30 23:02:34 +00003395 mReleasePreviousBuffer = false;
3396 mCallbackHandleAcquireTimeOrFence = -1;
3397
3398 return willPresent;
3399}
3400
3401Rect Layer::getBufferSize(const State& /*s*/) const {
3402 // for buffer state layers we use the display frame size as the buffer size.
3403
3404 if (mBufferInfo.mBuffer == nullptr) {
3405 return Rect::INVALID_RECT;
3406 }
3407
3408 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3409 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3410
3411 // Undo any transformations on the buffer and return the result.
3412 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3413 std::swap(bufWidth, bufHeight);
3414 }
3415
3416 if (getTransformToDisplayInverse()) {
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003417 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003418 if (invTransform & ui::Transform::ROT_90) {
3419 std::swap(bufWidth, bufHeight);
3420 }
3421 }
3422
3423 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3424}
3425
3426FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3427 if (mBufferInfo.mBuffer == nullptr) {
3428 return parentBounds;
3429 }
3430
3431 return getBufferSize(getDrawingState()).toFloatRect();
3432}
3433
3434bool Layer::fenceHasSignaled() const {
3435 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3436 return true;
3437 }
3438
3439 const bool fenceSignaled =
3440 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3441 if (!fenceSignaled) {
3442 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3443 TimeStats::LatchSkipReason::LateAcquire);
3444 }
3445
3446 return fenceSignaled;
3447}
3448
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003449void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003450 for (const auto& handle : mDrawingState.callbackHandles) {
3451 handle->refreshStartTime = refreshStartTime;
3452 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003453}
3454
3455void Layer::setAutoRefresh(bool autoRefresh) {
3456 mDrawingState.autoRefresh = autoRefresh;
3457}
3458
3459bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3460 // 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 +00003461 auto* snapshot = editLayerSnapshot();
3462 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003463
3464 if (mSidebandStreamChanged.exchange(false)) {
3465 const State& s(getDrawingState());
3466 // mSidebandStreamChanged was true
3467 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003468 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003469 if (mSidebandStream != nullptr) {
3470 setTransactionFlags(eTransactionNeeded);
3471 mFlinger->setTransactionFlags(eTraversalNeeded);
3472 }
3473 recomputeVisibleRegions = true;
3474
3475 return true;
3476 }
3477 return false;
3478}
3479
3480bool Layer::hasFrameUpdate() const {
3481 const State& c(getDrawingState());
3482 return (mDrawingStateModified || mDrawingState.modified) &&
3483 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3484}
3485
Vishnu Naird47bcee2023-02-24 18:08:51 +00003486void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003487 const State& s(getDrawingState());
3488
3489 if (!s.buffer) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003490 if (bgColorOnly || mBufferInfo.mBuffer) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003491 for (auto& handle : mDrawingState.callbackHandles) {
3492 handle->latchTime = latchTime;
3493 }
3494 }
3495 return;
3496 }
3497
3498 for (auto& handle : mDrawingState.callbackHandles) {
3499 if (handle->frameNumber == mDrawingState.frameNumber) {
3500 handle->latchTime = latchTime;
3501 }
3502 }
3503
3504 const int32_t layerId = getSequence();
3505 const uint64_t bufferId = mDrawingState.buffer->getId();
3506 const uint64_t frameNumber = mDrawingState.frameNumber;
3507 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3508 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3509 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3510
3511 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3512 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3513 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3514 FrameTracer::FrameEvent::LATCH);
3515
3516 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3517 if (bufferSurfaceFrame != nullptr &&
3518 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3519 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3520 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3521 // are processing the next state.
3522 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3523 mDrawingState.acquireFenceTime->getSignalTime(),
3524 latchTime);
3525 mDrawingState.bufferSurfaceFrameTX.reset();
3526 }
3527
3528 std::deque<sp<CallbackHandle>> remainingHandles;
3529 mFlinger->getTransactionCallbackInvoker()
3530 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3531 mDrawingState.callbackHandles = remainingHandles;
3532
3533 mDrawingStateModified = false;
3534}
3535
3536void Layer::gatherBufferInfo() {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003537 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3538 mPreviousReleaseBufferEndpoint = mBufferInfo.mReleaseBufferEndpoint;
3539 if (!mDrawingState.buffer) {
3540 mBufferInfo = {};
3541 return;
3542 }
3543
3544 if ((!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer))) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003545 decrementPendingBufferCount();
3546 }
3547
Patrick Williamsbb25f802022-08-30 23:02:34 +00003548 mBufferInfo.mBuffer = mDrawingState.buffer;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003549 mBufferInfo.mReleaseBufferEndpoint = mDrawingState.releaseBufferEndpoint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003550 mBufferInfo.mFence = mDrawingState.acquireFence;
3551 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3552 mBufferInfo.mPixelFormat =
3553 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3554 mBufferInfo.mFrameLatencyNeeded = true;
3555 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3556 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3557 mBufferInfo.mFence = mDrawingState.acquireFence;
3558 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3559 auto lastDataspace = mBufferInfo.mDataspace;
3560 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003561 if (mBufferInfo.mBuffer != nullptr) {
3562 auto& mapper = GraphicBufferMapper::get();
3563 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
3564 // and don't need to possibly remaps buffers.
3565 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
3566 status_t err = OK;
3567 {
3568 ATRACE_NAME("getDataspace");
3569 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
3570 }
3571 if (err != OK || dataspace != mBufferInfo.mDataspace) {
3572 {
3573 ATRACE_NAME("setDataspace");
3574 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
3575 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
3576 }
3577
3578 // Some GPU drivers may cache gralloc metadata which means before we composite we need
3579 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
3580 // compatible with old vendors, with a ticking clock.
3581 static const int32_t kVendorVersion =
Alec Mouri8a06fb72023-11-16 22:07:13 +00003582 base::GetIntProperty("ro.board.api_level", __ANDROID_API_FUTURE__);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003583 if (const auto format =
3584 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
3585 mBufferInfo.mBuffer->getPixelFormat());
3586 err == OK && kVendorVersion < __ANDROID_API_U__ &&
3587 (format ==
3588 aidl::android::hardware::graphics::common::PixelFormat::
3589 IMPLEMENTATION_DEFINED ||
3590 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
3591 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
3592 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
3593 mBufferInfo.mBuffer->remapBuffer();
3594 }
3595 }
3596 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003597 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003598 mFlinger->mHdrLayerInfoChanged = true;
3599 }
Sally Qi963049b2023-03-23 14:06:21 -07003600 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3601 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05003602 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003603 }
3604 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3605 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3606 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3607 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3608 mBufferInfo.mApi = mDrawingState.api;
3609 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003610}
3611
3612Rect Layer::computeBufferCrop(const State& s) {
3613 if (s.buffer && !s.bufferCrop.isEmpty()) {
3614 Rect bufferCrop;
3615 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3616 return bufferCrop;
3617 } else if (s.buffer) {
3618 return s.buffer->getBounds();
3619 } else {
3620 return s.bufferCrop;
3621 }
3622}
3623
Melody Hsu12ecd082024-04-17 19:03:13 +00003624sp<Layer> Layer::createClone() {
Kean Mariotti4ba343c2023-04-19 13:31:02 +00003625 surfaceflinger::LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0,
3626 LayerMetadata());
Patrick Williams83f36b22022-09-14 17:57:35 +00003627 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003628 return layer;
3629}
3630
Patrick Williamsbb25f802022-08-30 23:02:34 +00003631void Layer::decrementPendingBufferCount() {
3632 int32_t pendingBuffers = --mPendingBufferTransactions;
3633 tracePendingBufferCount(pendingBuffers);
3634}
3635
3636void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3637 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3638}
3639
3640/*
3641 * We don't want to send the layer's transform to input, but rather the
3642 * parent's transform. This is because Layer's transform is
3643 * information about how the buffer is placed on screen. The parent's
3644 * transform makes more sense to send since it's information about how the
3645 * layer is placed on screen. This transform is used by input to determine
3646 * how to go from screen space back to window space.
3647 */
3648ui::Transform Layer::getInputTransform() const {
3649 if (!hasBufferOrSidebandStream()) {
3650 return getTransform();
3651 }
3652 sp<Layer> parent = mDrawingParent.promote();
3653 if (parent == nullptr) {
3654 return ui::Transform();
3655 }
3656
3657 return parent->getTransform();
3658}
3659
3660/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003661 * Returns the bounds used to fill the input frame and the touchable region.
3662 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003663 * Similar to getInputTransform, we need to update the bounds to include the transform.
3664 * This is because bounds don't include the buffer transform, where the input assumes
3665 * that's already included.
3666 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003667std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3668 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3669 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3670 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3671 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3672 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003673 }
3674
Vishnu Nairfed7c122023-03-18 01:54:43 +00003675 bool inputBoundsValid = croppedBufferSize.isValid();
3676 if (!inputBoundsValid) {
3677 /**
3678 * Input bounds are based on the layer crop or buffer size. But if we are using
3679 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3680 * we can use the parent bounds as the input bounds if the layer does not have buffer
3681 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3682 * use the parent bounds. A layer without a buffer can get input. So when a window is
3683 * initially added, its touchable region can fill its parent layer bounds and that can
3684 * have negative consequences.
3685 */
3686 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003687 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003688
3689 // Clamp surface inset to the input bounds.
3690 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3691 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3692 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3693
3694 // Apply the insets to the input bounds.
3695 inputBounds.left += xSurfaceInset;
3696 inputBounds.top += ySurfaceInset;
3697 inputBounds.right -= xSurfaceInset;
3698 inputBounds.bottom -= ySurfaceInset;
3699
3700 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003701}
3702
Ady Abraham005398b2023-06-05 13:59:41 -07003703bool Layer::isSimpleBufferUpdate(const layer_state_t& s) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003704 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3705
3706 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3707 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3708 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
Ady Abrahambb1ad762024-03-27 18:31:28 -07003709 layer_state_t::eLayerStackChanged | layer_state_t::eReparent |
3710 (FlagManager::getInstance().latch_unsignaled_with_auto_refresh_changed()
3711 ? 0
3712 : layer_state_t::eAutoRefreshChanged);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003713
Patrick Williamsbb25f802022-08-30 23:02:34 +00003714 if ((s.what & requiredFlags) != requiredFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003715 ATRACE_FORMAT_INSTANT("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3716 (s.what | requiredFlags) & ~s.what);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003717 return false;
3718 }
3719
3720 if (s.what & deniedFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003721 ATRACE_FORMAT_INSTANT("%s: false [has denied flags 0x%" PRIx64 "]", __func__,
3722 s.what & deniedFlags);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003723 return false;
3724 }
3725
Patrick Williamsbb25f802022-08-30 23:02:34 +00003726 if (s.what & layer_state_t::ePositionChanged) {
3727 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
Ady Abraham005398b2023-06-05 13:59:41 -07003728 ATRACE_FORMAT_INSTANT("%s: false [ePositionChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003729 return false;
3730 }
3731 }
3732
3733 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003734 if (mDrawingState.color.a != s.color.a) {
Ady Abraham005398b2023-06-05 13:59:41 -07003735 ATRACE_FORMAT_INSTANT("%s: false [eAlphaChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003736 return false;
3737 }
3738 }
3739
3740 if (s.what & layer_state_t::eColorTransformChanged) {
3741 if (mDrawingState.colorTransform != s.colorTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003742 ATRACE_FORMAT_INSTANT("%s: false [eColorTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003743 return false;
3744 }
3745 }
3746
3747 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003748 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Ady Abraham005398b2023-06-05 13:59:41 -07003749 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundColorChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003750 return false;
3751 }
3752 }
3753
3754 if (s.what & layer_state_t::eMatrixChanged) {
3755 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3756 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3757 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3758 mRequestedTransform.dsdy() != s.matrix.dsdy) {
Ady Abraham005398b2023-06-05 13:59:41 -07003759 ATRACE_FORMAT_INSTANT("%s: false [eMatrixChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003760 return false;
3761 }
3762 }
3763
3764 if (s.what & layer_state_t::eCornerRadiusChanged) {
3765 if (mDrawingState.cornerRadius != s.cornerRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003766 ATRACE_FORMAT_INSTANT("%s: false [eCornerRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003767 return false;
3768 }
3769 }
3770
3771 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3772 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
Ady Abraham005398b2023-06-05 13:59:41 -07003773 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003774 return false;
3775 }
3776 }
3777
Vishnu Nairbbceb462022-10-10 04:52:13 +00003778 if (s.what & layer_state_t::eBufferTransformChanged) {
3779 if (mDrawingState.bufferTransform != s.bufferTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003780 ATRACE_FORMAT_INSTANT("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003781 return false;
3782 }
3783 }
3784
3785 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3786 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
Ady Abraham005398b2023-06-05 13:59:41 -07003787 ATRACE_FORMAT_INSTANT("%s: false [eTransformToDisplayInverseChanged changed]",
3788 __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003789 return false;
3790 }
3791 }
3792
3793 if (s.what & layer_state_t::eCropChanged) {
3794 if (mDrawingState.crop != s.crop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003795 ATRACE_FORMAT_INSTANT("%s: false [eCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003796 return false;
3797 }
3798 }
3799
3800 if (s.what & layer_state_t::eDataspaceChanged) {
3801 if (mDrawingState.dataspace != s.dataspace) {
Ady Abraham005398b2023-06-05 13:59:41 -07003802 ATRACE_FORMAT_INSTANT("%s: false [eDataspaceChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003803 return false;
3804 }
3805 }
3806
3807 if (s.what & layer_state_t::eHdrMetadataChanged) {
3808 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
Ady Abraham005398b2023-06-05 13:59:41 -07003809 ATRACE_FORMAT_INSTANT("%s: false [eHdrMetadataChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003810 return false;
3811 }
3812 }
3813
3814 if (s.what & layer_state_t::eSidebandStreamChanged) {
3815 if (mDrawingState.sidebandStream != s.sidebandStream) {
Ady Abraham005398b2023-06-05 13:59:41 -07003816 ATRACE_FORMAT_INSTANT("%s: false [eSidebandStreamChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003817 return false;
3818 }
3819 }
3820
3821 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3822 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
Ady Abraham005398b2023-06-05 13:59:41 -07003823 ATRACE_FORMAT_INSTANT("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003824 return false;
3825 }
3826 }
3827
3828 if (s.what & layer_state_t::eShadowRadiusChanged) {
3829 if (mDrawingState.shadowRadius != s.shadowRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003830 ATRACE_FORMAT_INSTANT("%s: false [eShadowRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003831 return false;
3832 }
3833 }
3834
3835 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3836 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
Ady Abraham005398b2023-06-05 13:59:41 -07003837 ATRACE_FORMAT_INSTANT("%s: false [eFixedTransformHintChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003838 return false;
3839 }
3840 }
3841
3842 if (s.what & layer_state_t::eTrustedOverlayChanged) {
Vishnu Nair9e0017e2024-05-22 19:02:44 +00003843 if (mDrawingState.isTrustedOverlay != (s.trustedOverlay == gui::TrustedOverlay::ENABLED)) {
Ady Abraham005398b2023-06-05 13:59:41 -07003844 ATRACE_FORMAT_INSTANT("%s: false [eTrustedOverlayChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003845 return false;
3846 }
3847 }
3848
3849 if (s.what & layer_state_t::eStretchChanged) {
3850 StretchEffect temp = s.stretchEffect;
3851 temp.sanitize();
3852 if (mDrawingState.stretchEffect != temp) {
Ady Abraham005398b2023-06-05 13:59:41 -07003853 ATRACE_FORMAT_INSTANT("%s: false [eStretchChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003854 return false;
3855 }
3856 }
3857
3858 if (s.what & layer_state_t::eBufferCropChanged) {
3859 if (mDrawingState.bufferCrop != s.bufferCrop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003860 ATRACE_FORMAT_INSTANT("%s: false [eBufferCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003861 return false;
3862 }
3863 }
3864
3865 if (s.what & layer_state_t::eDestinationFrameChanged) {
3866 if (mDrawingState.destinationFrame != s.destinationFrame) {
Ady Abraham005398b2023-06-05 13:59:41 -07003867 ATRACE_FORMAT_INSTANT("%s: false [eDestinationFrameChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003868 return false;
3869 }
3870 }
3871
3872 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3873 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
Ady Abraham005398b2023-06-05 13:59:41 -07003874 ATRACE_FORMAT_INSTANT("%s: false [eDimmingEnabledChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003875 return false;
3876 }
3877 }
3878
John Reck68796592023-01-25 13:47:12 -05003879 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07003880 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
3881 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
Ady Abraham005398b2023-06-05 13:59:41 -07003882 ATRACE_FORMAT_INSTANT("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05003883 return false;
3884 }
3885 }
3886
Alec Mouri1b0d4e12024-02-12 22:27:19 +00003887 if (s.what & layer_state_t::eDesiredHdrHeadroomChanged) {
3888 if (mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
3889 ATRACE_FORMAT_INSTANT("%s: false [eDesiredHdrHeadroomChanged changed]", __func__);
3890 return false;
3891 }
3892 }
3893
Patrick Williamsbb25f802022-08-30 23:02:34 +00003894 return true;
3895}
3896
Vishnu Naire14c6b32022-08-06 04:20:15 +00003897sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003898 // 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 +00003899 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003900}
3901
Vishnu Naire14c6b32022-08-06 04:20:15 +00003902const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003903 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003904}
3905
Vishnu Naire14c6b32022-08-06 04:20:15 +00003906LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003907 return mSnapshot.get();
3908}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003909
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003910std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3911 return std::move(mSnapshot);
3912}
3913
3914void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3915 mSnapshot = std::move(snapshot);
3916}
3917
Patrick Williamsbb25f802022-08-30 23:02:34 +00003918const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003919 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003920}
3921
Patrick Williams7584c6a2022-10-29 02:10:58 +00003922sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Lloyd Pique70ddc672024-04-30 18:20:40 -07003923 auto result = mFlinger->getFactory().createLayerFE(mName, this);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003924 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3925 return result;
3926}
3927
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003928sp<LayerFE> Layer::getCompositionEngineLayerFE(
3929 const frontend::LayerHierarchy::TraversalPath& path) {
3930 for (auto& [p, layerFE] : mLayerFEs) {
3931 if (p == path) {
3932 return layerFE;
3933 }
3934 }
Lloyd Pique70ddc672024-04-30 18:20:40 -07003935 auto layerFE = mFlinger->getFactory().createLayerFE(mName, this);
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003936 mLayerFEs.emplace_back(path, layerFE);
3937 return layerFE;
3938}
3939
Patrick Williamsbb25f802022-08-30 23:02:34 +00003940void Layer::useSurfaceDamage() {
3941 if (mFlinger->mForceFullDamage) {
3942 surfaceDamageRegion = Region::INVALID_REGION;
3943 } else {
3944 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3945 }
3946}
3947
3948void Layer::useEmptyDamage() {
3949 surfaceDamageRegion.clear();
3950}
3951
3952bool Layer::isOpaque(const Layer::State& s) const {
3953 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3954 // layer's opaque flag.
3955 if (!hasSomethingToDraw()) {
3956 return false;
3957 }
3958
3959 // if the layer has the opaque flag, then we're always opaque
3960 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3961 return true;
3962 }
3963
3964 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003965 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003966 return true;
3967 }
3968
3969 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3970 return fillsColor() && getAlpha() == 1.0_hf;
3971}
3972
3973bool Layer::canReceiveInput() const {
3974 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3975}
3976
3977bool Layer::isVisible() const {
3978 if (!hasSomethingToDraw()) {
3979 return false;
3980 }
3981
3982 if (isHiddenByPolicy()) {
3983 return false;
3984 }
3985
3986 return getAlpha() > 0.0f || hasBlur();
3987}
3988
Leon Scroggins III5b581492023-10-31 14:29:41 -04003989void Layer::onCompositionPresented(const DisplayDevice* display,
3990 const std::shared_ptr<FenceTime>& glDoneFence,
3991 const std::shared_ptr<FenceTime>& presentFence,
3992 const CompositorTiming& compositorTiming) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003993 // mFrameLatencyNeeded is true when a new frame was latched for the
3994 // composition.
3995 if (!mBufferInfo.mFrameLatencyNeeded) return;
3996
3997 for (const auto& handle : mDrawingState.callbackHandles) {
3998 handle->gpuCompositionDoneFence = glDoneFence;
3999 handle->compositorTiming = compositorTiming;
4000 }
4001
4002 // Update mFrameTracker.
4003 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
4004 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
4005
4006 const int32_t layerId = getSequence();
4007 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
4008
4009 const auto outputLayer = findOutputLayerForDisplay(display);
4010 if (outputLayer && outputLayer->requiresClientComposition()) {
4011 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
4012 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4013 clientCompositionTimestamp,
4014 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
4015 // Update the SurfaceFrames in the drawing state
4016 if (mDrawingState.bufferSurfaceFrameTX) {
4017 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
4018 }
4019 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
4020 surfaceFrame->setGpuComposition();
4021 }
4022 }
4023
4024 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
4025 if (frameReadyFence->isValid()) {
4026 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
4027 } else {
4028 // There was no fence for this frame, so assume that it was ready
4029 // to be presented at the desired present time.
4030 mFrameTracker.setFrameReadyTime(desiredPresentTime);
4031 }
4032
4033 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08004034 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004035 const std::optional<Fps> renderRate =
4036 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
4037
Alec Mouri7c1d8b52023-08-29 20:14:46 +00004038 const auto vote = frameRateToSetFrameRateVotePayload(getFrameRateForLayerTree());
Patrick Williamsbb25f802022-08-30 23:02:34 +00004039 const auto gameMode = getGameMode();
4040
4041 if (presentFence->isValid()) {
4042 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
4043 refreshRate, renderRate, vote, gameMode);
4044 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4045 presentFence,
4046 FrameTracer::FrameEvent::PRESENT_FENCE);
4047 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
4048 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
4049 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04004050 // The HWC doesn't support present fences, so use the present timestamp instead.
4051 const nsecs_t presentTimestamp =
4052 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
4053
4054 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
4055 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
4056 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
4057
Patrick Williamsbb25f802022-08-30 23:02:34 +00004058 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
4059 refreshRate, renderRate, vote, gameMode);
4060 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
4061 mCurrentFrameNumber, actualPresentTime,
4062 FrameTracer::FrameEvent::PRESENT_FENCE);
4063 mFrameTracker.setActualPresentTime(actualPresentTime);
4064 }
4065 }
4066
4067 mFrameTracker.advanceFrame();
4068 mBufferInfo.mFrameLatencyNeeded = false;
4069}
4070
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004071bool Layer::willReleaseBufferOnLatch() const {
4072 return !mDrawingState.buffer && mBufferInfo.mBuffer;
4073}
4074
Patrick Williamsbb25f802022-08-30 23:02:34 +00004075bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00004076 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
4077 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
4078}
4079
4080bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004081 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
4082 getDrawingState().frameNumber);
4083
4084 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
4085
4086 if (refreshRequired) {
4087 return refreshRequired;
4088 }
4089
4090 // If the head buffer's acquire fence hasn't signaled yet, return and
4091 // try again later
4092 if (!fenceHasSignaled()) {
4093 ATRACE_NAME("!fenceHasSignaled()");
4094 mFlinger->onLayerUpdate();
4095 return false;
4096 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00004097 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004098
4099 // Capture the old state of the layer for comparisons later
4100 BufferInfo oldBufferInfo = mBufferInfo;
4101 const bool oldOpacity = isOpaque(mDrawingState);
4102 mPreviousFrameNumber = mCurrentFrameNumber;
4103 mCurrentFrameNumber = mDrawingState.frameNumber;
4104 gatherBufferInfo();
4105
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004106 if (mBufferInfo.mBuffer) {
4107 // We latched a buffer that will be presented soon. Clear the previously presented layer
4108 // stack list.
4109 mPreviouslyPresentedLayerStacks.clear();
4110 }
4111
4112 if (mDrawingState.buffer == nullptr) {
4113 const bool bufferReleased = oldBufferInfo.mBuffer != nullptr;
4114 recomputeVisibleRegions = bufferReleased;
4115 return bufferReleased;
4116 }
4117
Patrick Williamsbb25f802022-08-30 23:02:34 +00004118 if (oldBufferInfo.mBuffer == nullptr) {
4119 // the first time we receive a buffer, we need to trigger a
4120 // geometry invalidation.
4121 recomputeVisibleRegions = true;
4122 }
4123
4124 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
4125 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
4126 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
4127 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
4128 recomputeVisibleRegions = true;
4129 }
4130
4131 if (oldBufferInfo.mBuffer != nullptr) {
4132 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
4133 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
4134 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
4135 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
4136 recomputeVisibleRegions = true;
4137 }
4138 }
4139
4140 if (oldOpacity != isOpaque(mDrawingState)) {
4141 recomputeVisibleRegions = true;
4142 }
4143
4144 return true;
4145}
4146
4147bool Layer::hasReadyFrame() const {
4148 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4149}
4150
4151bool Layer::isProtected() const {
4152 return (mBufferInfo.mBuffer != nullptr) &&
4153 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4154}
4155
Patrick Williamsbb25f802022-08-30 23:02:34 +00004156void Layer::latchAndReleaseBuffer() {
4157 if (hasReadyFrame()) {
4158 bool ignored = false;
4159 latchBuffer(ignored, systemTime());
4160 }
4161 releasePendingBuffer(systemTime());
4162}
4163
4164PixelFormat Layer::getPixelFormat() const {
4165 return mBufferInfo.mPixelFormat;
4166}
4167
4168bool Layer::getTransformToDisplayInverse() const {
4169 return mBufferInfo.mTransformToDisplayInverse;
4170}
4171
4172Rect Layer::getBufferCrop() const {
4173 // this is the crop rectangle that applies to the buffer
4174 // itself (as opposed to the window)
4175 if (!mBufferInfo.mCrop.isEmpty()) {
4176 // if the buffer crop is defined, we use that
4177 return mBufferInfo.mCrop;
4178 } else if (mBufferInfo.mBuffer != nullptr) {
4179 // otherwise we use the whole buffer
4180 return mBufferInfo.mBuffer->getBounds();
4181 } else {
4182 // if we don't have a buffer yet, we use an empty/invalid crop
4183 return Rect();
4184 }
4185}
4186
4187uint32_t Layer::getBufferTransform() const {
4188 return mBufferInfo.mTransform;
4189}
4190
4191ui::Dataspace Layer::getDataSpace() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004192 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4193}
4194
Alec Mouri89f5d4e2023-10-20 17:12:49 +00004195bool Layer::isFrontBuffered() const {
4196 if (mBufferInfo.mBuffer == nullptr) {
4197 return false;
4198 }
4199
4200 return mBufferInfo.mBuffer->getUsage() & AHARDWAREBUFFER_USAGE_FRONT_BUFFER;
4201}
4202
Patrick Williamsbb25f802022-08-30 23:02:34 +00004203ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4204 ui::Dataspace updatedDataspace = dataspace;
4205 // translate legacy dataspaces to modern dataspaces
4206 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00004207 // Treat unknown dataspaces as V0_sRGB
4208 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00004209 case ui::Dataspace::SRGB:
4210 updatedDataspace = ui::Dataspace::V0_SRGB;
4211 break;
4212 case ui::Dataspace::SRGB_LINEAR:
4213 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4214 break;
4215 case ui::Dataspace::JFIF:
4216 updatedDataspace = ui::Dataspace::V0_JFIF;
4217 break;
4218 case ui::Dataspace::BT601_625:
4219 updatedDataspace = ui::Dataspace::V0_BT601_625;
4220 break;
4221 case ui::Dataspace::BT601_525:
4222 updatedDataspace = ui::Dataspace::V0_BT601_525;
4223 break;
4224 case ui::Dataspace::BT709:
4225 updatedDataspace = ui::Dataspace::V0_BT709;
4226 break;
4227 default:
4228 break;
4229 }
4230
4231 return updatedDataspace;
4232}
4233
4234sp<GraphicBuffer> Layer::getBuffer() const {
4235 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4236}
4237
Vishnu Nairb76d99a2023-03-19 18:22:31 -07004238void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4239 mTransformHintLegacy = getFixedTransformHint();
4240 if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4241 mTransformHintLegacy = displayTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004242 }
4243}
4244
4245const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4246 return mBufferInfo.mBuffer;
4247}
4248
4249bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004250 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004251 return false;
4252 }
4253
4254 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004255 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004256 mDrawingState.modified = true;
4257 setTransactionFlags(eTransactionNeeded);
4258 return true;
4259}
4260
4261bool Layer::fillsColor() const {
4262 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4263 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4264}
4265
4266bool Layer::hasBlur() const {
4267 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4268}
4269
Vishnu Nairba354102022-08-01 00:14:18 +00004270void Layer::updateSnapshot(bool updateGeometry) {
4271 if (!getCompositionEngineLayerFE()) {
4272 return;
4273 }
4274
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004275 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004276 if (updateGeometry) {
4277 prepareBasicGeometryCompositionState();
4278 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004279 snapshot->roundedCorner = getRoundedCornerState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004280 snapshot->transformedBounds = mScreenBounds;
4281 if (mEffectiveShadowRadius > 0.f) {
4282 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4283
4284 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4285 // it if transparent regions are present. This may not be necessary since shadows are
4286 // typically cast by layers without transparent regions.
4287 snapshot->shadowSettings.boundaries = mBounds;
4288
4289 const float casterAlpha = snapshot->alpha;
4290 const bool casterIsOpaque =
4291 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4292
4293 // If the casting layer is translucent, we need to fill in the shadow underneath the
4294 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4295 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4296 snapshot->shadowSettings.ambientColor *= casterAlpha;
4297 snapshot->shadowSettings.spotColor *= casterAlpha;
4298 }
4299 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004300 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004301 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004302 snapshot->layerOpaqueFlagSet =
4303 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004304 sp<Layer> p = mDrawingParent.promote();
4305 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004306 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004307 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004308 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004309 }
4310 snapshot->bufferSize = getBufferSize(mDrawingState);
4311 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004312 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004313 preparePerFrameCompositionState();
4314}
4315
Vishnu Naire14c6b32022-08-06 04:20:15 +00004316void Layer::updateChildrenSnapshots(bool updateGeometry) {
4317 for (const sp<Layer>& child : mDrawingChildren) {
4318 child->updateSnapshot(updateGeometry);
4319 child->updateChildrenSnapshots(updateGeometry);
4320 }
4321}
4322
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004323void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4324 mSnapshot->layerMetadata = parentMetadata;
4325 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4326 for (const sp<Layer>& child : mDrawingChildren) {
4327 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4328 }
4329}
4330
4331void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4332 std::unordered_set<Layer*>& visited) {
4333 if (visited.find(this) != visited.end()) {
4334 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4335 return;
4336 }
4337 visited.insert(this);
4338
4339 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4340
4341 if (mDrawingState.zOrderRelatives.empty()) {
4342 return;
4343 }
4344 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4345 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4346 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4347 sp<Layer> relative = weakRelative.promote();
4348 if (!relative) {
4349 continue;
4350 }
4351 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4352 }
4353}
4354
Chavi Weingarten328a8312023-01-26 21:17:52 +00004355bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004356 TrustedPresentationListener const& listener) {
4357 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4358 mTrustedPresentationListener = listener;
4359 mTrustedPresentationThresholds = thresholds;
4360 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4361 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4362 mFlinger->mNumTrustedPresentationListeners++;
4363 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4364 mFlinger->mNumTrustedPresentationListeners--;
4365 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004366
4367 // Reset trusted presentation states to ensure we start the time again.
4368 mEnteredTrustedPresentationStateTime = -1;
4369 mLastReportedTrustedPresentationState = false;
4370 mLastComputedTrustedPresentationState = false;
4371
4372 // If there's a new trusted presentation listener, the code needs to go through the composite
4373 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4374 // we're already in the requested state.
4375 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004376}
4377
Vishnu Naira156f482023-02-22 00:23:38 +00004378void Layer::updateLastLatchTime(nsecs_t latchTime) {
4379 mLastLatchTime = latchTime;
4380}
4381
Arthur Hung69f95222023-10-04 07:39:02 +00004382void Layer::setIsSmallDirty(const Region& damageRegion,
4383 const ui::Transform& layerToDisplayTransform) {
4384 mSmallDirty = false;
Jerry Chang36678002023-11-29 16:56:17 +00004385 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00004386 return;
4387 }
4388
4389 if (mWindowType != WindowInfo::Type::APPLICATION &&
4390 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
4391 return;
4392 }
Arthur Hung69f95222023-10-04 07:39:02 +00004393
4394 Rect bounds = damageRegion.getBounds();
Arthur Hungc70bee22023-06-02 01:35:52 +00004395 if (!bounds.isValid()) {
4396 return;
4397 }
4398
Arthur Hung69f95222023-10-04 07:39:02 +00004399 // Transform to screen space.
4400 bounds = layerToDisplayTransform.transform(bounds);
4401
Arthur Hungc70bee22023-06-02 01:35:52 +00004402 // If the damage region is a small dirty, this could give the hint for the layer history that
4403 // it could suppress the heuristic rate when calculating.
Tony Huangf3621102023-09-04 17:14:22 +08004404 mSmallDirty = mFlinger->mScheduler->isSmallDirtyArea(mOwnerAppId,
Tony Huang9ac5e6e2023-08-24 09:01:44 +00004405 bounds.getWidth() * bounds.getHeight());
Arthur Hungc70bee22023-06-02 01:35:52 +00004406}
4407
Arthur Hung69f95222023-10-04 07:39:02 +00004408void Layer::setIsSmallDirty(frontend::LayerSnapshot* snapshot) {
4409 setIsSmallDirty(snapshot->surfaceDamage, snapshot->localTransform);
4410 snapshot->isSmallDirty = mSmallDirty;
4411}
4412
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004413} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004414
4415#if defined(__gl_h_)
4416#error "don't include gl/gl.h in this file"
4417#endif
4418
4419#if defined(__gl2_h_)
4420#error "don't include gl2/gl2.h in this file"
4421#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004422
4423// TODO(b/129481165): remove the #pragma below and fix conversion issues
4424#pragma clang diagnostic pop // ignored "-Wconversion"