blob: 3c8af19015b7bc37eb1aa3aa51c3b2005abd1df0 [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>
Vishnu Nairbe0ad902024-06-27 23:38:43 +000030#include <common/trace.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000031#include <compositionengine/CompositionEngine.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080032#include <compositionengine/Display.h>
Lloyd Piquea83776c2019-01-29 18:42:32 -080033#include <compositionengine/LayerFECompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080034#include <compositionengine/OutputLayer.h>
35#include <compositionengine/impl/OutputLayerCompositionState.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070036#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070037#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070038#include <cutils/properties.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070039#include <ftl/enum.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080040#include <ftl/fake_guard.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080041#include <gui/BufferItem.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080042#include <gui/Surface.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>
61
Alec Mourie60041e2019-06-14 18:59:51 -070062#include <algorithm>
63#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070064#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070065#include <sstream>
66
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070067#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080068#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070069#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070070#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +000071#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000072#include "FrontEnd/LayerHandle.h"
Melody Hsue4ef87f2024-03-26 23:54:45 +000073#include "Layer.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080074#include "LayerProtoHelper.h"
Josh Gao194ff392022-09-08 16:19:29 -070075#include "MutexUtils.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080077#include "TimeStats/TimeStats.h"
Melody Hsue4ef87f2024-03-26 23:54:45 +000078#include "TransactionCallbackInvoker.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070079#include "TunnelModeEnabledReporter.h"
Alec Mouri9892aac2023-12-11 21:16:59 +000080#include "Utils/FenceUtils.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070081
David Sodman41fdfc92017-11-06 16:09:56 -080082#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000083#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085namespace android {
Alec Mouri9892aac2023-12-11 21:16:59 +000086using namespace std::chrono_literals;
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010087namespace {
88constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000089
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000090const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000091
Linnan Li13bf76a2024-05-05 19:18:02 +080092ui::LogicalDisplayId toLogicalDisplayId(const ui::LayerStack& layerStack) {
93 return ui::LogicalDisplayId{static_cast<int32_t>(layerStack.id)};
94}
95
Patrick Williamsbb25f802022-08-30 23:02:34 +000096bool assignTransform(ui::Transform* dst, ui::Transform& from) {
97 if (*dst == from) {
98 return false;
99 }
100 *dst = from;
101 return true;
102}
103
104TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
105 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
106 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
107 const auto frameRateCompatibility = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700108 switch (frameRate.vote.type) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000109 case Layer::FrameRateCompatibility::Default:
110 return FrameRateCompatibility::Default;
111 case Layer::FrameRateCompatibility::ExactOrMultiple:
112 return FrameRateCompatibility::ExactOrMultiple;
113 default:
114 return FrameRateCompatibility::Undefined;
115 }
116 }();
117
118 const auto seamlessness = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700119 switch (frameRate.vote.seamlessness) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000120 case scheduler::Seamlessness::OnlySeamless:
121 return Seamlessness::ShouldBeSeamless;
122 case scheduler::Seamlessness::SeamedAndSeamless:
123 return Seamlessness::NotRequired;
124 default:
125 return Seamlessness::Undefined;
126 }
127 }();
128
Rachel Leece6e0042023-06-27 11:22:54 -0700129 return TimeStats::SetFrameRateVote{.frameRate = frameRate.vote.rate.getValue(),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000130 .frameRateCompatibility = frameRateCompatibility,
131 .seamlessness = seamlessness};
132}
133
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100134} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800135
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700136using namespace ftl::flag_operators;
137
Yiwei Zhang5434a782018-12-05 18:06:32 -0800138using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000139using frontend::LayerSnapshot;
140using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800141using gui::GameMode;
142using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500143using gui::WindowInfo;
Vishnu Nair494a2e42023-11-10 17:21:19 -0800144using ui::Size;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800145
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700146using PresentState = frametimeline::SurfaceFrame::PresentState;
147
Kean Mariotti4ba343c2023-04-19 13:31:02 +0000148Layer::Layer(const surfaceflinger::LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000149 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700150 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000151 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700152 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800153 mWindowType(static_cast<WindowInfo::Type>(
154 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000155 mLayerCreationFlags(args.flags),
Lloyd Pique70ddc672024-04-30 18:20:40 -0700156 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName, this)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000157 ALOGV("Creating Layer %s", getDebugName());
158
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700159 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700160 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
161 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
162 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700163 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
164 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700165 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700166 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700167 mDrawingState.z = 0;
168 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700169 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700170 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700171 mDrawingState.transform.set(0, 0);
172 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +0000173 mDrawingState.previousFrameNumber = 0;
Vishnu Nair63221212023-04-06 15:17:37 -0700174 mDrawingState.barrierFrameNumber = 0;
175 mDrawingState.producerId = 0;
176 mDrawingState.barrierProducerId = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700177 mDrawingState.bufferTransform = 0;
178 mDrawingState.transformToDisplayInverse = false;
Robert Carr6a160312021-05-17 12:08:20 -0700179 mDrawingState.acquireFence = sp<Fence>::make(-1);
180 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
Alec Mouri74c7ae12023-03-26 02:57:47 +0000181 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Robert Carr6a160312021-05-17 12:08:20 -0700182 mDrawingState.hdrMetadata.validTypes = 0;
183 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
184 mDrawingState.cornerRadius = 0.0f;
185 mDrawingState.backgroundBlurRadius = 0;
186 mDrawingState.api = -1;
187 mDrawingState.hasColorTransform = false;
188 mDrawingState.colorSpaceAgnostic = false;
189 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
190 mDrawingState.metadata = args.metadata;
191 mDrawingState.shadowRadius = 0.f;
192 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
193 mDrawingState.frameTimelineInfo = {};
194 mDrawingState.postTime = -1;
195 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000196 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700197 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700198 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000199 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Rachel Lee70f7b692023-11-22 11:24:02 -0800200 mDrawingState.frameRateSelectionStrategy = FrameRateSelectionStrategy::Propagate;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700201
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700202 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
203 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700204 mDrawingState.color.r = -1.0_hf;
205 mDrawingState.color.g = -1.0_hf;
206 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700207 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700208
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500209 mFrameTracker.setDisplayRefreshPeriod(
210 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700211
Vishnu Naircb8be502022-10-12 19:03:23 +0000212 mOwnerUid = args.ownerUid;
213 mOwnerPid = args.ownerPid;
Tony Huangf3621102023-09-04 17:14:22 +0800214 mOwnerAppId = mOwnerUid % PER_USER_RANGE;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000215
216 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
217 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
218 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000219
220 mSnapshot->sequence = sequence;
221 mSnapshot->name = getDebugName();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000222 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000223 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800224}
225
226void Layer::onFirstRef() {
227 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700228}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700229
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700230Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000231 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
232 "Layer destructor called off the main thread.");
233
Patrick Williamsbb25f802022-08-30 23:02:34 +0000234 if (mBufferInfo.mBuffer != nullptr) {
235 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
236 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800237 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000238 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000239 const int32_t layerId = getSequence();
240 mFlinger->mTimeStats->onDestroy(layerId);
241 mFlinger->mFrameTracer->onDestroy(layerId);
242
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000243 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700244 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700245
246 if (mDrawingState.sidebandStream != nullptr) {
247 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
248 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000249 if (hasTrustedPresentationListener()) {
250 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000251 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000252 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700253}
254
Mathias Agopian13127d82013-03-05 17:47:11 -0800255// ---------------------------------------------------------------------------
256// callbacks
257// ---------------------------------------------------------------------------
258
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700259void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700260 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700261 return;
262 }
Robert Carr2e102c92018-10-23 12:11:15 -0700263
Robert Carr6a160312021-05-17 12:08:20 -0700264 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700265 if (strongRelative == nullptr) {
266 setZOrderRelativeOf(nullptr);
267 return;
268 }
269
270 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700271 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700272 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800273 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700274 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700275}
276
Mathias Agopian13127d82013-03-05 17:47:11 -0800277// ---------------------------------------------------------------------------
278// set-up
279// ---------------------------------------------------------------------------
280
chaviw13fdc492017-06-27 12:40:18 -0700281bool Layer::getPremultipledAlpha() const {
282 return mPremultipliedAlpha;
283}
284
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700285sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800286 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700287 if (mGetHandleCalled) {
288 ALOGE("Get handle called twice" );
289 return nullptr;
290 }
291 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700292 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000293 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800294}
295
296// ---------------------------------------------------------------------------
297// h/w composer set-up
298// ---------------------------------------------------------------------------
299
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700300static Rect reduce(const Rect& win, const Region& exclude) {
301 if (CC_LIKELY(exclude.isEmpty())) {
302 return win;
303 }
304 if (exclude.isRect()) {
305 return win.reduce(exclude.getBounds());
306 }
307 return Region(win).subtract(exclude).getBounds();
308}
309
Dan Stoza80d61162017-12-20 15:57:52 -0800310static FloatRect reduce(const FloatRect& win, const Region& exclude) {
311 if (CC_LIKELY(exclude.isEmpty())) {
312 return win;
313 }
314 // Convert through Rect (by rounding) for lack of FloatRegion
315 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
316}
317
Vishnu Nair4351ad52019-02-11 14:13:02 -0800318Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800319 if (!reduceTransparentRegion) {
320 return Rect{mScreenBounds};
321 }
322
323 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800324 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800325 // Transform to screen space.
326 bounds = t.transform(bounds);
327 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700328}
329
Vishnu Nair4351ad52019-02-11 14:13:02 -0800330FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000331 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800332 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700333}
334
Vishnu Nairf0c28512019-02-08 12:40:28 -0800335FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
336 // Subtract the transparent region and snap to the bounds.
337 return reduce(mBounds, activeTransparentRegion);
338}
339
Chavi Weingarten076acac2023-01-19 17:20:43 +0000340// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000341void Layer::updateTrustedPresentationState(const DisplayDevice* display,
342 const frontend::LayerSnapshot* snapshot,
343 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000344 if (!hasTrustedPresentationListener()) {
345 return;
346 }
347 const bool lastState = mLastComputedTrustedPresentationState;
348 mLastComputedTrustedPresentationState = false;
349
350 if (!leaveState) {
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000351 const auto outputLayer = findOutputLayerForDisplay(display, snapshot->path);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000352 if (outputLayer != nullptr) {
353 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
354 Region coveredRegion =
355 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
356 mLastComputedTrustedPresentationState =
357 computeTrustedPresentationState(snapshot->geomLayerBounds,
358 snapshot->sourceBounds(), coveredRegion,
359 snapshot->transformedBounds,
360 snapshot->alpha,
361 snapshot->geomLayerTransform,
362 mTrustedPresentationThresholds);
363 } else {
364 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
365 "TrustedPresentationState",
366 getDebugName());
367 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000368 }
369 }
370 const bool newState = mLastComputedTrustedPresentationState;
371 if (lastState && !newState) {
372 // We were in the trusted presentation state, but now we left it,
373 // emit the callback if needed
374 if (mLastReportedTrustedPresentationState) {
375 mLastReportedTrustedPresentationState = false;
376 mTrustedPresentationListener.invoke(false);
377 }
378 // Reset the timer
379 mEnteredTrustedPresentationStateTime = -1;
380 } else if (!lastState && newState) {
381 // We were not in the trusted presentation state, but we entered it, begin the timer
382 // and make sure this gets called at least once more!
383 mEnteredTrustedPresentationStateTime = time_in_ms;
384 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
385 }
386
387 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
388 if (!mLastReportedTrustedPresentationState && newState &&
389 (time_in_ms - mEnteredTrustedPresentationStateTime >
390 mTrustedPresentationThresholds.stabilityRequirementMs)) {
391 mLastReportedTrustedPresentationState = true;
392 mTrustedPresentationListener.invoke(true);
393 }
394}
395
396/**
397 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
398 * of how the parameters and thresholds are interpreted. The general spirit is
399 * to produce an upper bound on the amount of the buffer which was presented.
400 */
401bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
402 const Region& coveredRegion,
403 const FloatRect& screenBounds, float alpha,
404 const ui::Transform& effectiveTransform,
405 const TrustedPresentationThresholds& thresholds) {
406 if (alpha < thresholds.minAlpha) {
407 return false;
408 }
409 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
410 return false;
411 }
412 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
413 return false;
414 }
415
416 const float sx = effectiveTransform.dsdx();
417 const float sy = effectiveTransform.dsdy();
418 float fractionRendered = std::min(sx * sy, 1.0f);
419
420 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
421 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
422 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
423
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000424 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
425 // Compute the size of all the rects since they may be disconnected.
426 float coveredSize = 0;
427 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
428 float size = rect->width() * rect->height();
429 coveredSize += size;
430 }
431
432 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000433
434 if (fractionRendered < thresholds.minFractionRendered) {
435 return false;
436 }
437
438 return true;
439}
440
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700441void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
442 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800443 const State& s(getDrawingState());
444
445 // Calculate effective layer transform
446 mEffectiveTransform = parentTransform * getActiveTransform(s);
447
Garfield Tan2c1782c2022-02-16 15:25:05 -0800448 if (CC_UNLIKELY(!isTransformValid())) {
449 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
450 getDebugName());
451 return;
452 }
453
Vishnu Nair4351ad52019-02-11 14:13:02 -0800454 // Transform parent bounds to layer space
455 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
456
Vishnu Nairc652ff82019-03-15 12:48:54 -0700457 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800458 mSourceBounds = computeSourceBounds(parentBounds);
459
460 // Calculate bounds by croping diplay frame with layer crop and parent bounds
461 FloatRect bounds = mSourceBounds;
462 const Rect layerCrop = getCrop(s);
463 if (!layerCrop.isEmpty()) {
464 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
465 }
466 bounds = bounds.intersect(parentBounds);
467
468 mBounds = bounds;
469 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700470
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700471 // Use the layer's own shadow radius if set. Otherwise get the radius from
472 // parent.
473 if (s.shadowRadius > 0.f) {
474 mEffectiveShadowRadius = s.shadowRadius;
475 } else {
476 mEffectiveShadowRadius = parentShadowRadius;
477 }
478
479 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
480 // don't pass it to its children.
481 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
482
Vishnu Nair4351ad52019-02-11 14:13:02 -0800483 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700484 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800485 }
Vishnu Nairba354102022-08-01 00:14:18 +0000486
487 if (mPotentialCursor) {
488 prepareCursorCompositionState();
489 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800490}
491
Vishnu Nair60356342018-11-13 13:00:45 -0800492Rect Layer::getCroppedBufferSize(const State& s) const {
493 Rect size = getBufferSize(s);
494 Rect crop = getCrop(s);
495 if (!crop.isEmpty() && size.isValid()) {
496 size.intersect(crop, &size);
497 } else if (!crop.isEmpty()) {
498 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700499 }
Vishnu Nair60356342018-11-13 13:00:45 -0800500 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800501}
502
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700503void Layer::setupRoundedCornersCropCoordinates(Rect win,
504 const FloatRect& roundedCornersCrop) const {
505 // Translate win by the rounded corners rect coordinates, to have all values in
506 // layer coordinate space.
507 win.left -= roundedCornersCrop.left;
508 win.right -= roundedCornersCrop.left;
509 win.top -= roundedCornersCrop.top;
510 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700511}
512
Lloyd Piquede196652020-01-22 17:29:58 -0800513void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800514 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800515 const auto alpha = static_cast<float>(getAlpha());
516 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700517 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800518
519 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
520 if (!opaque || alpha != 1.0f) {
521 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
522 : Hwc2::IComposerClient::BlendMode::COVERAGE;
523 }
524
Alec Mourif4af03e2023-02-11 00:25:24 +0000525 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000526 auto* snapshot = editLayerSnapshot();
527 snapshot->outputFilter = getOutputFilter();
528 snapshot->isVisible = isVisible();
529 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
Vishnu Naird9e4f462023-10-06 04:05:45 +0000530 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800531
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000532 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800533 contentDirty = false;
534
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000535 snapshot->geomLayerBounds = mBounds;
536 snapshot->geomLayerTransform = getTransform();
537 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
538 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000539 snapshot->localTransform = getActiveTransform(drawingState);
540 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000541 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
542 snapshot->alpha = alpha;
Vishnu Nairc6384702023-07-31 12:22:20 -0700543 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
544 snapshot->blurRegions = getBlurRegions();
Lloyd Piquec6687342019-03-07 21:34:57 -0800545}
546
Lloyd Piquede196652020-01-22 17:29:58 -0800547void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800548 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000549 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700550
Alec Mourif4af03e2023-02-11 00:25:24 +0000551 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000552 snapshot->geomBufferSize = getBufferSize(drawingState);
553 snapshot->geomContentCrop = getBufferCrop();
554 snapshot->geomCrop = getCrop(drawingState);
555 snapshot->geomBufferTransform = getBufferTransform();
556 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
557 snapshot->geomUsesSourceCrop = usesSourceCrop();
558 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800559
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000560 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800561 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
562 for (const auto& [key, mandatory] : supportedMetadata) {
563 const auto& genericLayerMetadataCompatibilityMap =
564 mFlinger->getGenericLayerMetadataKeyMap();
565 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
566 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
567 continue;
568 }
569 const uint32_t id = compatIter->second;
570
571 auto it = drawingState.metadata.mMap.find(id);
572 if (it == std::end(drawingState.metadata.mMap)) {
573 continue;
574 }
575
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000576 snapshot->metadata.emplace(key,
577 compositionengine::GenericLayerMetadataEntry{mandatory,
578 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800579 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800580}
David Sodmanba340492018-08-05 21:51:33 -0700581
Lloyd Piquede196652020-01-22 17:29:58 -0800582void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800583 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000584 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000585 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800586
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000587 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800588
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000589 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
590 snapshot->dataspace = getDataSpace();
591 snapshot->colorTransform = getColorTransform();
592 snapshot->colorTransformIsIdentity = !hasColorTransform();
593 snapshot->surfaceDamage = surfaceDamageRegion;
594 snapshot->hasProtectedContent = isProtected();
595 snapshot->dimmingEnabled = isDimmingEnabled();
Sally Qi963049b2023-03-23 14:06:21 -0700596 snapshot->currentHdrSdrRatio = getCurrentHdrSdrRatio();
597 snapshot->desiredHdrSdrRatio = getDesiredHdrSdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000598 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800599
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700600 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700601
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000602 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800603
604 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400605 // Rounded corners no longer force client composition, since we may use a
606 // hole punch so that the layer will appear to have rounded corners.
Alec Mouri994761f2023-08-04 21:50:55 +0000607 if (drawShadows() || snapshot->stretchEffect.hasEffect()) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000608 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800609 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700610 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairc6384702023-07-31 12:22:20 -0700611 snapshot->blurRegions = getBlurRegions();
612 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400613
614 // Layer framerate is used in caching decisions.
615 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
616 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000617 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000618
619 if (hasBufferOrSidebandStream()) {
620 preparePerFrameBufferCompositionState();
621 } else {
622 preparePerFrameEffectsCompositionState();
623 }
624}
625
626void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000627 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000628 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000629 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000630 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
631 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000632 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
633 return;
634 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000635 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000636 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800637 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
638 snapshot->compositionType =
639 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000640 } else {
641 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000642 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
643 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000644 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
645 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
646 }
647
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000648 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000649 snapshot->acquireFence = mBufferInfo.mFence;
650 snapshot->frameNumber = mBufferInfo.mFrameNumber;
651 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000652}
653
654void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000655 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000656 auto* snapshot = editLayerSnapshot();
657 snapshot->color = getColor();
658 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000659 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800660}
661
Lloyd Piquede196652020-01-22 17:29:58 -0800662void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800663 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000664 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000665 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800666
667 // Apply the layer's transform, followed by the display's global transform
668 // Here we're guaranteed that the layer's transform preserves rects
669 Rect win = getCroppedBufferSize(drawingState);
670 // Subtract the transparent region and snap to the bounds
671 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
672 Rect frame(getTransform().transform(bounds));
673
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000674 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800675}
676
Lloyd Piquea83776c2019-01-29 18:42:32 -0800677const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700678 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800679}
680
Mathias Agopian13127d82013-03-05 17:47:11 -0800681// ---------------------------------------------------------------------------
682// drawing...
683// ---------------------------------------------------------------------------
684
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500685aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
686 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700687 const auto outputLayer = findOutputLayerForDisplay(&display);
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000688 return getCompositionType(outputLayer);
689}
690
691aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
692 const compositionengine::OutputLayer* outputLayer) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -0800693 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500694 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800695 }
696 if (outputLayer->getState().hwc) {
697 return (*outputLayer->getState().hwc).hwcCompositionType;
698 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500699 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800700 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800701}
702
Mathias Agopian13127d82013-03-05 17:47:11 -0800703// ----------------------------------------------------------------------------
704// local state
705// ----------------------------------------------------------------------------
706
David Sodman41fdfc92017-11-06 16:09:56 -0800707bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800708 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700709 if (s.flags & layer_state_t::eLayerSecure) {
710 return true;
711 }
712
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000713 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700714 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700715}
716
Mathias Agopian13127d82013-03-05 17:47:11 -0800717// ----------------------------------------------------------------------------
718// transaction
719// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800720
Vishnu Naira156f482023-02-22 00:23:38 +0000721uint32_t Layer::doTransaction(uint32_t flags) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000722 SFTRACE_CALL();
Marissa Wall61c58622018-07-18 10:12:20 -0700723
Robert Carr0758e5d2021-03-11 22:15:04 -0800724 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700725 mDrawingStateModified = mDrawingState.modified;
726 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700727
Alec Mourib416efd2018-09-06 21:01:59 +0000728 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700729
Robert Carr6a160312021-05-17 12:08:20 -0700730 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800731 // invalidate and recompute the visible regions if needed
732 flags |= Layer::eVisibleRegion;
733 }
734
Robert Carr6a160312021-05-17 12:08:20 -0700735 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800736 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000737 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800738 flags |= eVisibleRegion;
739 this->contentDirty = true;
740
741 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700742 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800743 }
744
Arthur Hung9ed43392022-05-27 06:31:57 +0000745 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
746 mFlinger->mUpdateInputInfo = true;
747 }
748
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700749 commitTransaction();
Robert Carra1257842020-01-31 13:48:28 -0800750
Mathias Agopian13127d82013-03-05 17:47:11 -0800751 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800752}
753
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700754void Layer::commitTransaction() {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000755 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
756 // bufferSurfaceFrameTX will be presented in latchBuffer.
757 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
758 if (surfaceFrame->getPresentState() != PresentState::Presented) {
759 // With applyPendingStates, we could end up having presented surfaceframes from previous
760 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800761 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000762 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
763 }
764 }
Robert Carr6a160312021-05-17 12:08:20 -0700765 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700766}
767
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700768uint32_t Layer::clearTransactionFlags(uint32_t mask) {
769 const auto flags = mTransactionFlags & mask;
770 mTransactionFlags &= ~mask;
771 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800772}
773
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700774void Layer::setTransactionFlags(uint32_t mask) {
775 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800776}
777
Robert Carrae060832016-11-28 10:51:00 -0800778bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700779 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
780 mDrawingState.sequence++;
781 mDrawingState.z = z;
782 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700783
Robert Carra70e91c2021-06-11 13:59:52 -0700784 mFlinger->mSomeChildrenChanged = true;
785
Robert Carrdb66e622017-04-10 16:55:57 -0700786 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700787 if (mDrawingState.zOrderRelativeOf != nullptr) {
788 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700789 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700790 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700791 }
chaviw606e5cf2019-03-01 10:12:10 -0800792 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700793 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800794 setTransactionFlags(eTransactionNeeded);
795 return true;
796}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700797
Robert Carrdb66e622017-04-10 16:55:57 -0700798void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700799 mDrawingState.zOrderRelatives.remove(relative);
800 mDrawingState.sequence++;
801 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700802 setTransactionFlags(eTransactionNeeded);
803}
804
805void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700806 mDrawingState.zOrderRelatives.add(relative);
807 mDrawingState.modified = true;
808 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700809 setTransactionFlags(eTransactionNeeded);
810}
811
chaviw606e5cf2019-03-01 10:12:10 -0800812void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700813 mDrawingState.zOrderRelativeOf = relativeOf;
814 mDrawingState.sequence++;
815 mDrawingState.modified = true;
816 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700817
chaviw606e5cf2019-03-01 10:12:10 -0800818 setTransactionFlags(eTransactionNeeded);
819}
820
Robert Carr503d2bd2017-12-04 15:49:47 -0800821bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000822 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700823 if (relative == nullptr) {
824 return false;
825 }
826
Robert Carr6a160312021-05-17 12:08:20 -0700827 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
828 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800829 return false;
830 }
831
Robert Carr88b85e12022-03-21 15:47:35 -0700832 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
833 (relative->mDrawingState.zOrderRelativeOf == this)) {
834 ALOGE("Detected relative layer loop between %s and %s",
835 mName.c_str(), relative->mName.c_str());
836 ALOGE("Ignoring new call to set relative layer");
837 return false;
838 }
839
Robert Carra70e91c2021-06-11 13:59:52 -0700840 mFlinger->mSomeChildrenChanged = true;
841
Robert Carr6a160312021-05-17 12:08:20 -0700842 mDrawingState.sequence++;
843 mDrawingState.modified = true;
844 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700845
Robert Carr6a160312021-05-17 12:08:20 -0700846 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700847 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700848 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700849 }
chaviw606e5cf2019-03-01 10:12:10 -0800850 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700851 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700852
853 setTransactionFlags(eTransactionNeeded);
854
855 return true;
856}
857
Winson Chunga30f7c92021-06-29 15:42:56 -0700858bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
859 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
860 mDrawingState.isTrustedOverlay = isTrustedOverlay;
861 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000862 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700863 setTransactionFlags(eTransactionNeeded);
864 return true;
865}
866
867bool Layer::isTrustedOverlay() const {
868 if (getDrawingState().isTrustedOverlay) {
869 return true;
870 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000871 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700872 return (p != nullptr) && p->isTrustedOverlay();
873}
874
Dan Stoza9e56aa02015-11-02 13:00:03 -0800875bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700876 if (mDrawingState.color.a == alpha) return false;
877 mDrawingState.sequence++;
878 mDrawingState.color.a = alpha;
879 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800880 setTransactionFlags(eTransactionNeeded);
881 return true;
882}
chaviw13fdc492017-06-27 12:40:18 -0700883
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700884bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -0700885 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700886
Robert Carr6a160312021-05-17 12:08:20 -0700887 mDrawingState.sequence++;
888 mDrawingState.cornerRadius = cornerRadius;
889 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700890 setTransactionFlags(eTransactionNeeded);
891 return true;
892}
893
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800894bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -0700895 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -0700896 // If we start or stop drawing blur then the layer's visibility state may change so increment
897 // the magic sequence number.
898 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
899 mDrawingState.sequence++;
900 }
Robert Carr6a160312021-05-17 12:08:20 -0700901 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
902 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800903 setTransactionFlags(eTransactionNeeded);
904 return true;
905}
Marissa Wall61c58622018-07-18 10:12:20 -0700906
Mathias Agopian13127d82013-03-05 17:47:11 -0800907bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +0000908 mDrawingState.sequence++;
909 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -0700910 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800911 setTransactionFlags(eTransactionNeeded);
912 return true;
913}
Ana Krulecc84d09b2019-11-02 23:10:29 +0100914
Lucas Dupinc3800b82020-10-02 16:24:48 -0700915bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -0700916 // If we start or stop drawing blur then the layer's visibility state may change so increment
917 // the magic sequence number.
918 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
919 mDrawingState.sequence++;
920 }
Robert Carr6a160312021-05-17 12:08:20 -0700921 mDrawingState.blurRegions = blurRegions;
922 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -0700923 setTransactionFlags(eTransactionNeeded);
924 return true;
925}
926
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800927bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -0700928 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
929 if (mDrawingState.flags == newFlags) return false;
930 mDrawingState.sequence++;
931 mDrawingState.flags = newFlags;
932 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800933 setTransactionFlags(eTransactionNeeded);
934 return true;
935}
Robert Carr99e27f02016-06-16 15:18:02 -0700936
chaviw25714502021-02-11 10:01:08 -0800937bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +0000938 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -0700939 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -0700940 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -0700941
Robert Carr6a160312021-05-17 12:08:20 -0700942 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800943 setTransactionFlags(eTransactionNeeded);
944 return true;
945}
Robert Carr8d5227b2017-03-16 15:41:03 -0700946
Evan Roskyef876c92019-01-25 17:46:06 -0800947bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -0700948 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
949 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -0800950 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -0800951 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500952}
953
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700954bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -0700955 if (mDrawingState.layerStack == layerStack) return false;
956 mDrawingState.sequence++;
957 mDrawingState.layerStack = layerStack;
958 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800959 setTransactionFlags(eTransactionNeeded);
960 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700961}
962
Peiyong Linc502cb72019-03-01 15:00:23 -0800963bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -0700964 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -0800965 return false;
966 }
Robert Carr6a160312021-05-17 12:08:20 -0700967 mDrawingState.sequence++;
968 mDrawingState.colorSpaceAgnostic = agnostic;
969 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -0800970 setTransactionFlags(eTransactionNeeded);
971 return true;
972}
973
Sally Qi81d95e62022-03-21 19:41:33 -0700974bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
975 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
976
977 mDrawingState.sequence++;
978 mDrawingState.dimmingEnabled = dimmingEnabled;
979 mDrawingState.modified = true;
980 setTransactionFlags(eTransactionNeeded);
981 return true;
982}
983
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700984bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
985 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
986};
987
Vishnu Nair73908d12022-10-24 21:46:42 -0700988ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
989 bool useDrawing = state == LayerVector::StateSet::Drawing;
990 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
991 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000992 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700993 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000994 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700995}
996
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700997bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -0700998 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700999 return false;
1000 }
1001
Robert Carr6a160312021-05-17 12:08:20 -07001002 mDrawingState.sequence++;
1003 mDrawingState.shadowRadius = shadowRadius;
1004 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001005 setTransactionFlags(eTransactionNeeded);
1006 return true;
1007}
1008
Vishnu Nair6213bd92020-05-08 17:42:25 -07001009bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001010 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001011 return false;
1012 }
1013
Robert Carr6a160312021-05-17 12:08:20 -07001014 mDrawingState.sequence++;
1015 mDrawingState.fixedTransformHint = fixedTransformHint;
1016 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001017 setTransactionFlags(eTransactionNeeded);
1018 return true;
1019}
1020
John Reckcdb4ed72021-02-04 13:39:33 -05001021bool Layer::setStretchEffect(const StretchEffect& effect) {
1022 StretchEffect temp = effect;
1023 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001024 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001025 return false;
1026 }
Robert Carr6a160312021-05-17 12:08:20 -07001027 mDrawingState.sequence++;
1028 mDrawingState.stretchEffect = temp;
1029 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001030 setTransactionFlags(eTransactionNeeded);
1031 return true;
1032}
1033
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001034void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
Vishnu Nair39a74a92024-07-29 19:01:50 +00001035 nsecs_t postTime, gui::GameMode gameMode) {
Robert Carr6a160312021-05-17 12:08:20 -07001036 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001037
1038 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1039 // there are two transactions with the same token, the first one without a buffer and the
1040 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1041 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001042 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1043 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001044 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001045 mDrawingState.bufferSurfaceFrameTX = it->second;
1046 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1047 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1048 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001049 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001050 mDrawingState.bufferSurfaceFrameTX =
Vishnu Nair39a74a92024-07-29 19:01:50 +00001051 createSurfaceFrameForBuffer(info, postTime, mTransactionName, gameMode);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001052 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001053
Vishnu Nair39a74a92024-07-29 19:01:50 +00001054 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName, gameMode);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001055}
1056
1057void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
Vishnu Nair39a74a92024-07-29 19:01:50 +00001058 nsecs_t postTime,
1059 gui::GameMode gameMode) {
Robert Carr6a160312021-05-17 12:08:20 -07001060 mDrawingState.frameTimelineInfo = info;
1061 mDrawingState.postTime = postTime;
1062 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001063 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001064
Robert Carr6a160312021-05-17 12:08:20 -07001065 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001066 bufferSurfaceFrameTX != nullptr) {
1067 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1068 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1069 // being used for BufferSurfaceFrame, don't create a new one.
1070 return;
1071 }
1072 }
1073 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1074 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1075 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001076 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1077 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Vishnu Nair39a74a92024-07-29 19:01:50 +00001078 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime, gameMode);
Robert Carr6a160312021-05-17 12:08:20 -07001079 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001080 } else {
1081 if (it->second->getPresentState() == PresentState::Presented) {
1082 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1083 // have been from previous vsync.
Vishnu Nair39a74a92024-07-29 19:01:50 +00001084 it->second = createSurfaceFrameForTransaction(info, postTime, gameMode);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001085 }
1086 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001087
Vishnu Nair39a74a92024-07-29 19:01:50 +00001088 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName, gameMode);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001089}
1090
1091void Layer::addSurfaceFrameDroppedForBuffer(
Ady Abraham5a3e3562023-06-07 10:32:08 -07001092 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t dropTime) {
1093 surfaceFrame->setDropTime(dropTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001094 surfaceFrame->setPresentState(PresentState::Dropped);
1095 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1096}
1097
1098void Layer::addSurfaceFramePresentedForBuffer(
1099 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1100 nsecs_t currentLatchTime) {
1101 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1102 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1103 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001104 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001105}
1106
1107std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
Vishnu Nair39a74a92024-07-29 19:01:50 +00001108 const FrameTimelineInfo& info, nsecs_t postTime, gui::GameMode gameMode) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001109 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001110 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1111 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001112 mTransactionName,
Vishnu Nair39a74a92024-07-29 19:01:50 +00001113 /*isBuffer*/ false, gameMode);
Rachel Leeed511ef2021-10-11 15:09:51 -07001114 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001115 // For Transactions, the post time is considered to be both queue and acquire fence time.
1116 surfaceFrame->setActualQueueTime(postTime);
1117 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001118 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1119 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001120 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001121 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001122 return surfaceFrame;
1123}
1124
1125std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
Vishnu Nair39a74a92024-07-29 19:01:50 +00001126 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName,
1127 gui::GameMode gameMode) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001128 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001129 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001130 getSequence(), mName, debugName,
Vishnu Nair39a74a92024-07-29 19:01:50 +00001131 /*isBuffer*/ true, gameMode);
Rachel Leeed511ef2021-10-11 15:09:51 -07001132 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001133 // For buffers, acquire fence time will set during latch.
1134 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001135 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1136 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001137 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001138 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001139 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001140}
1141
Ady Abraham5a3e3562023-06-07 10:32:08 -07001142void Layer::setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
Vishnu Nair39a74a92024-07-29 19:01:50 +00001143 std::string debugName, gui::GameMode gameMode) {
Ady Abraham5a3e3562023-06-07 10:32:08 -07001144 if (info.skippedFrameVsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
1145 return;
1146 }
1147
1148 FrameTimelineInfo skippedFrameTimelineInfo = info;
1149 skippedFrameTimelineInfo.vsyncId = info.skippedFrameVsyncId;
1150
1151 auto surfaceFrame =
1152 mFlinger->mFrameTimeline->createSurfaceFrameForToken(skippedFrameTimelineInfo,
1153 mOwnerPid, mOwnerUid,
1154 getSequence(), mName, debugName,
Vishnu Nair39a74a92024-07-29 19:01:50 +00001155 /*isBuffer*/ false, gameMode);
Ady Abraham5a3e3562023-06-07 10:32:08 -07001156 surfaceFrame->setActualStartTime(skippedFrameTimelineInfo.skippedFrameStartTimeNanos);
1157 // For Transactions, the post time is considered to be both queue and acquire fence time.
1158 surfaceFrame->setActualQueueTime(postTime);
1159 surfaceFrame->setAcquireFenceTime(postTime);
1160 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1161 if (fps) {
1162 surfaceFrame->setRenderRate(*fps);
1163 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001164 addSurfaceFrameDroppedForBuffer(surfaceFrame, postTime);
1165}
1166
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001167bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps,
1168 nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001169 if (mDrawingState.frameRateForLayerTree == frameRate) {
1170 return false;
1171 }
1172
1173 mDrawingState.frameRateForLayerTree = frameRate;
1174 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001175 ->recordLayerHistory(sequence, layerProps, now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001176 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001177 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001178}
1179
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001180Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1181 return getDrawingState().frameRateForLayerTree;
1182}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001183
Robert Carr1f0a16a2016-10-24 16:27:39 -07001184bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001185 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001186 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001187 if (parent != nullptr && parent->isHiddenByPolicy()) {
1188 return true;
1189 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001190 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1191 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1192 if (zOrderRelativeOf != nullptr) {
1193 if (zOrderRelativeOf->isHiddenByPolicy()) {
1194 return true;
1195 }
1196 }
1197 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001198 if (CC_UNLIKELY(!isTransformValid())) {
1199 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1200 return true;
1201 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001202 return s.flags & layer_state_t::eLayerHidden;
1203}
1204
David Sodman41fdfc92017-11-06 16:09:56 -08001205uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001206 // TODO: should we do something special if mSecure is set?
1207 if (mProtectedByApp) {
1208 // need a hardware-protected path to external video sink
1209 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001210 }
Riley Andrews03414a12014-07-01 14:22:59 -07001211 if (mPotentialCursor) {
1212 usage |= GraphicBuffer::USAGE_CURSOR;
1213 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001214 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001215 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001216}
1217
Mathias Agopian13127d82013-03-05 17:47:11 -08001218// ----------------------------------------------------------------------------
1219// debugging
1220// ----------------------------------------------------------------------------
1221
Yiwei Zhang5434a782018-12-05 18:06:32 -08001222void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001223 result.append(kDumpTableRowLength, '-');
1224 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001225 result.append(" Layer name\n");
1226 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001227 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001228 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001229 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001230 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001231 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001232 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1233 result.append(kDumpTableRowLength, '-');
1234 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001235}
1236
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001237void Layer::miniDump(std::string& result, const frontend::LayerSnapshot& snapshot,
1238 const DisplayDevice& display) const {
1239 const auto outputLayer = findOutputLayerForDisplay(&display, snapshot.path);
1240 if (!outputLayer) {
1241 return;
1242 }
1243
1244 StringAppendF(&result, " %s\n", snapshot.debugName.c_str());
1245 StringAppendF(&result, " %10zu | ", snapshot.globalZ);
1246 StringAppendF(&result, " %10d | ",
1247 snapshot.layerMetadata.getInt32(gui::METADATA_WINDOW_TYPE, 0));
1248 StringAppendF(&result, "%10s | ", toString(getCompositionType(outputLayer)).c_str());
1249 const auto& outputLayerState = outputLayer->getState();
1250 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1251 const Rect& frame = outputLayerState.displayFrame;
1252 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1253 const FloatRect& crop = outputLayerState.sourceCrop;
1254 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
1255 crop.bottom);
1256 const auto frameRate = snapshot.frameRate;
Ady Abraham77d406d2023-11-22 15:00:23 -08001257 std::string frameRateStr;
1258 if (frameRate.vote.rate.isValid()) {
1259 StringAppendF(&frameRateStr, "%.2f", frameRate.vote.rate.getValue());
1260 }
Rachel Leece6e0042023-06-27 11:22:54 -07001261 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
Ady Abraham77d406d2023-11-22 15:00:23 -08001262 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
Rachel Leece6e0042023-06-27 11:22:54 -07001263 ftl::enum_string(frameRate.vote.type).c_str(),
1264 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abraham77d406d2023-11-22 15:00:23 -08001265 } else if (frameRate.category != FrameRateCategory::Default) {
1266 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
1267 (std::string("Cat::") + ftl::enum_string(frameRate.category)).c_str(),
1268 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001269 } else {
1270 result.append(41, ' ');
1271 }
1272
1273 const auto focused = isLayerFocusedBasedOnPriority(snapshot.frameRateSelectionPriority);
1274 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1275
1276 result.append(kDumpTableRowLength, '-');
1277 result.append("\n");
1278}
1279
Yiwei Zhang5434a782018-12-05 18:06:32 -08001280void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001281 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001282}
1283
Svetoslavd85084b2014-03-20 10:28:31 -07001284void Layer::clearFrameStats() {
1285 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001286}
1287
Jamie Gennis6547ff42013-07-16 20:12:42 -07001288void Layer::logFrameStats() {
1289 mFrameTracker.logAndResetStats(mName);
1290}
1291
Svetoslavd85084b2014-03-20 10:28:31 -07001292void Layer::getFrameStats(FrameStats* outStats) const {
1293 mFrameTracker.getStats(outStats);
1294}
1295
Vishnu Nair76554eb2022-12-09 03:38:36 +00001296void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1297 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
Vishnu Nair3be61902023-04-26 19:47:29 -07001298 StringAppendF(&result, "Layer %s%s pid:%d uid:%d%s\n", getName().c_str(), hasBuffer.c_str(),
1299 mOwnerPid, mOwnerUid, isHandleAlive() ? " handleAlive" : "");
Vishnu Nair0f085c62019-08-30 08:49:12 -07001300}
1301
Brian Anderson5ea5e592016-12-01 16:54:33 -08001302void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001303 const int32_t layerId = getSequence();
1304 mFlinger->mTimeStats->onDestroy(layerId);
1305 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001306}
1307
Robert Carr15eae092018-03-23 13:43:53 -07001308void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001309 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001310 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001311 const float parentShadowRadius =
1312 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001313 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001314 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001315 }
1316}
1317
Peiyong Lind3788632018-09-18 16:01:31 -07001318bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001319 static const mat4 identityMatrix = mat4();
1320
Robert Carr6a160312021-05-17 12:08:20 -07001321 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001322 return false;
1323 }
Robert Carr6a160312021-05-17 12:08:20 -07001324 ++mDrawingState.sequence;
1325 mDrawingState.colorTransform = matrix;
1326 mDrawingState.hasColorTransform = matrix != identityMatrix;
1327 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001328 setTransactionFlags(eTransactionNeeded);
1329 return true;
1330}
1331
chaviwf66724d2018-11-28 16:35:21 -08001332mat4 Layer::getColorTransform() const {
1333 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001334 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001335 colorTransform = parent->getColorTransform() * colorTransform;
1336 }
1337 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001338}
1339
1340bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001341 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001342 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001343 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1344 }
1345 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001346}
1347
Chia-I Wu11481472018-05-04 10:43:19 -07001348bool Layer::isLegacyDataSpace() const {
1349 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001350 return !(getDataSpace() &
1351 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1352 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001353}
1354
Robert Carr1f0a16a2016-10-24 16:27:39 -07001355void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001356 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001357}
1358
Robert Carr6a160312021-05-17 12:08:20 -07001359int32_t Layer::getZ(LayerVector::StateSet) const {
1360 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001361}
1362
Robert Carr1c5481e2019-07-01 14:42:27 -07001363bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001364 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001365 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001366 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001367}
1368
David Sodman41fdfc92017-11-06 16:09:56 -08001369__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001370 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001371 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1372 "makeTraversalList received invalid stateSet");
1373 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1374 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001375 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001376
Robert Carr29abff82017-12-04 13:51:20 -08001377 if (state.zOrderRelatives.size() == 0) {
1378 *outSkipRelativeZUsers = true;
1379 return children;
1380 }
1381
chaviwfd462612018-05-31 16:11:27 -07001382 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001383 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001384 sp<Layer> strongRelative = weakRelative.promote();
1385 if (strongRelative != nullptr) {
1386 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001387 }
1388 }
1389
Dan Stoza412903f2017-04-27 13:42:17 -07001390 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001391 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001392 continue;
1393 }
Robert Carrdb66e622017-04-10 16:55:57 -07001394 traverse.add(child);
1395 }
1396
1397 return traverse;
1398}
1399
Peiyong Linefefaac2018-08-17 12:27:51 -07001400ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001401 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001402}
1403
Garfield Tan2c1782c2022-02-16 15:25:05 -08001404bool Layer::isTransformValid() const {
1405 float transformDet = getTransform().det();
1406 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1407}
1408
chaviw13fdc492017-06-27 12:40:18 -07001409half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001410 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001411
chaviw13fdc492017-06-27 12:40:18 -07001412 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1413 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07001414}
Robert Carr6452f122017-03-21 10:41:29 -07001415
Vishnu Nair6213bd92020-05-08 17:42:25 -07001416ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07001417 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001418 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
1419 return fixedTransformHint;
1420 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001421 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07001422 if (!p) return fixedTransformHint;
1423 return p->getFixedTransformHint();
1424}
1425
chaviw13fdc492017-06-27 12:40:18 -07001426half4 Layer::getColor() const {
1427 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001428 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07001429}
Robert Carr6452f122017-03-21 10:41:29 -07001430
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001431int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00001432 if (getDrawingState().backgroundBlurRadius == 0) {
1433 return 0;
1434 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01001435
Vishnu Nair29810f72022-07-01 16:38:41 +00001436 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01001437 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1438 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001439}
1440
Galia Peychevae0acf382021-04-12 21:22:34 +02001441const std::vector<BlurRegion> Layer::getBlurRegions() const {
1442 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02001443 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02001444 for (auto& region : regionsCopy) {
1445 region.alpha = region.alpha * layerAlpha;
1446 }
1447 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001448}
1449
Vishnu Naire14c6b32022-08-06 04:20:15 +00001450RoundedCornerState Layer::getRoundedCornerState() const {
Leon Scroggins IIIc1dbfcb2022-03-21 16:48:10 -04001451 // Today's DPUs cannot do rounded corners. If RenderEngine cannot render
1452 // protected content, remove rounded corners from protected content so it
1453 // can be rendered by the DPU.
1454 if (isProtected() && !mFlinger->getRenderEngine().supportsProtectedContent()) {
1455 return {};
1456 }
1457
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001458 // Get parent settings
1459 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001460 const auto& parent = mDrawingParent.promote();
1461 if (parent != nullptr) {
1462 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001463 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001464 ui::Transform t = getActiveTransform(getDrawingState());
1465 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001466 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001467 parentSettings.radius.x *= t.getScaleX();
1468 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001469 }
1470 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001471
1472 // Get layer settings
1473 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001474 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001475 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001476 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001477
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001478 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001479 // If the parent and the layer have rounded corner settings, use the parent settings if the
1480 // parent crop is entirely inside the layer crop.
1481 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
1482 if (parentSettings.cropRect.left > layerCropRect.left &&
1483 parentSettings.cropRect.top > layerCropRect.top &&
1484 parentSettings.cropRect.right < layerCropRect.right &&
1485 parentSettings.cropRect.bottom < layerCropRect.bottom) {
1486 return parentSettings;
1487 } else {
1488 return layerSettings;
1489 }
Vishnu Nairb1845592021-10-07 12:17:57 -07001490 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001491 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001492 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001493 return parentSettings;
1494 }
1495 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001496}
1497
Robert Carr88b85e12022-03-21 15:47:35 -07001498bool Layer::findInHierarchy(const sp<Layer>& l) {
1499 if (l == this) {
1500 return true;
1501 }
1502 for (auto& child : mDrawingChildren) {
1503 if (child->findInHierarchy(l)) {
1504 return true;
1505 }
1506 }
1507 return false;
1508}
1509
chaviw3277faf2021-05-19 16:45:23 -05001510void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07001511 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00001512 mDrawingState.touchableRegionCrop =
1513 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07001514 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00001515 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07001516 setTransactionFlags(eTransactionNeeded);
1517}
1518
Kean Mariotti4ba343c2023-04-19 13:31:02 +00001519perfetto::protos::LayerProto* Layer::writeToProto(perfetto::protos::LayersProto& layersProto,
1520 uint32_t traceFlags) {
1521 perfetto::protos::LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08001522 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08001523 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
1524
Vishnu Nair00b90132021-11-05 14:03:40 -07001525 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nair2f65e972023-04-04 16:36:28 +00001526 ui::LayerStack layerStack =
1527 (mSnapshot) ? mSnapshot->outputFilter.layerStack : ui::INVALID_LAYER_STACK;
1528 writeCompositionStateToProto(layerProto, layerStack);
Alec Mouri6b9e9912020-01-21 10:50:24 -08001529 }
1530
chaviw08f3cb22020-01-13 13:17:21 -08001531 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08001532 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08001533 }
chaviw6d89e2d2020-01-14 14:42:01 -08001534
1535 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08001536}
1537
Kean Mariotti4ba343c2023-04-19 13:31:02 +00001538void Layer::writeCompositionStateToProto(perfetto::protos::LayerProto* layerProto,
1539 ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00001540 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +00001541 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +00001542
1543 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +00001544 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00001545 const auto compositionType = getCompositionType(*display);
Kean Mariotti4ba343c2023-04-19 13:31:02 +00001546 layerProto->set_hwc_composition_type(
1547 static_cast<perfetto::protos::HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +00001548 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +00001549 [&]() { return layerProto->mutable_visible_region(); });
1550 }
1551}
1552
Kean Mariotti4ba343c2023-04-19 13:31:02 +00001553void Layer::writeToProtoDrawingState(perfetto::protos::LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07001554 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08001555 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07001556 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08001557 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07001558 [&]() { return layerInfo->mutable_active_buffer(); });
1559 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
1560 layerInfo->mutable_buffer_transform());
1561 }
1562 layerInfo->set_invalidate(contentDirty);
1563 layerInfo->set_is_protected(isProtected());
1564 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
1565 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07001566 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07001567 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001568 layerInfo->set_corner_radius(
1569 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07001570 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
1571 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
1572 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
1573 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
1574 [&]() { return layerInfo->mutable_position(); });
1575 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07001576 LayerProtoHelper::writeToProto(surfaceDamageRegion,
1577 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07001578
Vishnu Nair00b90132021-11-05 14:03:40 -07001579 if (hasColorTransform()) {
1580 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07001581 }
1582
Vishnu Nair60db8c02020-04-02 11:55:16 -07001583 LayerProtoHelper::writeToProto(mSourceBounds,
1584 [&]() { return layerInfo->mutable_source_bounds(); });
1585 LayerProtoHelper::writeToProto(mScreenBounds,
1586 [&]() { return layerInfo->mutable_screen_bounds(); });
1587 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
1588 [&]() { return layerInfo->mutable_corner_radius_crop(); });
1589 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07001590}
1591
Kean Mariotti4ba343c2023-04-19 13:31:02 +00001592void Layer::writeToProtoCommonState(perfetto::protos::LayerProto* layerInfo,
1593 LayerVector::StateSet stateSet, uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07001594 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1595 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001596 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07001597
chaviw766c9c52021-02-10 17:36:47 -08001598 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07001599
Vishnu Nair00b90132021-11-05 14:03:40 -07001600 layerInfo->set_id(sequence);
1601 layerInfo->set_name(getName().c_str());
1602 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07001603
Vishnu Nair00b90132021-11-05 14:03:40 -07001604 for (const auto& child : children) {
1605 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07001606 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001607
Vishnu Nair00b90132021-11-05 14:03:40 -07001608 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1609 sp<Layer> strongRelative = weakRelative.promote();
1610 if (strongRelative != nullptr) {
1611 layerInfo->add_relatives(strongRelative->sequence);
1612 }
1613 }
1614
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001615 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07001616 [&]() { return layerInfo->mutable_transparent_region(); });
1617
1618 layerInfo->set_layer_stack(getLayerStack().id);
1619 layerInfo->set_z(state.z);
1620
1621 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
1622 return layerInfo->mutable_requested_position();
1623 });
1624
Vishnu Nair00b90132021-11-05 14:03:40 -07001625 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
1626
1627 layerInfo->set_is_opaque(isOpaque(state));
1628
1629 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
1630 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
1631 LayerProtoHelper::writeToProto(state.color,
1632 [&]() { return layerInfo->mutable_requested_color(); });
1633 layerInfo->set_flags(state.flags);
1634
1635 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
1636 layerInfo->mutable_requested_transform());
1637
1638 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1639 if (parent != nullptr) {
1640 layerInfo->set_parent(parent->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07001641 }
1642
1643 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
1644 if (zOrderRelativeOf != nullptr) {
1645 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07001646 }
1647
1648 layerInfo->set_is_relative_of(state.isRelativeOf);
1649
1650 layerInfo->set_owner_uid(mOwnerUid);
1651
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00001652 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05001653 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07001654 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00001655 info = fillInputInfo(
1656 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07001657 } else {
1658 info = state.inputInfo;
1659 }
1660
1661 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07001662 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001663 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07001664
Vishnu Nair00b90132021-11-05 14:03:40 -07001665 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07001666 auto protoMap = layerInfo->mutable_metadata();
1667 for (const auto& entry : state.metadata.mMap) {
1668 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
1669 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07001670 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08001671
1672 LayerProtoHelper::writeToProto(state.destinationFrame,
1673 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07001674}
1675
Prabir Pradhan33da9462022-06-14 14:55:57 +00001676// Applies the given transform to the region, while protecting against overflows caused by any
1677// offsets. If applying the offset in the transform to any of the Rects in the region would result
1678// in an overflow, they are not added to the output Region.
1679static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
1680 const std::string& debugWindowName) {
1681 // Round the translation using the same rounding strategy used by ui::Transform.
1682 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
1683 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
1684
1685 ui::Transform transformWithoutOffset = t;
1686 transformWithoutOffset.set(0.f, 0.f);
1687
1688 const Region transformed = transformWithoutOffset.transform(r);
1689
1690 // Apply the translation to each of the Rects in the region while discarding any that overflow.
1691 Region ret;
1692 for (const auto& rect : transformed) {
1693 Rect newRect;
1694 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
1695 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
1696 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
1697 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
1698 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
1699 debugWindowName.c_str());
1700 continue;
1701 }
1702 ret.orSelf(newRect);
1703 }
1704 return ret;
1705}
1706
Prabir Pradhanc9589c12021-09-22 06:11:43 -07001707void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00001708 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
1709 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08001710 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08001711 }
1712
Chavi Weingarten7f019192023-08-08 20:39:01 +00001713 info.frame = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
chaviw1ff3d1e2020-07-01 15:53:47 -07001714
Prabir Pradhanc9589c12021-09-22 06:11:43 -07001715 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00001716 inputToLayer.set(inputBounds.left, inputBounds.top);
1717 const ui::Transform layerToScreen = getInputTransform();
1718 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08001719
Prabir Pradhanc9589c12021-09-22 06:11:43 -07001720 // InputDispatcher expects a display-to-input transform.
1721 info.transform = inputToDisplay.inverse();
1722
1723 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00001724 info.touchableRegion =
1725 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08001726}
1727
chaviw3277faf2021-05-19 16:45:23 -05001728void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001729 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01001730 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001731 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01001732 }
1733 if (p != nullptr) {
1734 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
1735 }
1736}
1737
Vishnu Naira066d902021-09-13 18:40:17 -07001738gui::DropInputMode Layer::getDropInputMode() const {
1739 gui::DropInputMode mode = mDrawingState.dropInputMode;
1740 if (mode == gui::DropInputMode::ALL) {
1741 return mode;
1742 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001743 sp<Layer> parent = mDrawingParent.promote();
1744 if (parent) {
1745 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07001746 if (parentMode != gui::DropInputMode::NONE) {
1747 return parentMode;
1748 }
1749 }
1750 return mode;
1751}
1752
1753void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001754 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07001755 return;
1756 }
1757
1758 // Check if we need to drop input unconditionally
1759 gui::DropInputMode dropInputMode = getDropInputMode();
1760 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001761 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07001762 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
1763 return;
1764 }
1765
1766 // Check if we need to check if the window is obscured by parent
1767 if (dropInputMode != gui::DropInputMode::OBSCURED) {
1768 return;
1769 }
1770
1771 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001772 sp<Layer> parent = mDrawingParent.promote();
1773 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001774 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07001775 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
1776 static_cast<float>(getAlpha()));
1777 }
1778
1779 // Check if the parent has cropped the buffer
1780 Rect bufferSize = getCroppedBufferSize(getDrawingState());
1781 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001782 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07001783 return;
1784 }
1785
1786 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
1787 // To check if the layer has been cropped, we take the buffer bounds, apply the local
1788 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
1789 // match then the layer has not been cropped by its parents.
1790 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
1791 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
1792
1793 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001794 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07001795 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
1796 getDebugName());
1797 } else {
1798 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
1799 // input if the window is obscured. This check should be done in surfaceflinger but the
1800 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
1801 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001802 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07001803 }
1804}
1805
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00001806WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08001807 if (!hasInputInfo()) {
1808 mDrawingState.inputInfo.name = getName();
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00001809 mDrawingState.inputInfo.ownerUid = gui::Uid{mOwnerUid};
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00001810 mDrawingState.inputInfo.ownerPid = gui::Pid{mOwnerPid};
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001811 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Linnan Li13bf76a2024-05-05 19:18:02 +08001812 mDrawingState.inputInfo.displayId = toLogicalDisplayId(getLayerStack());
chaviw7e72caf2020-12-02 16:50:43 -08001813 }
1814
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00001815 const ui::Transform& displayTransform =
1816 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
1817
chaviw3277faf2021-05-19 16:45:23 -05001818 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08001819 info.id = sequence;
Linnan Li13bf76a2024-05-05 19:18:02 +08001820 info.displayId = toLogicalDisplayId(getLayerStack());
chaviw7e72caf2020-12-02 16:50:43 -08001821
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001822 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08001823
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00001824 if (displayArgs.transform == nullptr) {
1825 // Do not let the window receive touches if it is not associated with a valid display
1826 // transform. We still allow the window to receive keys and prevent ANRs.
1827 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
1828 }
1829
Patrick Williams1caf3b72023-03-31 10:59:10 -05001830 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !isVisibleForInput());
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001831
Bernardo Rufinoea97d182020-08-19 14:43:14 +01001832 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01001833 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07001834 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07001835
Vishnu Nair16a938f2021-09-24 07:14:54 -07001836 // If the window will be blacked out on a display because the display does not have the secure
1837 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00001838 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001839 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07001840 }
1841
Vishnu Nairfed7c122023-03-18 01:54:43 +00001842 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07001843 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00001844 Rect inputBoundsInDisplaySpace;
1845 if (!cropLayer) {
1846 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
1847 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
1848 } else {
1849 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
1850 inputBoundsInDisplaySpace =
1851 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
1852 }
1853 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07001854 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00001855 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
1856 Rect inputBoundsInDisplaySpace =
1857 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
1858 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07001859 }
1860
Winson Chunga30f7c92021-06-29 15:42:56 -07001861 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
1862 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001863 if (isTrustedOverlay()) {
1864 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
1865 }
Winson Chunga30f7c92021-06-29 15:42:56 -07001866
Vishnu Nair494a2e42023-11-10 17:21:19 -08001867 Rect bufferSize = getBufferSize(getDrawingState());
1868 info.contentSize = Size(bufferSize.width(), bufferSize.height());
1869
Robert Carr720e5062018-07-30 17:45:14 -07001870 return info;
1871}
1872
Vishnu Nairfed7c122023-03-18 01:54:43 +00001873Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
1874 const ui::Transform& screenToDisplay) {
1875 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
1876 // frame and transform used for the layer, which determines the bounds and the coordinate space
1877 // within which the layer will receive input.
1878
1879 // Coordinate space definitions:
1880 // - display: The display device's coordinate space. Correlates to pixels on the display.
1881 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
1882 // - layer: The coordinate space of this layer.
1883 // - input: The coordinate space in which this layer will receive input events. This could be
1884 // different than layer space if a surfaceInset is used, which changes the origin
1885 // of the input space.
1886
1887 // Crop the input bounds to ensure it is within the parent's bounds.
1888 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
1889 const ui::Transform layerToScreen = getInputTransform();
1890 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
1891 return Rect{layerToDisplay.transform(croppedInputBounds)};
1892}
1893
Robert Carredd13602020-04-13 17:24:34 -07001894bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00001895 return mDrawingState.inputInfo.token != nullptr ||
1896 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07001897}
1898
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001899compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001900 const DisplayDevice* display) const {
1901 if (!display) return nullptr;
Vishnu Naird47bcee2023-02-24 18:08:51 +00001902 sp<LayerFE> layerFE;
1903 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
1904 for (auto& [p, layer] : mLayerFEs) {
1905 if (p == path) {
1906 layerFE = layer;
1907 }
1908 }
1909
1910 if (!layerFE) return nullptr;
1911 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001912}
1913
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001914compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
1915 const DisplayDevice* display, const frontend::LayerHierarchy::TraversalPath& path) const {
1916 if (!display) return nullptr;
1917 sp<LayerFE> layerFE;
1918 for (auto& [p, layer] : mLayerFEs) {
1919 if (p == path) {
1920 layerFE = layer;
1921 }
1922 }
1923
1924 if (!layerFE) return nullptr;
1925 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
1926}
1927
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001928Region Layer::getVisibleRegion(const DisplayDevice* display) const {
1929 const auto outputLayer = findOutputLayerForDisplay(display);
1930 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08001931}
1932
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001933bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07001934 const State& s(mDrawingState);
1935 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
1936 return true;
1937 }
1938
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001939 sp<Layer> parent = mDrawingParent.promote();
1940 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07001941}
1942
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07001943bool Layer::setDropInputMode(gui::DropInputMode mode) {
1944 if (mDrawingState.dropInputMode == mode) {
1945 return false;
1946 }
1947 mDrawingState.dropInputMode = mode;
1948 return true;
1949}
1950
Patrick Williamsbb25f802022-08-30 23:02:34 +00001951void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
1952 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08001953 const sp<Fence>& releaseFence) {
Patrick Williams7c9fa272024-08-30 12:38:43 +00001954 if (!listener && !mBufferReleaseChannel) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00001955 return;
1956 }
Patrick Williams7c9fa272024-08-30 12:38:43 +00001957
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001958 SFTRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
Patrick Williams7c9fa272024-08-30 12:38:43 +00001959
1960 ReleaseCallbackId callbackId{buffer->getId(), framenumber};
1961 const sp<Fence>& fence = releaseFence ? releaseFence : Fence::NO_FENCE;
liulijuneb489f62022-10-17 22:02:14 +08001962 uint32_t currentMaxAcquiredBufferCount =
1963 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Patrick Williams7c9fa272024-08-30 12:38:43 +00001964
1965 if (listener) {
1966 listener->onReleaseBuffer(callbackId, fence, currentMaxAcquiredBufferCount);
1967 }
1968
1969 if (mBufferReleaseChannel) {
1970 mBufferReleaseChannel->writeReleaseFence(callbackId, fence, currentMaxAcquiredBufferCount);
1971 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00001972}
1973
Melody Hsu793f8362024-01-08 20:00:35 +00001974sp<CallbackHandle> Layer::findCallbackHandle() {
Patrick Williamsbb25f802022-08-30 23:02:34 +00001975 // If we are displayed on multiple displays in a single composition cycle then we would
1976 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
1977 // For example we can only use it if all the displays are client comp, and we need
1978 // to merge all the client comp fences. We could do this, but for now we just
1979 // disable the optimization when a layer is composed on multiple displays.
1980 if (mClearClientCompositionFenceOnLayerDisplayed) {
1981 mLastClientCompositionFence = nullptr;
1982 } else {
1983 mClearClientCompositionFenceOnLayerDisplayed = true;
1984 }
1985
1986 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
1987 // buffer that was presented on this layer. The first transaction that came in this frame that
1988 // replaced the previous buffer on this layer needs this release fence, because the fence will
1989 // let the client know when that previous buffer is removed from the screen.
1990 //
1991 // Every other transaction on this layer does not need a release fence because no other
1992 // Transactions that were set on this layer this frame are going to have their preceding buffer
1993 // removed from the display this frame.
1994 //
1995 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
1996 // buffer so it doesn't need a previous release fence because the layer still needs the previous
1997 // buffer. The second transaction contains a buffer so it needs a previous release fence because
1998 // the previous buffer will be released this frame. The third transaction also contains a
1999 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2000 // transaction will now no longer be presented so it is released immediately and the third
2001 // transaction doesn't need a previous release fence.
2002 sp<CallbackHandle> ch;
2003 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002004 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002005 ch = handle;
2006 break;
2007 }
2008 }
Melody Hsu793f8362024-01-08 20:00:35 +00002009 return ch;
2010}
2011
2012void Layer::prepareReleaseCallbacks(ftl::Future<FenceResult> futureFenceResult,
2013 ui::LayerStack layerStack) {
2014 sp<CallbackHandle> ch = findCallbackHandle();
2015
2016 if (ch != nullptr) {
2017 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2018 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2019 ch->name = mName;
2020 } else {
Melody Hsue4ef87f2024-03-26 23:54:45 +00002021 // If we didn't get a release callback yet (e.g. some scenarios when capturing
2022 // screenshots asynchronously) then make sure we don't drop the fence.
2023 // Older fences for the same layer stack can be dropped when a new fence arrives.
2024 // An assumption here is that RenderEngine performs work sequentially, so an
2025 // incoming fence will not fire before an existing fence.
2026 mAdditionalPreviousReleaseFences.emplace_or_replace(layerStack,
2027 std::move(futureFenceResult));
Melody Hsu793f8362024-01-08 20:00:35 +00002028 }
2029
2030 if (mBufferInfo.mBuffer) {
2031 mPreviouslyPresentedLayerStacks.push_back(layerStack);
2032 }
2033
2034 if (mDrawingState.frameNumber > 0) {
2035 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
2036 }
2037}
2038
2039void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
2040 ui::LayerStack layerStack,
2041 std::function<FenceResult(FenceResult)>&& continuation) {
2042 sp<CallbackHandle> ch = findCallbackHandle();
Alec Mouri9892aac2023-12-11 21:16:59 +00002043
2044 if (!FlagManager::getInstance().screenshot_fence_preservation() && continuation) {
2045 futureFenceResult = ftl::Future(futureFenceResult).then(std::move(continuation)).share();
2046 }
2047
Patrick Williamsbb25f802022-08-30 23:02:34 +00002048 if (ch != nullptr) {
2049 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
Melody Hsu793f8362024-01-08 20:00:35 +00002050 ch->previousSharedReleaseFences.emplace_back(std::move(futureFenceResult));
Patrick Williamsbb25f802022-08-30 23:02:34 +00002051 ch->name = mName;
Alec Mouri9892aac2023-12-11 21:16:59 +00002052 } else if (FlagManager::getInstance().screenshot_fence_preservation()) {
2053 // If we didn't get a release callback yet, e.g. some scenarios when capturing screenshots
2054 // asynchronously, then make sure we don't drop the fence.
Melody Hsu793f8362024-01-08 20:00:35 +00002055 mPreviousReleaseFenceAndContinuations.emplace_back(std::move(futureFenceResult),
2056 std::move(continuation));
Alec Mouri9892aac2023-12-11 21:16:59 +00002057 std::vector<FenceAndContinuation> mergedFences;
2058 sp<Fence> prevFence = nullptr;
2059 // For a layer that's frequently screenshotted, try to merge fences to make sure we don't
2060 // grow unbounded.
Melody Hsu793f8362024-01-08 20:00:35 +00002061 for (const auto& futureAndContinuation : mPreviousReleaseFenceAndContinuations) {
2062 auto result = futureAndContinuation.future.wait_for(0s);
Alec Mouri9892aac2023-12-11 21:16:59 +00002063 if (result != std::future_status::ready) {
Melody Hsu793f8362024-01-08 20:00:35 +00002064 mergedFences.emplace_back(futureAndContinuation);
Alec Mouri9892aac2023-12-11 21:16:59 +00002065 continue;
2066 }
2067
Melody Hsu793f8362024-01-08 20:00:35 +00002068 mergeFence(getDebugName(),
2069 futureAndContinuation.chain().get().value_or(Fence::NO_FENCE), prevFence);
Alec Mouri9892aac2023-12-11 21:16:59 +00002070 }
2071 if (prevFence != nullptr) {
2072 mergedFences.emplace_back(ftl::yield(FenceResult(std::move(prevFence))).share());
2073 }
2074
Melody Hsu793f8362024-01-08 20:00:35 +00002075 mPreviousReleaseFenceAndContinuations.swap(mergedFences);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002076 }
Alec Mouri9892aac2023-12-11 21:16:59 +00002077
Vishnu Nair316b7f42023-10-13 23:44:46 +00002078 if (mBufferInfo.mBuffer) {
2079 mPreviouslyPresentedLayerStacks.push_back(layerStack);
2080 }
Alec Mouri21d94322023-10-17 19:51:39 +00002081
2082 if (mDrawingState.frameNumber > 0) {
2083 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
2084 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002085}
2086
Patrick Williamsbb25f802022-08-30 23:02:34 +00002087void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2088 for (const auto& handle : mDrawingState.callbackHandles) {
Patrick Williams7c9fa272024-08-30 12:38:43 +00002089 handle->bufferReleaseChannel = mBufferReleaseChannel;
Melody Hsu9af30702024-04-17 18:23:43 +00002090 handle->transformHint = mTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002091 handle->dequeueReadyTime = dequeueReadyTime;
2092 handle->currentMaxAcquiredBufferCount =
2093 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002094 SFTRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2095 handle->previousReleaseCallbackId.framenumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002096 }
2097
2098 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002099 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002100 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2101 break;
2102 }
2103 }
2104
Pascal Mütschardd56514e2024-05-24 17:37:13 +02002105 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002106 mDrawingState.callbackHandles = {};
2107}
2108
2109bool Layer::willPresentCurrentTransaction() const {
2110 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2111 return (getSidebandStreamChanged() || getAutoRefresh() ||
2112 (mDrawingState.modified &&
2113 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2114}
2115
2116bool Layer::setTransform(uint32_t transform) {
2117 if (mDrawingState.bufferTransform == transform) return false;
2118 mDrawingState.bufferTransform = transform;
2119 mDrawingState.modified = true;
2120 setTransactionFlags(eTransactionNeeded);
2121 return true;
2122}
2123
2124bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2125 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2126 mDrawingState.sequence++;
2127 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2128 mDrawingState.modified = true;
2129 setTransactionFlags(eTransactionNeeded);
2130 return true;
2131}
2132
2133bool Layer::setBufferCrop(const Rect& bufferCrop) {
2134 if (mDrawingState.bufferCrop == bufferCrop) return false;
2135
2136 mDrawingState.sequence++;
2137 mDrawingState.bufferCrop = bufferCrop;
2138
2139 mDrawingState.modified = true;
2140 setTransactionFlags(eTransactionNeeded);
2141 return true;
2142}
2143
2144bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2145 if (mDrawingState.destinationFrame == destinationFrame) return false;
2146
2147 mDrawingState.sequence++;
2148 mDrawingState.destinationFrame = destinationFrame;
2149
2150 mDrawingState.modified = true;
2151 setTransactionFlags(eTransactionNeeded);
2152 return true;
2153}
2154
2155// Translate destination frame into scale and position. If a destination frame is not set, use the
2156// provided scale and position
2157bool Layer::updateGeometry() {
2158 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2159 mDrawingState.destinationFrame.isEmpty()) {
2160 // If destination frame is not set, use the requested transform set via
2161 // Layer::setPosition and Layer::setMatrix.
2162 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2163 }
2164
2165 Rect destRect = mDrawingState.destinationFrame;
2166 int32_t destW = destRect.width();
2167 int32_t destH = destRect.height();
2168 if (destRect.left < 0) {
2169 destRect.left = 0;
2170 destRect.right = destW;
2171 }
2172 if (destRect.top < 0) {
2173 destRect.top = 0;
2174 destRect.bottom = destH;
2175 }
2176
2177 if (!mDrawingState.buffer) {
2178 ui::Transform t;
2179 t.set(destRect.left, destRect.top);
2180 return assignTransform(&mDrawingState.transform, t);
2181 }
2182
2183 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2184 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2185 // Undo any transformations on the buffer.
2186 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2187 std::swap(bufferWidth, bufferHeight);
2188 }
Leon Scroggins III85d4b222023-05-09 13:58:18 -04002189 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00002190 if (mDrawingState.transformToDisplayInverse) {
2191 if (invTransform & ui::Transform::ROT_90) {
2192 std::swap(bufferWidth, bufferHeight);
2193 }
2194 }
2195
2196 float sx = destW / static_cast<float>(bufferWidth);
2197 float sy = destH / static_cast<float>(bufferHeight);
2198 ui::Transform t;
2199 t.set(sx, 0, 0, sy);
2200 t.set(destRect.left, destRect.top);
2201 return assignTransform(&mDrawingState.transform, t);
2202}
2203
2204bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
2205 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
2206 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
2207 return false;
2208 }
2209
2210 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
2211
2212 mDrawingState.sequence++;
2213 mDrawingState.modified = true;
2214 setTransactionFlags(eTransactionNeeded);
2215
2216 return true;
2217}
2218
2219bool Layer::setPosition(float x, float y) {
2220 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
2221 return false;
2222 }
2223
2224 mRequestedTransform.set(x, y);
2225
2226 mDrawingState.sequence++;
2227 mDrawingState.modified = true;
2228 setTransactionFlags(eTransactionNeeded);
2229
2230 return true;
2231}
2232
Dorin Drimuse5374e52023-08-02 17:52:43 +00002233void Layer::releasePreviousBuffer() {
2234 mReleasePreviousBuffer = true;
2235 if (!mBufferInfo.mBuffer ||
2236 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
2237 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
2238 // If mDrawingState has a buffer, and we are about to update again
2239 // before swapping to drawing state, then the first buffer will be
2240 // dropped and we should decrement the pending buffer count and
2241 // call any release buffer callbacks if set.
2242 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
2243 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
2244 mDrawingState.acquireFence);
Dominic Lemire95c4ecc2024-07-09 12:06:18 -07002245 const int32_t layerId = getSequence();
2246 mFlinger->mTimeStats->removeTimeRecord(layerId, mDrawingState.frameNumber);
Dorin Drimuse5374e52023-08-02 17:52:43 +00002247 decrementPendingBufferCount();
2248 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
2249 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
2250 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX, systemTime());
2251 mDrawingState.bufferSurfaceFrameTX.reset();
2252 }
2253 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
2254 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
2255 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
2256 mLastClientCompositionFence);
2257 mLastClientCompositionFence = nullptr;
2258 }
2259}
2260
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002261void Layer::resetDrawingStateBufferInfo() {
2262 mDrawingState.producerId = 0;
2263 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +00002264 mDrawingState.previousFrameNumber = 0;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002265 mDrawingState.releaseBufferListener = nullptr;
2266 mDrawingState.buffer = nullptr;
2267 mDrawingState.acquireFence = sp<Fence>::make(-1);
2268 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
2269 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
2270 mDrawingState.releaseBufferEndpoint = nullptr;
2271}
2272
Patrick Williamsbb25f802022-08-30 23:02:34 +00002273bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
2274 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
Vishnu Nair39a74a92024-07-29 19:01:50 +00002275 bool isAutoTimestamp, const FrameTimelineInfo& info, gui::GameMode gameMode) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002276 SFTRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00002277
2278 const bool frameNumberChanged =
2279 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
2280 const uint64_t frameNumber =
2281 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002282 SFTRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002283
2284 if (mDrawingState.buffer) {
Dorin Drimuse5374e52023-08-02 17:52:43 +00002285 releasePreviousBuffer();
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002286 } else if (buffer) {
Vishnu Nairc09c0232023-03-02 03:22:35 +00002287 // if we are latching a buffer for the first time then clear the mLastLatchTime since
2288 // we don't want to incorrectly classify a frame if we miss the desired present time.
2289 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002290 }
2291
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002292 mDrawingState.desiredPresentTime = desiredPresentTime;
2293 mDrawingState.isAutoTimestamp = isAutoTimestamp;
2294 mDrawingState.latchedVsyncId = info.vsyncId;
Ady Abraham55269162023-05-09 11:26:06 -07002295 mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002296 mDrawingState.modified = true;
2297 if (!buffer) {
2298 resetDrawingStateBufferInfo();
2299 setTransactionFlags(eTransactionNeeded);
2300 mDrawingState.bufferSurfaceFrameTX = nullptr;
Vishnu Nair39a74a92024-07-29 19:01:50 +00002301 setFrameTimelineVsyncForBufferlessTransaction(info, postTime, gameMode);
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002302 return true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00002303 } else {
2304 // release sideband stream if it exists and a non null buffer is being set
2305 if (mDrawingState.sidebandStream != nullptr) {
Vishnu Nair39a74a92024-07-29 19:01:50 +00002306 setSidebandStream(nullptr, info, postTime, gameMode);
Dorin Drimuse5374e52023-08-02 17:52:43 +00002307 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002308 }
2309
Vishnu Naird1f74982023-06-15 20:16:51 -07002310 if ((mDrawingState.producerId > bufferData.producerId) ||
2311 ((mDrawingState.producerId == bufferData.producerId) &&
2312 (mDrawingState.frameNumber > frameNumber))) {
2313 ALOGE("Out of order buffers detected for %s producedId=%d frameNumber=%" PRIu64
2314 " -> producedId=%d frameNumber=%" PRIu64,
2315 getDebugName(), mDrawingState.producerId, mDrawingState.frameNumber,
2316 bufferData.producerId, frameNumber);
2317 TransactionTraceWriter::getInstance().invoke("out_of_order_buffers_", /*overwrite=*/false);
2318 }
2319
liulijuneb489f62022-10-17 22:02:14 +08002320 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -07002321 mDrawingState.barrierProducerId =
2322 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002323 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -07002324 mDrawingState.barrierFrameNumber =
2325 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
2326
Patrick Williamsbb25f802022-08-30 23:02:34 +00002327 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
2328 mDrawingState.buffer = std::move(buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002329 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
2330 ? bufferData.acquireFence
2331 : Fence::NO_FENCE;
2332 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
2333 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
2334 // We latched this buffer unsiganled, so we need to pass the acquire fence
2335 // on the callback instead of just the acquire time, since it's unknown at
2336 // this point.
2337 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
2338 } else {
2339 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
2340 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002341 setTransactionFlags(eTransactionNeeded);
2342
2343 const int32_t layerId = getSequence();
2344 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
Vishnu Nair39a74a92024-07-29 19:01:50 +00002345 mOwnerUid, postTime, gameMode);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002346
Vishnu Nair39a74a92024-07-29 19:01:50 +00002347 setFrameTimelineVsyncForBufferTransaction(info, postTime, gameMode);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002348
Nergi Rahardi39f510f2024-05-23 15:16:54 +09002349 if (bufferData.dequeueTime > 0) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002350 const uint64_t bufferId = mDrawingState.buffer->getId();
2351 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
Nergi Rahardi39f510f2024-05-23 15:16:54 +09002352 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber,
2353 bufferData.dequeueTime,
Patrick Williamsbb25f802022-08-30 23:02:34 +00002354 FrameTracer::FrameEvent::DEQUEUE);
2355 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
2356 FrameTracer::FrameEvent::QUEUE);
2357 }
2358
2359 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
Arthur Hungc70bee22023-06-02 01:35:52 +00002360
2361 // If the layer had been updated a TextureView, this would make sure the present time could be
2362 // same to TextureView update when it's a small dirty, and get the correct heuristic rate.
Jerry Chang36678002023-11-29 16:56:17 +00002363 if (mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00002364 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
2365 mUsedVsyncIdForRefreshRateSelection = true;
2366 }
2367 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002368 return true;
2369}
2370
Vishnu Nairef68d6d2023-02-28 06:18:27 +00002371void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
2372 mDrawingState.desiredPresentTime = desiredPresentTime;
2373 mDrawingState.isAutoTimestamp = isAutoTimestamp;
2374}
2375
Vishnu Nair47b7bb42023-09-29 16:27:33 -07002376void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps, nsecs_t now) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002377 SFTRACE_CALL();
Vishnu Nairef68d6d2023-02-28 06:18:27 +00002378 const nsecs_t presentTime = [&] {
Ady Abraham55269162023-05-09 11:26:06 -07002379 if (!mDrawingState.isAutoTimestamp) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002380 SFTRACE_FORMAT_INSTANT("desiredPresentTime");
Ady Abraham55269162023-05-09 11:26:06 -07002381 return mDrawingState.desiredPresentTime;
2382 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00002383
Ady Abraham55269162023-05-09 11:26:06 -07002384 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
2385 const auto prediction =
2386 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
2387 mDrawingState.latchedVsyncId);
2388 if (prediction.has_value()) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002389 SFTRACE_FORMAT_INSTANT("predictedPresentTime");
Arthur Hungc70bee22023-06-02 01:35:52 +00002390 mMaxTimeForUseVsyncId = prediction->presentTime +
2391 scheduler::LayerHistory::kMaxPeriodForHistory.count();
Ady Abraham55269162023-05-09 11:26:06 -07002392 return prediction->presentTime;
2393 }
2394 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00002395
Jerry Chang36678002023-11-29 16:56:17 +00002396 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00002397 return static_cast<nsecs_t>(0);
2398 }
2399
2400 // If the layer is not an application and didn't set an explicit rate or desiredPresentTime,
2401 // return "0" to tell the layer history that it will use the max refresh rate without
2402 // calculating the adaptive rate.
2403 if (mWindowType != WindowInfo::Type::APPLICATION &&
2404 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
2405 return static_cast<nsecs_t>(0);
2406 }
2407
2408 // Return the valid present time only when the layer potentially updated a TextureView so
2409 // LayerHistory could heuristically calculate the rate if the UI is continually updating.
2410 if (mUsedVsyncIdForRefreshRateSelection) {
2411 const auto prediction =
2412 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
2413 mDrawingState.latchedVsyncId);
2414 if (prediction.has_value()) {
2415 if (mMaxTimeForUseVsyncId >= prediction->presentTime) {
2416 return prediction->presentTime;
2417 }
2418 mUsedVsyncIdForRefreshRateSelection = false;
2419 }
2420 }
2421
Vishnu Nairef68d6d2023-02-28 06:18:27 +00002422 return static_cast<nsecs_t>(0);
2423 }();
Ady Abraham55269162023-05-09 11:26:06 -07002424
Vishnu Nair2665ca92024-07-09 22:08:15 +00002425 if (SFTRACE_ENABLED() && presentTime > 0) {
Ady Abraham55269162023-05-09 11:26:06 -07002426 const auto presentIn = TimePoint::fromNs(presentTime) - TimePoint::now();
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002427 SFTRACE_FORMAT_INSTANT("presentIn %s", to_string(presentIn).c_str());
Ady Abraham55269162023-05-09 11:26:06 -07002428 }
2429
Vishnu Nair47b7bb42023-09-29 16:27:33 -07002430 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00002431 scheduler::LayerHistory::LayerUpdateType::Buffer);
2432}
2433
Vishnu Nair47b7bb42023-09-29 16:27:33 -07002434void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps, nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00002435 const nsecs_t presentTime =
2436 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
Vishnu Nair47b7bb42023-09-29 16:27:33 -07002437 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00002438 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
2439}
2440
Patrick Williamsbb25f802022-08-30 23:02:34 +00002441bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002442 if (mDrawingState.dataspace == dataspace) return false;
2443 mDrawingState.dataspace = dataspace;
2444 mDrawingState.modified = true;
2445 setTransactionFlags(eTransactionNeeded);
2446 return true;
2447}
2448
John Reck68796592023-01-25 13:47:12 -05002449bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07002450 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
2451 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05002452 return false;
Sally Qi963049b2023-03-23 14:06:21 -07002453 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
2454 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05002455 mDrawingState.modified = true;
2456 setTransactionFlags(eTransactionNeeded);
2457 return true;
2458}
2459
Alec Mouri1b0d4e12024-02-12 22:27:19 +00002460bool Layer::setDesiredHdrHeadroom(float desiredRatio) {
2461 if (mDrawingState.desiredHdrSdrRatio == desiredRatio) return false;
2462 mDrawingState.desiredHdrSdrRatio = desiredRatio;
2463 mDrawingState.modified = true;
2464 setTransactionFlags(eTransactionNeeded);
2465 return true;
2466}
2467
Alec Mourif4af03e2023-02-11 00:25:24 +00002468bool Layer::setCachingHint(gui::CachingHint cachingHint) {
2469 if (mDrawingState.cachingHint == cachingHint) return false;
2470 mDrawingState.cachingHint = cachingHint;
2471 mDrawingState.modified = true;
2472 setTransactionFlags(eTransactionNeeded);
2473 return true;
2474}
2475
Patrick Williamsbb25f802022-08-30 23:02:34 +00002476bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
2477 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
2478 mDrawingState.hdrMetadata = hdrMetadata;
2479 mDrawingState.modified = true;
2480 setTransactionFlags(eTransactionNeeded);
2481 return true;
2482}
2483
2484bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00002485 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002486 mDrawingState.surfaceDamageRegion = surfaceDamage;
2487 mDrawingState.modified = true;
2488 setTransactionFlags(eTransactionNeeded);
Arthur Hung69f95222023-10-04 07:39:02 +00002489 setIsSmallDirty(surfaceDamage, getTransform());
Patrick Williamsbb25f802022-08-30 23:02:34 +00002490 return true;
2491}
2492
2493bool Layer::setApi(int32_t api) {
2494 if (mDrawingState.api == api) return false;
2495 mDrawingState.api = api;
2496 mDrawingState.modified = true;
2497 setTransactionFlags(eTransactionNeeded);
2498 return true;
2499}
2500
Dorin Drimuse5374e52023-08-02 17:52:43 +00002501bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream, const FrameTimelineInfo& info,
Vishnu Nair39a74a92024-07-29 19:01:50 +00002502 nsecs_t postTime, gui::GameMode gameMode) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002503 if (mDrawingState.sidebandStream == sidebandStream) return false;
2504
2505 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
2506 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
2507 } else if (sidebandStream != nullptr) {
2508 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
2509 }
2510
2511 mDrawingState.sidebandStream = sidebandStream;
2512 mDrawingState.modified = true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00002513 if (sidebandStream != nullptr && mDrawingState.buffer != nullptr) {
2514 releasePreviousBuffer();
2515 resetDrawingStateBufferInfo();
2516 mDrawingState.bufferSurfaceFrameTX = nullptr;
Vishnu Nair39a74a92024-07-29 19:01:50 +00002517 setFrameTimelineVsyncForBufferlessTransaction(info, postTime, gameMode);
Dorin Drimuse5374e52023-08-02 17:52:43 +00002518 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002519 setTransactionFlags(eTransactionNeeded);
2520 if (!mSidebandStreamChanged.exchange(true)) {
2521 // mSidebandStreamChanged was false
2522 mFlinger->onLayerUpdate();
2523 }
2524 return true;
2525}
2526
Vishnu Nair3af0ec02023-02-10 04:13:48 +00002527bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
2528 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002529 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
2530 if (handles.empty()) {
2531 mReleasePreviousBuffer = false;
2532 return false;
2533 }
2534
Pascal Muetschard81cef292023-02-06 12:18:52 +01002535 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002536 for (const auto& handle : handles) {
2537 // If this transaction set a buffer on this layer, release its previous buffer
2538 handle->releasePreviousBuffer = mReleasePreviousBuffer;
2539
2540 // If this layer will be presented in this frame
2541 if (willPresent) {
2542 // If this transaction set an acquire fence on this layer, set its acquire time
2543 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
2544 handle->frameNumber = mDrawingState.frameNumber;
Alec Mouri21d94322023-10-17 19:51:39 +00002545 handle->previousFrameNumber = mDrawingState.previousFrameNumber;
Melody Hsu793f8362024-01-08 20:00:35 +00002546 if (FlagManager::getInstance().ce_fence_promise() &&
Alec Mouri9892aac2023-12-11 21:16:59 +00002547 mPreviousReleaseBufferEndpoint == handle->listener) {
Melody Hsue4ef87f2024-03-26 23:54:45 +00002548 // Add fence from previous screenshot now so that it can be dispatched to the
Alec Mouri9892aac2023-12-11 21:16:59 +00002549 // client.
Melody Hsue4ef87f2024-03-26 23:54:45 +00002550 for (auto& [_, future] : mAdditionalPreviousReleaseFences) {
2551 handle->previousReleaseFences.emplace_back(std::move(future));
Alec Mouri9892aac2023-12-11 21:16:59 +00002552 }
2553 mAdditionalPreviousReleaseFences.clear();
Melody Hsu793f8362024-01-08 20:00:35 +00002554 } else if (FlagManager::getInstance().screenshot_fence_preservation() &&
2555 mPreviousReleaseBufferEndpoint == handle->listener) {
2556 // Add fences from previous screenshots now so that they can be dispatched to the
2557 // client.
2558 for (const auto& futureAndContinution : mPreviousReleaseFenceAndContinuations) {
2559 handle->previousSharedReleaseFences.emplace_back(futureAndContinution.chain());
2560 }
2561 mPreviousReleaseFenceAndContinuations.clear();
Alec Mouri9892aac2023-12-11 21:16:59 +00002562 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002563 // Store so latched time and release fence can be set
2564 mDrawingState.callbackHandles.push_back(handle);
2565
2566 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01002567 // Queue this handle to be notified below.
2568 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002569 }
2570 }
2571
Pascal Muetschard81cef292023-02-06 12:18:52 +01002572 if (!remainingHandles.empty()) {
2573 // Notify the transaction completed threads these handles are done. These are only the
2574 // handles that were not added to the mDrawingState, which will be notified later.
Pascal Mütschardd56514e2024-05-24 17:37:13 +02002575 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles);
Pascal Muetschard81cef292023-02-06 12:18:52 +01002576 }
2577
Patrick Williamsbb25f802022-08-30 23:02:34 +00002578 mReleasePreviousBuffer = false;
2579 mCallbackHandleAcquireTimeOrFence = -1;
2580
2581 return willPresent;
2582}
2583
2584Rect Layer::getBufferSize(const State& /*s*/) const {
2585 // for buffer state layers we use the display frame size as the buffer size.
2586
2587 if (mBufferInfo.mBuffer == nullptr) {
2588 return Rect::INVALID_RECT;
2589 }
2590
2591 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
2592 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
2593
2594 // Undo any transformations on the buffer and return the result.
2595 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
2596 std::swap(bufWidth, bufHeight);
2597 }
2598
2599 if (getTransformToDisplayInverse()) {
Leon Scroggins III85d4b222023-05-09 13:58:18 -04002600 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00002601 if (invTransform & ui::Transform::ROT_90) {
2602 std::swap(bufWidth, bufHeight);
2603 }
2604 }
2605
2606 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
2607}
2608
2609FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
2610 if (mBufferInfo.mBuffer == nullptr) {
2611 return parentBounds;
2612 }
2613
2614 return getBufferSize(getDrawingState()).toFloatRect();
2615}
2616
2617bool Layer::fenceHasSignaled() const {
2618 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
2619 return true;
2620 }
2621
2622 const bool fenceSignaled =
2623 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
2624 if (!fenceSignaled) {
2625 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
2626 TimeStats::LatchSkipReason::LateAcquire);
2627 }
2628
2629 return fenceSignaled;
2630}
2631
Vishnu Nair3af0ec02023-02-10 04:13:48 +00002632void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002633 for (const auto& handle : mDrawingState.callbackHandles) {
2634 handle->refreshStartTime = refreshStartTime;
2635 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002636}
2637
2638void Layer::setAutoRefresh(bool autoRefresh) {
2639 mDrawingState.autoRefresh = autoRefresh;
2640}
2641
2642bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
2643 // 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 +00002644 auto* snapshot = editLayerSnapshot();
2645 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00002646
2647 if (mSidebandStreamChanged.exchange(false)) {
2648 const State& s(getDrawingState());
2649 // mSidebandStreamChanged was true
2650 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00002651 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002652 if (mSidebandStream != nullptr) {
2653 setTransactionFlags(eTransactionNeeded);
2654 mFlinger->setTransactionFlags(eTraversalNeeded);
2655 }
2656 recomputeVisibleRegions = true;
2657
2658 return true;
2659 }
2660 return false;
2661}
2662
2663bool Layer::hasFrameUpdate() const {
2664 const State& c(getDrawingState());
2665 return (mDrawingStateModified || mDrawingState.modified) &&
2666 (c.buffer != nullptr || c.bgColorLayer != nullptr);
2667}
2668
Vishnu Naird47bcee2023-02-24 18:08:51 +00002669void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002670 const State& s(getDrawingState());
2671
2672 if (!s.buffer) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002673 if (bgColorOnly || mBufferInfo.mBuffer) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002674 for (auto& handle : mDrawingState.callbackHandles) {
2675 handle->latchTime = latchTime;
2676 }
2677 }
2678 return;
2679 }
2680
2681 for (auto& handle : mDrawingState.callbackHandles) {
2682 if (handle->frameNumber == mDrawingState.frameNumber) {
2683 handle->latchTime = latchTime;
2684 }
2685 }
2686
2687 const int32_t layerId = getSequence();
2688 const uint64_t bufferId = mDrawingState.buffer->getId();
2689 const uint64_t frameNumber = mDrawingState.frameNumber;
2690 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
2691 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
2692 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
2693
2694 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
2695 FrameTracer::FrameEvent::ACQUIRE_FENCE);
2696 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
2697 FrameTracer::FrameEvent::LATCH);
2698
2699 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
2700 if (bufferSurfaceFrame != nullptr &&
2701 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
2702 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
2703 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
2704 // are processing the next state.
2705 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
2706 mDrawingState.acquireFenceTime->getSignalTime(),
2707 latchTime);
2708 mDrawingState.bufferSurfaceFrameTX.reset();
2709 }
2710
2711 std::deque<sp<CallbackHandle>> remainingHandles;
2712 mFlinger->getTransactionCallbackInvoker()
2713 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
2714 mDrawingState.callbackHandles = remainingHandles;
2715
2716 mDrawingStateModified = false;
2717}
2718
2719void Layer::gatherBufferInfo() {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002720 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
2721 mPreviousReleaseBufferEndpoint = mBufferInfo.mReleaseBufferEndpoint;
2722 if (!mDrawingState.buffer) {
2723 mBufferInfo = {};
2724 return;
2725 }
2726
2727 if ((!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer))) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002728 decrementPendingBufferCount();
2729 }
2730
Patrick Williamsbb25f802022-08-30 23:02:34 +00002731 mBufferInfo.mBuffer = mDrawingState.buffer;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002732 mBufferInfo.mReleaseBufferEndpoint = mDrawingState.releaseBufferEndpoint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002733 mBufferInfo.mFence = mDrawingState.acquireFence;
2734 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
2735 mBufferInfo.mPixelFormat =
2736 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
2737 mBufferInfo.mFrameLatencyNeeded = true;
2738 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
2739 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
2740 mBufferInfo.mFence = mDrawingState.acquireFence;
2741 mBufferInfo.mTransform = mDrawingState.bufferTransform;
2742 auto lastDataspace = mBufferInfo.mDataspace;
2743 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00002744 if (mBufferInfo.mBuffer != nullptr) {
2745 auto& mapper = GraphicBufferMapper::get();
2746 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
2747 // and don't need to possibly remaps buffers.
2748 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
2749 status_t err = OK;
2750 {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002751 SFTRACE_NAME("getDataspace");
Alec Mouri74c7ae12023-03-26 02:57:47 +00002752 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
2753 }
2754 if (err != OK || dataspace != mBufferInfo.mDataspace) {
2755 {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002756 SFTRACE_NAME("setDataspace");
Alec Mouri74c7ae12023-03-26 02:57:47 +00002757 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
2758 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
2759 }
2760
2761 // Some GPU drivers may cache gralloc metadata which means before we composite we need
2762 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
2763 // compatible with old vendors, with a ticking clock.
2764 static const int32_t kVendorVersion =
Alec Mouri8a06fb72023-11-16 22:07:13 +00002765 base::GetIntProperty("ro.board.api_level", __ANDROID_API_FUTURE__);
Alec Mouri74c7ae12023-03-26 02:57:47 +00002766 if (const auto format =
2767 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
2768 mBufferInfo.mBuffer->getPixelFormat());
2769 err == OK && kVendorVersion < __ANDROID_API_U__ &&
2770 (format ==
2771 aidl::android::hardware::graphics::common::PixelFormat::
2772 IMPLEMENTATION_DEFINED ||
2773 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
2774 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
2775 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
2776 mBufferInfo.mBuffer->remapBuffer();
2777 }
2778 }
2779 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002780 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05002781 mFlinger->mHdrLayerInfoChanged = true;
2782 }
Sally Qi963049b2023-03-23 14:06:21 -07002783 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
2784 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05002785 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002786 }
2787 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
2788 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
2789 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
2790 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
2791 mBufferInfo.mApi = mDrawingState.api;
2792 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002793}
2794
2795Rect Layer::computeBufferCrop(const State& s) {
2796 if (s.buffer && !s.bufferCrop.isEmpty()) {
2797 Rect bufferCrop;
2798 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
2799 return bufferCrop;
2800 } else if (s.buffer) {
2801 return s.buffer->getBounds();
2802 } else {
2803 return s.bufferCrop;
2804 }
2805}
2806
Patrick Williamsbb25f802022-08-30 23:02:34 +00002807void Layer::decrementPendingBufferCount() {
2808 int32_t pendingBuffers = --mPendingBufferTransactions;
2809 tracePendingBufferCount(pendingBuffers);
2810}
2811
2812void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002813 SFTRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002814}
2815
2816/*
2817 * We don't want to send the layer's transform to input, but rather the
2818 * parent's transform. This is because Layer's transform is
2819 * information about how the buffer is placed on screen. The parent's
2820 * transform makes more sense to send since it's information about how the
2821 * layer is placed on screen. This transform is used by input to determine
2822 * how to go from screen space back to window space.
2823 */
2824ui::Transform Layer::getInputTransform() const {
2825 if (!hasBufferOrSidebandStream()) {
2826 return getTransform();
2827 }
2828 sp<Layer> parent = mDrawingParent.promote();
2829 if (parent == nullptr) {
2830 return ui::Transform();
2831 }
2832
2833 return parent->getTransform();
2834}
2835
2836/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00002837 * Returns the bounds used to fill the input frame and the touchable region.
2838 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00002839 * Similar to getInputTransform, we need to update the bounds to include the transform.
2840 * This is because bounds don't include the buffer transform, where the input assumes
2841 * that's already included.
2842 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00002843std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
2844 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
2845 FloatRect inputBounds = croppedBufferSize.toFloatRect();
2846 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
2847 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
2848 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002849 }
2850
Vishnu Nairfed7c122023-03-18 01:54:43 +00002851 bool inputBoundsValid = croppedBufferSize.isValid();
2852 if (!inputBoundsValid) {
2853 /**
2854 * Input bounds are based on the layer crop or buffer size. But if we are using
2855 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
2856 * we can use the parent bounds as the input bounds if the layer does not have buffer
2857 * or a crop. We want to unify this logic but because of compat reasons we cannot always
2858 * use the parent bounds. A layer without a buffer can get input. So when a window is
2859 * initially added, its touchable region can fill its parent layer bounds and that can
2860 * have negative consequences.
2861 */
2862 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00002863 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00002864
2865 // Clamp surface inset to the input bounds.
2866 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
2867 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
2868 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
2869
2870 // Apply the insets to the input bounds.
2871 inputBounds.left += xSurfaceInset;
2872 inputBounds.top += ySurfaceInset;
2873 inputBounds.right -= xSurfaceInset;
2874 inputBounds.bottom -= ySurfaceInset;
2875
2876 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00002877}
2878
Ady Abraham005398b2023-06-05 13:59:41 -07002879bool Layer::isSimpleBufferUpdate(const layer_state_t& s) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002880 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
2881
2882 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
2883 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
2884 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
Ady Abrahambb1ad762024-03-27 18:31:28 -07002885 layer_state_t::eLayerStackChanged | layer_state_t::eReparent |
2886 (FlagManager::getInstance().latch_unsignaled_with_auto_refresh_changed()
2887 ? 0
2888 : layer_state_t::eAutoRefreshChanged);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002889
Patrick Williamsbb25f802022-08-30 23:02:34 +00002890 if ((s.what & requiredFlags) != requiredFlags) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002891 SFTRACE_FORMAT_INSTANT("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
2892 (s.what | requiredFlags) & ~s.what);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002893 return false;
2894 }
2895
2896 if (s.what & deniedFlags) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002897 SFTRACE_FORMAT_INSTANT("%s: false [has denied flags 0x%" PRIx64 "]", __func__,
2898 s.what & deniedFlags);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002899 return false;
2900 }
2901
Patrick Williamsbb25f802022-08-30 23:02:34 +00002902 if (s.what & layer_state_t::ePositionChanged) {
2903 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002904 SFTRACE_FORMAT_INSTANT("%s: false [ePositionChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002905 return false;
2906 }
2907 }
2908
2909 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00002910 if (mDrawingState.color.a != s.color.a) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002911 SFTRACE_FORMAT_INSTANT("%s: false [eAlphaChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002912 return false;
2913 }
2914 }
2915
2916 if (s.what & layer_state_t::eColorTransformChanged) {
2917 if (mDrawingState.colorTransform != s.colorTransform) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002918 SFTRACE_FORMAT_INSTANT("%s: false [eColorTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002919 return false;
2920 }
2921 }
2922
2923 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00002924 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002925 SFTRACE_FORMAT_INSTANT("%s: false [eBackgroundColorChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002926 return false;
2927 }
2928 }
2929
2930 if (s.what & layer_state_t::eMatrixChanged) {
2931 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
2932 mRequestedTransform.dtdy() != s.matrix.dtdy ||
2933 mRequestedTransform.dtdx() != s.matrix.dtdx ||
2934 mRequestedTransform.dsdy() != s.matrix.dsdy) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002935 SFTRACE_FORMAT_INSTANT("%s: false [eMatrixChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002936 return false;
2937 }
2938 }
2939
2940 if (s.what & layer_state_t::eCornerRadiusChanged) {
2941 if (mDrawingState.cornerRadius != s.cornerRadius) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002942 SFTRACE_FORMAT_INSTANT("%s: false [eCornerRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002943 return false;
2944 }
2945 }
2946
2947 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
2948 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002949 SFTRACE_FORMAT_INSTANT("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002950 return false;
2951 }
2952 }
2953
Vishnu Nairbbceb462022-10-10 04:52:13 +00002954 if (s.what & layer_state_t::eBufferTransformChanged) {
2955 if (mDrawingState.bufferTransform != s.bufferTransform) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002956 SFTRACE_FORMAT_INSTANT("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002957 return false;
2958 }
2959 }
2960
2961 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
2962 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002963 SFTRACE_FORMAT_INSTANT("%s: false [eTransformToDisplayInverseChanged changed]",
2964 __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002965 return false;
2966 }
2967 }
2968
2969 if (s.what & layer_state_t::eCropChanged) {
2970 if (mDrawingState.crop != s.crop) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002971 SFTRACE_FORMAT_INSTANT("%s: false [eCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002972 return false;
2973 }
2974 }
2975
2976 if (s.what & layer_state_t::eDataspaceChanged) {
2977 if (mDrawingState.dataspace != s.dataspace) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002978 SFTRACE_FORMAT_INSTANT("%s: false [eDataspaceChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002979 return false;
2980 }
2981 }
2982
2983 if (s.what & layer_state_t::eHdrMetadataChanged) {
2984 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002985 SFTRACE_FORMAT_INSTANT("%s: false [eHdrMetadataChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002986 return false;
2987 }
2988 }
2989
2990 if (s.what & layer_state_t::eSidebandStreamChanged) {
2991 if (mDrawingState.sidebandStream != s.sidebandStream) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002992 SFTRACE_FORMAT_INSTANT("%s: false [eSidebandStreamChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002993 return false;
2994 }
2995 }
2996
2997 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
2998 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002999 SFTRACE_FORMAT_INSTANT("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003000 return false;
3001 }
3002 }
3003
3004 if (s.what & layer_state_t::eShadowRadiusChanged) {
3005 if (mDrawingState.shadowRadius != s.shadowRadius) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003006 SFTRACE_FORMAT_INSTANT("%s: false [eShadowRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003007 return false;
3008 }
3009 }
3010
3011 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3012 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003013 SFTRACE_FORMAT_INSTANT("%s: false [eFixedTransformHintChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003014 return false;
3015 }
3016 }
3017
3018 if (s.what & layer_state_t::eTrustedOverlayChanged) {
Vishnu Nair9e0017e2024-05-22 19:02:44 +00003019 if (mDrawingState.isTrustedOverlay != (s.trustedOverlay == gui::TrustedOverlay::ENABLED)) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003020 SFTRACE_FORMAT_INSTANT("%s: false [eTrustedOverlayChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003021 return false;
3022 }
3023 }
3024
3025 if (s.what & layer_state_t::eStretchChanged) {
3026 StretchEffect temp = s.stretchEffect;
3027 temp.sanitize();
3028 if (mDrawingState.stretchEffect != temp) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003029 SFTRACE_FORMAT_INSTANT("%s: false [eStretchChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003030 return false;
3031 }
3032 }
3033
3034 if (s.what & layer_state_t::eBufferCropChanged) {
3035 if (mDrawingState.bufferCrop != s.bufferCrop) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003036 SFTRACE_FORMAT_INSTANT("%s: false [eBufferCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003037 return false;
3038 }
3039 }
3040
3041 if (s.what & layer_state_t::eDestinationFrameChanged) {
3042 if (mDrawingState.destinationFrame != s.destinationFrame) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003043 SFTRACE_FORMAT_INSTANT("%s: false [eDestinationFrameChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003044 return false;
3045 }
3046 }
3047
3048 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3049 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003050 SFTRACE_FORMAT_INSTANT("%s: false [eDimmingEnabledChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003051 return false;
3052 }
3053 }
3054
John Reck68796592023-01-25 13:47:12 -05003055 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07003056 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
3057 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003058 SFTRACE_FORMAT_INSTANT("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05003059 return false;
3060 }
3061 }
3062
Alec Mouri1b0d4e12024-02-12 22:27:19 +00003063 if (s.what & layer_state_t::eDesiredHdrHeadroomChanged) {
3064 if (mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003065 SFTRACE_FORMAT_INSTANT("%s: false [eDesiredHdrHeadroomChanged changed]", __func__);
Alec Mouri1b0d4e12024-02-12 22:27:19 +00003066 return false;
3067 }
3068 }
3069
Patrick Williamsbb25f802022-08-30 23:02:34 +00003070 return true;
3071}
3072
Vishnu Naire14c6b32022-08-06 04:20:15 +00003073sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003074 // 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 +00003075 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003076}
3077
Vishnu Naire14c6b32022-08-06 04:20:15 +00003078const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003079 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003080}
3081
Vishnu Naire14c6b32022-08-06 04:20:15 +00003082LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003083 return mSnapshot.get();
3084}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003085
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003086std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3087 return std::move(mSnapshot);
3088}
3089
3090void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3091 mSnapshot = std::move(snapshot);
3092}
3093
Patrick Williamsbb25f802022-08-30 23:02:34 +00003094const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003095 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003096}
3097
Patrick Williams7584c6a2022-10-29 02:10:58 +00003098sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Lloyd Pique70ddc672024-04-30 18:20:40 -07003099 auto result = mFlinger->getFactory().createLayerFE(mName, this);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003100 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3101 return result;
3102}
3103
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003104sp<LayerFE> Layer::getCompositionEngineLayerFE(
3105 const frontend::LayerHierarchy::TraversalPath& path) {
3106 for (auto& [p, layerFE] : mLayerFEs) {
3107 if (p == path) {
3108 return layerFE;
3109 }
3110 }
Lloyd Pique70ddc672024-04-30 18:20:40 -07003111 auto layerFE = mFlinger->getFactory().createLayerFE(mName, this);
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003112 mLayerFEs.emplace_back(path, layerFE);
3113 return layerFE;
3114}
3115
Patrick Williamsbb25f802022-08-30 23:02:34 +00003116void Layer::useSurfaceDamage() {
3117 if (mFlinger->mForceFullDamage) {
3118 surfaceDamageRegion = Region::INVALID_REGION;
3119 } else {
3120 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3121 }
3122}
3123
3124void Layer::useEmptyDamage() {
3125 surfaceDamageRegion.clear();
3126}
3127
3128bool Layer::isOpaque(const Layer::State& s) const {
3129 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3130 // layer's opaque flag.
3131 if (!hasSomethingToDraw()) {
3132 return false;
3133 }
3134
3135 // if the layer has the opaque flag, then we're always opaque
3136 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3137 return true;
3138 }
3139
3140 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003141 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003142 return true;
3143 }
3144
3145 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3146 return fillsColor() && getAlpha() == 1.0_hf;
3147}
3148
3149bool Layer::canReceiveInput() const {
3150 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3151}
3152
3153bool Layer::isVisible() const {
3154 if (!hasSomethingToDraw()) {
3155 return false;
3156 }
3157
3158 if (isHiddenByPolicy()) {
3159 return false;
3160 }
3161
3162 return getAlpha() > 0.0f || hasBlur();
3163}
3164
Leon Scroggins III5b581492023-10-31 14:29:41 -04003165void Layer::onCompositionPresented(const DisplayDevice* display,
3166 const std::shared_ptr<FenceTime>& glDoneFence,
3167 const std::shared_ptr<FenceTime>& presentFence,
Vishnu Nair39a74a92024-07-29 19:01:50 +00003168 const CompositorTiming& compositorTiming,
3169 gui::GameMode gameMode) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003170 // mFrameLatencyNeeded is true when a new frame was latched for the
3171 // composition.
3172 if (!mBufferInfo.mFrameLatencyNeeded) return;
3173
3174 for (const auto& handle : mDrawingState.callbackHandles) {
3175 handle->gpuCompositionDoneFence = glDoneFence;
3176 handle->compositorTiming = compositorTiming;
3177 }
3178
3179 // Update mFrameTracker.
3180 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3181 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3182
3183 const int32_t layerId = getSequence();
3184 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3185
3186 const auto outputLayer = findOutputLayerForDisplay(display);
3187 if (outputLayer && outputLayer->requiresClientComposition()) {
3188 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3189 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3190 clientCompositionTimestamp,
3191 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3192 // Update the SurfaceFrames in the drawing state
3193 if (mDrawingState.bufferSurfaceFrameTX) {
3194 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3195 }
3196 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3197 surfaceFrame->setGpuComposition();
3198 }
3199 }
3200
3201 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3202 if (frameReadyFence->isValid()) {
3203 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3204 } else {
3205 // There was no fence for this frame, so assume that it was ready
3206 // to be presented at the desired present time.
3207 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3208 }
3209
3210 if (display) {
Dominik Laskowskife749dc2024-07-26 10:09:31 -04003211 const auto activeMode = display->refreshRateSelector().getActiveMode();
3212 const Fps refreshRate = activeMode.fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003213 const std::optional<Fps> renderRate =
3214 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3215
Alec Mouri7c1d8b52023-08-29 20:14:46 +00003216 const auto vote = frameRateToSetFrameRateVotePayload(getFrameRateForLayerTree());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003217
3218 if (presentFence->isValid()) {
3219 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3220 refreshRate, renderRate, vote, gameMode);
3221 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3222 presentFence,
3223 FrameTracer::FrameEvent::PRESENT_FENCE);
3224 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3225 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3226 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003227 // The HWC doesn't support present fences, so use the present timestamp instead.
3228 const nsecs_t presentTimestamp =
3229 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3230
3231 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
Dominik Laskowskife749dc2024-07-26 10:09:31 -04003232 const nsecs_t vsyncPeriod =
3233 mFlinger->getHwComposer()
3234 .getDisplayVsyncPeriod(*displayId)
3235 .value_opt()
3236 .value_or(activeMode.modePtr->getVsyncRate().getPeriodNsecs());
3237
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003238 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3239
Patrick Williamsbb25f802022-08-30 23:02:34 +00003240 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3241 refreshRate, renderRate, vote, gameMode);
3242 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3243 mCurrentFrameNumber, actualPresentTime,
3244 FrameTracer::FrameEvent::PRESENT_FENCE);
3245 mFrameTracker.setActualPresentTime(actualPresentTime);
3246 }
3247 }
3248
3249 mFrameTracker.advanceFrame();
3250 mBufferInfo.mFrameLatencyNeeded = false;
3251}
3252
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003253bool Layer::willReleaseBufferOnLatch() const {
3254 return !mDrawingState.buffer && mBufferInfo.mBuffer;
3255}
3256
Patrick Williamsbb25f802022-08-30 23:02:34 +00003257bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003258 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
3259 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
3260}
3261
3262bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003263 SFTRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3264 getDrawingState().frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003265
3266 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3267
3268 if (refreshRequired) {
3269 return refreshRequired;
3270 }
3271
3272 // If the head buffer's acquire fence hasn't signaled yet, return and
3273 // try again later
3274 if (!fenceHasSignaled()) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003275 SFTRACE_NAME("!fenceHasSignaled()");
Patrick Williamsbb25f802022-08-30 23:02:34 +00003276 mFlinger->onLayerUpdate();
3277 return false;
3278 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00003279 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003280
3281 // Capture the old state of the layer for comparisons later
3282 BufferInfo oldBufferInfo = mBufferInfo;
3283 const bool oldOpacity = isOpaque(mDrawingState);
3284 mPreviousFrameNumber = mCurrentFrameNumber;
3285 mCurrentFrameNumber = mDrawingState.frameNumber;
3286 gatherBufferInfo();
3287
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003288 if (mBufferInfo.mBuffer) {
3289 // We latched a buffer that will be presented soon. Clear the previously presented layer
3290 // stack list.
3291 mPreviouslyPresentedLayerStacks.clear();
3292 }
3293
3294 if (mDrawingState.buffer == nullptr) {
3295 const bool bufferReleased = oldBufferInfo.mBuffer != nullptr;
3296 recomputeVisibleRegions = bufferReleased;
3297 return bufferReleased;
3298 }
3299
Patrick Williamsbb25f802022-08-30 23:02:34 +00003300 if (oldBufferInfo.mBuffer == nullptr) {
3301 // the first time we receive a buffer, we need to trigger a
3302 // geometry invalidation.
3303 recomputeVisibleRegions = true;
3304 }
3305
3306 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3307 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3308 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3309 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3310 recomputeVisibleRegions = true;
3311 }
3312
3313 if (oldBufferInfo.mBuffer != nullptr) {
3314 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3315 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3316 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3317 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3318 recomputeVisibleRegions = true;
3319 }
3320 }
3321
3322 if (oldOpacity != isOpaque(mDrawingState)) {
3323 recomputeVisibleRegions = true;
3324 }
3325
3326 return true;
3327}
3328
3329bool Layer::hasReadyFrame() const {
3330 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
3331}
3332
3333bool Layer::isProtected() const {
3334 return (mBufferInfo.mBuffer != nullptr) &&
3335 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
3336}
3337
Patrick Williamsbb25f802022-08-30 23:02:34 +00003338void Layer::latchAndReleaseBuffer() {
3339 if (hasReadyFrame()) {
3340 bool ignored = false;
3341 latchBuffer(ignored, systemTime());
3342 }
3343 releasePendingBuffer(systemTime());
3344}
3345
3346PixelFormat Layer::getPixelFormat() const {
3347 return mBufferInfo.mPixelFormat;
3348}
3349
3350bool Layer::getTransformToDisplayInverse() const {
3351 return mBufferInfo.mTransformToDisplayInverse;
3352}
3353
3354Rect Layer::getBufferCrop() const {
3355 // this is the crop rectangle that applies to the buffer
3356 // itself (as opposed to the window)
3357 if (!mBufferInfo.mCrop.isEmpty()) {
3358 // if the buffer crop is defined, we use that
3359 return mBufferInfo.mCrop;
3360 } else if (mBufferInfo.mBuffer != nullptr) {
3361 // otherwise we use the whole buffer
3362 return mBufferInfo.mBuffer->getBounds();
3363 } else {
3364 // if we don't have a buffer yet, we use an empty/invalid crop
3365 return Rect();
3366 }
3367}
3368
3369uint32_t Layer::getBufferTransform() const {
3370 return mBufferInfo.mTransform;
3371}
3372
3373ui::Dataspace Layer::getDataSpace() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003374 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
3375}
3376
Alec Mouri89f5d4e2023-10-20 17:12:49 +00003377bool Layer::isFrontBuffered() const {
3378 if (mBufferInfo.mBuffer == nullptr) {
3379 return false;
3380 }
3381
3382 return mBufferInfo.mBuffer->getUsage() & AHARDWAREBUFFER_USAGE_FRONT_BUFFER;
3383}
3384
Patrick Williamsbb25f802022-08-30 23:02:34 +00003385ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
3386 ui::Dataspace updatedDataspace = dataspace;
3387 // translate legacy dataspaces to modern dataspaces
3388 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00003389 // Treat unknown dataspaces as V0_sRGB
3390 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00003391 case ui::Dataspace::SRGB:
3392 updatedDataspace = ui::Dataspace::V0_SRGB;
3393 break;
3394 case ui::Dataspace::SRGB_LINEAR:
3395 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
3396 break;
3397 case ui::Dataspace::JFIF:
3398 updatedDataspace = ui::Dataspace::V0_JFIF;
3399 break;
3400 case ui::Dataspace::BT601_625:
3401 updatedDataspace = ui::Dataspace::V0_BT601_625;
3402 break;
3403 case ui::Dataspace::BT601_525:
3404 updatedDataspace = ui::Dataspace::V0_BT601_525;
3405 break;
3406 case ui::Dataspace::BT709:
3407 updatedDataspace = ui::Dataspace::V0_BT709;
3408 break;
3409 default:
3410 break;
3411 }
3412
3413 return updatedDataspace;
3414}
3415
3416sp<GraphicBuffer> Layer::getBuffer() const {
3417 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
3418}
3419
Patrick Williamsbb25f802022-08-30 23:02:34 +00003420const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
3421 return mBufferInfo.mBuffer;
3422}
3423
3424bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003425 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003426 return false;
3427 }
3428
3429 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00003430 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003431 mDrawingState.modified = true;
3432 setTransactionFlags(eTransactionNeeded);
3433 return true;
3434}
3435
3436bool Layer::fillsColor() const {
3437 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
3438 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
3439}
3440
3441bool Layer::hasBlur() const {
3442 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
3443}
3444
Vishnu Nairba354102022-08-01 00:14:18 +00003445void Layer::updateSnapshot(bool updateGeometry) {
3446 if (!getCompositionEngineLayerFE()) {
3447 return;
3448 }
3449
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003450 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00003451 if (updateGeometry) {
3452 prepareBasicGeometryCompositionState();
3453 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003454 snapshot->roundedCorner = getRoundedCornerState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003455 snapshot->transformedBounds = mScreenBounds;
3456 if (mEffectiveShadowRadius > 0.f) {
3457 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
3458
3459 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
3460 // it if transparent regions are present. This may not be necessary since shadows are
3461 // typically cast by layers without transparent regions.
3462 snapshot->shadowSettings.boundaries = mBounds;
3463
3464 const float casterAlpha = snapshot->alpha;
3465 const bool casterIsOpaque =
3466 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
3467
3468 // If the casting layer is translucent, we need to fill in the shadow underneath the
3469 // layer. Otherwise the generated shadow will only be shown around the casting layer.
3470 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
3471 snapshot->shadowSettings.ambientColor *= casterAlpha;
3472 snapshot->shadowSettings.spotColor *= casterAlpha;
3473 }
3474 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00003475 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003476 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003477 snapshot->layerOpaqueFlagSet =
3478 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003479 sp<Layer> p = mDrawingParent.promote();
3480 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003481 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003482 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003483 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003484 }
3485 snapshot->bufferSize = getBufferSize(mDrawingState);
3486 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00003487 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00003488 preparePerFrameCompositionState();
3489}
3490
Vishnu Naire14c6b32022-08-06 04:20:15 +00003491void Layer::updateChildrenSnapshots(bool updateGeometry) {
3492 for (const sp<Layer>& child : mDrawingChildren) {
3493 child->updateSnapshot(updateGeometry);
3494 child->updateChildrenSnapshots(updateGeometry);
3495 }
3496}
3497
Chavi Weingarten328a8312023-01-26 21:17:52 +00003498bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00003499 TrustedPresentationListener const& listener) {
3500 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
3501 mTrustedPresentationListener = listener;
3502 mTrustedPresentationThresholds = thresholds;
3503 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
3504 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
3505 mFlinger->mNumTrustedPresentationListeners++;
3506 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
3507 mFlinger->mNumTrustedPresentationListeners--;
3508 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00003509
3510 // Reset trusted presentation states to ensure we start the time again.
3511 mEnteredTrustedPresentationStateTime = -1;
3512 mLastReportedTrustedPresentationState = false;
3513 mLastComputedTrustedPresentationState = false;
3514
3515 // If there's a new trusted presentation listener, the code needs to go through the composite
3516 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
3517 // we're already in the requested state.
3518 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00003519}
3520
Patrick Williams7c9fa272024-08-30 12:38:43 +00003521void Layer::setBufferReleaseChannel(
3522 const std::shared_ptr<gui::BufferReleaseChannel::ProducerEndpoint>& channel) {
3523 mBufferReleaseChannel = channel;
3524}
3525
Vishnu Naira156f482023-02-22 00:23:38 +00003526void Layer::updateLastLatchTime(nsecs_t latchTime) {
3527 mLastLatchTime = latchTime;
3528}
3529
Arthur Hung69f95222023-10-04 07:39:02 +00003530void Layer::setIsSmallDirty(const Region& damageRegion,
3531 const ui::Transform& layerToDisplayTransform) {
3532 mSmallDirty = false;
Jerry Chang36678002023-11-29 16:56:17 +00003533 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00003534 return;
3535 }
3536
3537 if (mWindowType != WindowInfo::Type::APPLICATION &&
3538 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
3539 return;
3540 }
Arthur Hung69f95222023-10-04 07:39:02 +00003541
3542 Rect bounds = damageRegion.getBounds();
Arthur Hungc70bee22023-06-02 01:35:52 +00003543 if (!bounds.isValid()) {
3544 return;
3545 }
3546
Arthur Hung69f95222023-10-04 07:39:02 +00003547 // Transform to screen space.
3548 bounds = layerToDisplayTransform.transform(bounds);
3549
Arthur Hungc70bee22023-06-02 01:35:52 +00003550 // If the damage region is a small dirty, this could give the hint for the layer history that
3551 // it could suppress the heuristic rate when calculating.
Tony Huangf3621102023-09-04 17:14:22 +08003552 mSmallDirty = mFlinger->mScheduler->isSmallDirtyArea(mOwnerAppId,
Tony Huang9ac5e6e2023-08-24 09:01:44 +00003553 bounds.getWidth() * bounds.getHeight());
Arthur Hungc70bee22023-06-02 01:35:52 +00003554}
3555
Arthur Hung69f95222023-10-04 07:39:02 +00003556void Layer::setIsSmallDirty(frontend::LayerSnapshot* snapshot) {
3557 setIsSmallDirty(snapshot->surfaceDamage, snapshot->localTransform);
3558 snapshot->isSmallDirty = mSmallDirty;
3559}
3560
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07003561} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003562
3563#if defined(__gl_h_)
3564#error "don't include gl/gl.h in this file"
3565#endif
3566
3567#if defined(__gl2_h_)
3568#error "don't include gl2/gl2.h in this file"
3569#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08003570
3571// TODO(b/129481165): remove the #pragma below and fix conversion issues
3572#pragma clang diagnostic pop // ignored "-Wconversion"