blob: 736fec6fb2c11f6662fe0fb60c3d29cfd086b5d2 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Dan Stoza9e56aa02015-11-02 13:00:03 -080021//#define LOG_NDEBUG 0
22#undef LOG_TAG
23#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080024#define ATRACE_TAG ATRACE_TAG_GRAPHICS
25
Alec Mourie60041e2019-06-14 18:59:51 -070026#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080027
[1;3C2b9fc252021-02-04 16:16:50 -080028#include <android-base/properties.h>
Yiwei Zhang5434a782018-12-05 18:06:32 -080029#include <android-base/stringprintf.h>
Vishnu Nair0f085c62019-08-30 08:49:12 -070030#include <binder/IPCThreadState.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000031#include <compositionengine/CompositionEngine.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080032#include <compositionengine/Display.h>
Lloyd Piquea83776c2019-01-29 18:42:32 -080033#include <compositionengine/LayerFECompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080034#include <compositionengine/OutputLayer.h>
35#include <compositionengine/impl/OutputLayerCompositionState.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070036#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070037#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070038#include <cutils/properties.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070039#include <ftl/enum.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080040#include <ftl/fake_guard.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080041#include <gui/BufferItem.h>
42#include <gui/LayerDebugInfo.h>
43#include <gui/Surface.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000044#include <gui/TraceUtils.h>
Alec Mourie60041e2019-06-14 18:59:51 -070045#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070046#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080047#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070048#include <stdint.h>
49#include <stdlib.h>
50#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000051#include <system/graphics-base-v1.0.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080052#include <ui/DebugUtils.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000053#include <ui/FloatRect.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080054#include <ui/GraphicBuffer.h>
Sally Qif6918d42023-08-07 15:28:30 -070055#include <ui/HdrRenderTypeUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080056#include <ui/PixelFormat.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000057#include <ui/Rect.h>
58#include <ui/Transform.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059#include <utils/Errors.h>
60#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080061#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080063#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Alec Mourie60041e2019-06-14 18:59:51 -070065#include <algorithm>
66#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070067#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070068#include <sstream>
69
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070070#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080071#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070072#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070073#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +000074#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000075#include "FrontEnd/LayerHandle.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080076#include "LayerProtoHelper.h"
Josh Gao194ff392022-09-08 16:19:29 -070077#include "MutexUtils.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080079#include "TimeStats/TimeStats.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070080#include "TunnelModeEnabledReporter.h"
Alec Mouri9892aac2023-12-11 21:16:59 +000081#include "Utils/FenceUtils.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070082
David Sodman41fdfc92017-11-06 16:09:56 -080083#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000084#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086namespace android {
Alec Mouri9892aac2023-12-11 21:16:59 +000087using namespace std::chrono_literals;
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010088namespace {
89constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000090
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000091const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000092
Patrick Williamsbb25f802022-08-30 23:02:34 +000093bool assignTransform(ui::Transform* dst, ui::Transform& from) {
94 if (*dst == from) {
95 return false;
96 }
97 *dst = from;
98 return true;
99}
100
101TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
102 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
103 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
104 const auto frameRateCompatibility = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700105 switch (frameRate.vote.type) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000106 case Layer::FrameRateCompatibility::Default:
107 return FrameRateCompatibility::Default;
108 case Layer::FrameRateCompatibility::ExactOrMultiple:
109 return FrameRateCompatibility::ExactOrMultiple;
110 default:
111 return FrameRateCompatibility::Undefined;
112 }
113 }();
114
115 const auto seamlessness = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700116 switch (frameRate.vote.seamlessness) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000117 case scheduler::Seamlessness::OnlySeamless:
118 return Seamlessness::ShouldBeSeamless;
119 case scheduler::Seamlessness::SeamedAndSeamless:
120 return Seamlessness::NotRequired;
121 default:
122 return Seamlessness::Undefined;
123 }
124 }();
125
Rachel Leece6e0042023-06-27 11:22:54 -0700126 return TimeStats::SetFrameRateVote{.frameRate = frameRate.vote.rate.getValue(),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000127 .frameRateCompatibility = frameRateCompatibility,
128 .seamlessness = seamlessness};
129}
130
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100131} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800132
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700133using namespace ftl::flag_operators;
134
Yiwei Zhang5434a782018-12-05 18:06:32 -0800135using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000136using frontend::LayerSnapshot;
137using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800138using gui::GameMode;
139using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500140using gui::WindowInfo;
Vishnu Nair494a2e42023-11-10 17:21:19 -0800141using ui::Size;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800142
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700143using PresentState = frametimeline::SurfaceFrame::PresentState;
144
Kean Mariotti4ba343c2023-04-19 13:31:02 +0000145Layer::Layer(const surfaceflinger::LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000146 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700147 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000148 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700149 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800150 mWindowType(static_cast<WindowInfo::Type>(
151 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000152 mLayerCreationFlags(args.flags),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000153 mBorderEnabled(false),
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000154 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000155 ALOGV("Creating Layer %s", getDebugName());
156
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700157 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700158 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
159 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
160 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700161 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
162 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700163 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700164 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700165 mDrawingState.z = 0;
166 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700167 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700168 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700169 mDrawingState.transform.set(0, 0);
170 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +0000171 mDrawingState.previousFrameNumber = 0;
Vishnu Nair63221212023-04-06 15:17:37 -0700172 mDrawingState.barrierFrameNumber = 0;
173 mDrawingState.producerId = 0;
174 mDrawingState.barrierProducerId = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700175 mDrawingState.bufferTransform = 0;
176 mDrawingState.transformToDisplayInverse = false;
Robert Carr6a160312021-05-17 12:08:20 -0700177 mDrawingState.acquireFence = sp<Fence>::make(-1);
178 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
Alec Mouri74c7ae12023-03-26 02:57:47 +0000179 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Robert Carr6a160312021-05-17 12:08:20 -0700180 mDrawingState.hdrMetadata.validTypes = 0;
181 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
182 mDrawingState.cornerRadius = 0.0f;
183 mDrawingState.backgroundBlurRadius = 0;
184 mDrawingState.api = -1;
185 mDrawingState.hasColorTransform = false;
186 mDrawingState.colorSpaceAgnostic = false;
187 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
188 mDrawingState.metadata = args.metadata;
189 mDrawingState.shadowRadius = 0.f;
190 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
191 mDrawingState.frameTimelineInfo = {};
192 mDrawingState.postTime = -1;
193 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000194 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700195 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700196 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000197 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Rachel Lee70f7b692023-11-22 11:24:02 -0800198 mDrawingState.frameRateSelectionStrategy = FrameRateSelectionStrategy::Propagate;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700199
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700200 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
201 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700202 mDrawingState.color.r = -1.0_hf;
203 mDrawingState.color.g = -1.0_hf;
204 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700205 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700206
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500207 mFrameTracker.setDisplayRefreshPeriod(
208 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700209
Vishnu Naircb8be502022-10-12 19:03:23 +0000210 mOwnerUid = args.ownerUid;
211 mOwnerPid = args.ownerPid;
Tony Huangf3621102023-09-04 17:14:22 +0800212 mOwnerAppId = mOwnerUid % PER_USER_RANGE;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000213
214 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
215 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
216 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000217
218 mSnapshot->sequence = sequence;
219 mSnapshot->name = getDebugName();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000220 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000221 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800222}
223
224void Layer::onFirstRef() {
225 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700226}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700227
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700228Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000229 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
230 "Layer destructor called off the main thread.");
231
Patrick Williamsbb25f802022-08-30 23:02:34 +0000232 // The original layer and the clone layer share the same texture and buffer. Therefore, only
233 // one of the layers, in this case the original layer, needs to handle the deletion. The
234 // original layer and the clone should be removed at the same time so there shouldn't be any
235 // issue with the clone layer trying to use the texture.
236 if (mBufferInfo.mBuffer != nullptr) {
237 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
238 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800239 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000240 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000241 const int32_t layerId = getSequence();
242 mFlinger->mTimeStats->onDestroy(layerId);
243 mFlinger->mFrameTracer->onDestroy(layerId);
244
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000245 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700246 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700247
248 if (mDrawingState.sidebandStream != nullptr) {
249 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
250 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700251 if (mHadClonedChild) {
Vishnu Nair3be61902023-04-26 19:47:29 -0700252 auto& roots = mFlinger->mLayerMirrorRoots;
253 roots.erase(std::remove(roots.begin(), roots.end(), this), roots.end());
Robert Carr6a0382d2021-07-01 15:57:17 -0700254 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000255 if (hasTrustedPresentationListener()) {
256 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000257 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000258 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700259}
260
Mathias Agopian13127d82013-03-05 17:47:11 -0800261// ---------------------------------------------------------------------------
262// callbacks
263// ---------------------------------------------------------------------------
264
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700265void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700266 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700267 return;
268 }
Robert Carr2e102c92018-10-23 12:11:15 -0700269
Robert Carr6a160312021-05-17 12:08:20 -0700270 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700271 if (strongRelative == nullptr) {
272 setZOrderRelativeOf(nullptr);
273 return;
274 }
275
276 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700277 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700278 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800279 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700280 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700281}
282
283void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700284 if (!mRemovedFromDrawingState) {
285 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700286 mFlinger->mScheduler->deregisterLayer(this);
287 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000288 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000289
Ady Abrahamd11bade2022-08-01 16:18:03 -0700290 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700291}
Chia-I Wu38512252017-05-17 14:36:16 -0700292
chaviw68d4dab2020-06-08 15:07:32 -0700293sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000294 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700295 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700296 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700297 }
298 return parent->getRootLayer();
299}
300
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700301void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700302 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
303 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700304 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700305
Josh Gao194ff392022-09-08 16:19:29 -0700306 REQUIRE_MUTEX(mFlinger->mStateLock);
307 traverse(LayerVector::StateSet::Current,
308 [&](Layer* layer) REQUIRES(layer->mFlinger->mStateLock) {
309 layer->removeFromCurrentState();
310 layer->removeRelativeZ(layersInTree);
311 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700312}
313
chaviw61626f22018-11-15 16:26:27 -0800314void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700315 if (mRemovedFromDrawingState) {
316 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700317 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700318 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700319 }
chaviw61626f22018-11-15 16:26:27 -0800320
321 for (const auto& child : mCurrentChildren) {
322 child->addToCurrentState();
323 }
324}
325
Mathias Agopian13127d82013-03-05 17:47:11 -0800326// ---------------------------------------------------------------------------
327// set-up
328// ---------------------------------------------------------------------------
329
chaviw13fdc492017-06-27 12:40:18 -0700330bool Layer::getPremultipledAlpha() const {
331 return mPremultipliedAlpha;
332}
333
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700334sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800335 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700336 if (mGetHandleCalled) {
337 ALOGE("Get handle called twice" );
338 return nullptr;
339 }
340 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700341 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000342 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800343}
344
345// ---------------------------------------------------------------------------
346// h/w composer set-up
347// ---------------------------------------------------------------------------
348
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700349static Rect reduce(const Rect& win, const Region& exclude) {
350 if (CC_LIKELY(exclude.isEmpty())) {
351 return win;
352 }
353 if (exclude.isRect()) {
354 return win.reduce(exclude.getBounds());
355 }
356 return Region(win).subtract(exclude).getBounds();
357}
358
Dan Stoza80d61162017-12-20 15:57:52 -0800359static FloatRect reduce(const FloatRect& win, const Region& exclude) {
360 if (CC_LIKELY(exclude.isEmpty())) {
361 return win;
362 }
363 // Convert through Rect (by rounding) for lack of FloatRegion
364 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
365}
366
Vishnu Nair4351ad52019-02-11 14:13:02 -0800367Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800368 if (!reduceTransparentRegion) {
369 return Rect{mScreenBounds};
370 }
371
372 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800373 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800374 // Transform to screen space.
375 bounds = t.transform(bounds);
376 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700377}
378
Vishnu Nair4351ad52019-02-11 14:13:02 -0800379FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000380 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800381 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700382}
383
Vishnu Nairf0c28512019-02-08 12:40:28 -0800384FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
385 // Subtract the transparent region and snap to the bounds.
386 return reduce(mBounds, activeTransparentRegion);
387}
388
Chavi Weingarten076acac2023-01-19 17:20:43 +0000389// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000390void Layer::updateTrustedPresentationState(const DisplayDevice* display,
391 const frontend::LayerSnapshot* snapshot,
392 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000393 if (!hasTrustedPresentationListener()) {
394 return;
395 }
396 const bool lastState = mLastComputedTrustedPresentationState;
397 mLastComputedTrustedPresentationState = false;
398
399 if (!leaveState) {
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000400 const auto outputLayer = findOutputLayerForDisplay(display, snapshot->path);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000401 if (outputLayer != nullptr) {
402 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
403 Region coveredRegion =
404 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
405 mLastComputedTrustedPresentationState =
406 computeTrustedPresentationState(snapshot->geomLayerBounds,
407 snapshot->sourceBounds(), coveredRegion,
408 snapshot->transformedBounds,
409 snapshot->alpha,
410 snapshot->geomLayerTransform,
411 mTrustedPresentationThresholds);
412 } else {
413 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
414 "TrustedPresentationState",
415 getDebugName());
416 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000417 }
418 }
419 const bool newState = mLastComputedTrustedPresentationState;
420 if (lastState && !newState) {
421 // We were in the trusted presentation state, but now we left it,
422 // emit the callback if needed
423 if (mLastReportedTrustedPresentationState) {
424 mLastReportedTrustedPresentationState = false;
425 mTrustedPresentationListener.invoke(false);
426 }
427 // Reset the timer
428 mEnteredTrustedPresentationStateTime = -1;
429 } else if (!lastState && newState) {
430 // We were not in the trusted presentation state, but we entered it, begin the timer
431 // and make sure this gets called at least once more!
432 mEnteredTrustedPresentationStateTime = time_in_ms;
433 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
434 }
435
436 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
437 if (!mLastReportedTrustedPresentationState && newState &&
438 (time_in_ms - mEnteredTrustedPresentationStateTime >
439 mTrustedPresentationThresholds.stabilityRequirementMs)) {
440 mLastReportedTrustedPresentationState = true;
441 mTrustedPresentationListener.invoke(true);
442 }
443}
444
445/**
446 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
447 * of how the parameters and thresholds are interpreted. The general spirit is
448 * to produce an upper bound on the amount of the buffer which was presented.
449 */
450bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
451 const Region& coveredRegion,
452 const FloatRect& screenBounds, float alpha,
453 const ui::Transform& effectiveTransform,
454 const TrustedPresentationThresholds& thresholds) {
455 if (alpha < thresholds.minAlpha) {
456 return false;
457 }
458 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
459 return false;
460 }
461 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
462 return false;
463 }
464
465 const float sx = effectiveTransform.dsdx();
466 const float sy = effectiveTransform.dsdy();
467 float fractionRendered = std::min(sx * sy, 1.0f);
468
469 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
470 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
471 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
472
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000473 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
474 // Compute the size of all the rects since they may be disconnected.
475 float coveredSize = 0;
476 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
477 float size = rect->width() * rect->height();
478 coveredSize += size;
479 }
480
481 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000482
483 if (fractionRendered < thresholds.minFractionRendered) {
484 return false;
485 }
486
487 return true;
488}
489
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700490void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
491 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800492 const State& s(getDrawingState());
493
494 // Calculate effective layer transform
495 mEffectiveTransform = parentTransform * getActiveTransform(s);
496
Garfield Tan2c1782c2022-02-16 15:25:05 -0800497 if (CC_UNLIKELY(!isTransformValid())) {
498 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
499 getDebugName());
500 return;
501 }
502
Vishnu Nair4351ad52019-02-11 14:13:02 -0800503 // Transform parent bounds to layer space
504 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
505
Vishnu Nairc652ff82019-03-15 12:48:54 -0700506 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800507 mSourceBounds = computeSourceBounds(parentBounds);
508
509 // Calculate bounds by croping diplay frame with layer crop and parent bounds
510 FloatRect bounds = mSourceBounds;
511 const Rect layerCrop = getCrop(s);
512 if (!layerCrop.isEmpty()) {
513 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
514 }
515 bounds = bounds.intersect(parentBounds);
516
517 mBounds = bounds;
518 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700519
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700520 // Use the layer's own shadow radius if set. Otherwise get the radius from
521 // parent.
522 if (s.shadowRadius > 0.f) {
523 mEffectiveShadowRadius = s.shadowRadius;
524 } else {
525 mEffectiveShadowRadius = parentShadowRadius;
526 }
527
528 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
529 // don't pass it to its children.
530 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
531
Vishnu Nair4351ad52019-02-11 14:13:02 -0800532 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700533 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800534 }
Vishnu Nairba354102022-08-01 00:14:18 +0000535
536 if (mPotentialCursor) {
537 prepareCursorCompositionState();
538 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800539}
540
Vishnu Nair60356342018-11-13 13:00:45 -0800541Rect Layer::getCroppedBufferSize(const State& s) const {
542 Rect size = getBufferSize(s);
543 Rect crop = getCrop(s);
544 if (!crop.isEmpty() && size.isValid()) {
545 size.intersect(crop, &size);
546 } else if (!crop.isEmpty()) {
547 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700548 }
Vishnu Nair60356342018-11-13 13:00:45 -0800549 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800550}
551
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700552void Layer::setupRoundedCornersCropCoordinates(Rect win,
553 const FloatRect& roundedCornersCrop) const {
554 // Translate win by the rounded corners rect coordinates, to have all values in
555 // layer coordinate space.
556 win.left -= roundedCornersCrop.left;
557 win.right -= roundedCornersCrop.left;
558 win.top -= roundedCornersCrop.top;
559 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700560}
561
Lloyd Piquede196652020-01-22 17:29:58 -0800562void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800563 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800564 const auto alpha = static_cast<float>(getAlpha());
565 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700566 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800567
568 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
569 if (!opaque || alpha != 1.0f) {
570 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
571 : Hwc2::IComposerClient::BlendMode::COVERAGE;
572 }
573
Alec Mourif4af03e2023-02-11 00:25:24 +0000574 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000575 auto* snapshot = editLayerSnapshot();
576 snapshot->outputFilter = getOutputFilter();
577 snapshot->isVisible = isVisible();
578 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
Vishnu Naird9e4f462023-10-06 04:05:45 +0000579 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800580
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000581 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800582 contentDirty = false;
583
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000584 snapshot->geomLayerBounds = mBounds;
585 snapshot->geomLayerTransform = getTransform();
586 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
587 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000588 snapshot->localTransform = getActiveTransform(drawingState);
589 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000590 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
591 snapshot->alpha = alpha;
Vishnu Nairc6384702023-07-31 12:22:20 -0700592 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
593 snapshot->blurRegions = getBlurRegions();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000594 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800595}
596
Lloyd Piquede196652020-01-22 17:29:58 -0800597void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800598 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000599 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700600
Alec Mourif4af03e2023-02-11 00:25:24 +0000601 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000602 snapshot->geomBufferSize = getBufferSize(drawingState);
603 snapshot->geomContentCrop = getBufferCrop();
604 snapshot->geomCrop = getCrop(drawingState);
605 snapshot->geomBufferTransform = getBufferTransform();
606 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
607 snapshot->geomUsesSourceCrop = usesSourceCrop();
608 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800609
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000610 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800611 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
612 for (const auto& [key, mandatory] : supportedMetadata) {
613 const auto& genericLayerMetadataCompatibilityMap =
614 mFlinger->getGenericLayerMetadataKeyMap();
615 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
616 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
617 continue;
618 }
619 const uint32_t id = compatIter->second;
620
621 auto it = drawingState.metadata.mMap.find(id);
622 if (it == std::end(drawingState.metadata.mMap)) {
623 continue;
624 }
625
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000626 snapshot->metadata.emplace(key,
627 compositionengine::GenericLayerMetadataEntry{mandatory,
628 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800629 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800630}
David Sodmanba340492018-08-05 21:51:33 -0700631
Lloyd Piquede196652020-01-22 17:29:58 -0800632void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800633 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000634 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000635 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800636
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000637 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800638
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000639 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
640 snapshot->dataspace = getDataSpace();
641 snapshot->colorTransform = getColorTransform();
642 snapshot->colorTransformIsIdentity = !hasColorTransform();
643 snapshot->surfaceDamage = surfaceDamageRegion;
644 snapshot->hasProtectedContent = isProtected();
645 snapshot->dimmingEnabled = isDimmingEnabled();
Sally Qi963049b2023-03-23 14:06:21 -0700646 snapshot->currentHdrSdrRatio = getCurrentHdrSdrRatio();
647 snapshot->desiredHdrSdrRatio = getDesiredHdrSdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000648 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800649
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700650 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700651
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000652 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800653
654 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400655 // Rounded corners no longer force client composition, since we may use a
656 // hole punch so that the layer will appear to have rounded corners.
Alec Mouri994761f2023-08-04 21:50:55 +0000657 if (drawShadows() || snapshot->stretchEffect.hasEffect()) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000658 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800659 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700660 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairc6384702023-07-31 12:22:20 -0700661 snapshot->blurRegions = getBlurRegions();
662 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400663
664 // Layer framerate is used in caching decisions.
665 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
666 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000667 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000668
669 if (hasBufferOrSidebandStream()) {
670 preparePerFrameBufferCompositionState();
671 } else {
672 preparePerFrameEffectsCompositionState();
673 }
674}
675
676void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000677 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000678 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000679 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000680 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
681 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000682 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
683 return;
684 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000685 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000686 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800687 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
688 snapshot->compositionType =
689 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000690 } else {
691 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000692 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
693 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000694 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
695 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
696 }
697
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000698 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000699 snapshot->acquireFence = mBufferInfo.mFence;
700 snapshot->frameNumber = mBufferInfo.mFrameNumber;
701 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000702}
703
704void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000705 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000706 auto* snapshot = editLayerSnapshot();
707 snapshot->color = getColor();
708 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000709 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800710}
711
Lloyd Piquede196652020-01-22 17:29:58 -0800712void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800713 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000714 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000715 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800716
717 // Apply the layer's transform, followed by the display's global transform
718 // Here we're guaranteed that the layer's transform preserves rects
719 Rect win = getCroppedBufferSize(drawingState);
720 // Subtract the transparent region and snap to the bounds
721 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
722 Rect frame(getTransform().transform(bounds));
723
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000724 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800725}
726
Lloyd Piquea83776c2019-01-29 18:42:32 -0800727const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700728 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800729}
730
Mathias Agopian13127d82013-03-05 17:47:11 -0800731// ---------------------------------------------------------------------------
732// drawing...
733// ---------------------------------------------------------------------------
734
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500735aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
736 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700737 const auto outputLayer = findOutputLayerForDisplay(&display);
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000738 return getCompositionType(outputLayer);
739}
740
741aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
742 const compositionengine::OutputLayer* outputLayer) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -0800743 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500744 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800745 }
746 if (outputLayer->getState().hwc) {
747 return (*outputLayer->getState().hwc).hwcCompositionType;
748 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500749 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800750 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800751}
752
Mathias Agopian13127d82013-03-05 17:47:11 -0800753// ----------------------------------------------------------------------------
754// local state
755// ----------------------------------------------------------------------------
756
David Sodman41fdfc92017-11-06 16:09:56 -0800757bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800758 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700759 if (s.flags & layer_state_t::eLayerSecure) {
760 return true;
761 }
762
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000763 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700764 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700765}
766
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100767void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
768 std::vector<JankData>& jankData) {
769 if (mPendingJankClassifications.empty() ||
770 !mPendingJankClassifications.front()->getJankType()) {
771 return;
772 }
773
774 bool includeJankData = false;
775 for (const auto& handle : handles) {
776 for (const auto& cb : handle->callbackIds) {
777 if (cb.includeJankData) {
778 includeJankData = true;
779 break;
780 }
781 }
782
783 if (includeJankData) {
784 jankData.reserve(mPendingJankClassifications.size());
785 break;
786 }
787 }
788
789 while (!mPendingJankClassifications.empty() &&
790 mPendingJankClassifications.front()->getJankType()) {
791 if (includeJankData) {
792 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
793 mPendingJankClassifications.front();
Pascal Muetschardac7bcd92023-10-03 15:05:36 +0200794 jankData.emplace_back(JankData(surfaceFrame->getToken(),
795 surfaceFrame->getJankType().value(),
796 surfaceFrame->getRenderRate().getPeriodNsecs()));
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100797 }
798 mPendingJankClassifications.pop_front();
799 }
800}
801
Mathias Agopian13127d82013-03-05 17:47:11 -0800802// ----------------------------------------------------------------------------
803// transaction
804// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800805
Vishnu Naira156f482023-02-22 00:23:38 +0000806uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700807 ATRACE_CALL();
808
Robert Carr0758e5d2021-03-11 22:15:04 -0800809 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700810 mDrawingStateModified = mDrawingState.modified;
811 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700812
Alec Mourib416efd2018-09-06 21:01:59 +0000813 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700814
Robert Carr6a160312021-05-17 12:08:20 -0700815 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800816 // invalidate and recompute the visible regions if needed
817 flags |= Layer::eVisibleRegion;
818 }
819
Robert Carr6a160312021-05-17 12:08:20 -0700820 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800821 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000822 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800823 flags |= eVisibleRegion;
824 this->contentDirty = true;
825
826 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700827 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800828 }
829
Arthur Hung9ed43392022-05-27 06:31:57 +0000830 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
831 mFlinger->mUpdateInputInfo = true;
832 }
833
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700834 commitTransaction();
Robert Carra1257842020-01-31 13:48:28 -0800835
Mathias Agopian13127d82013-03-05 17:47:11 -0800836 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800837}
838
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700839void Layer::commitTransaction() {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000840 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
841 // bufferSurfaceFrameTX will be presented in latchBuffer.
842 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
843 if (surfaceFrame->getPresentState() != PresentState::Presented) {
844 // With applyPendingStates, we could end up having presented surfaceframes from previous
845 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800846 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000847 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
848 }
849 }
Robert Carr6a160312021-05-17 12:08:20 -0700850 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700851}
852
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700853uint32_t Layer::clearTransactionFlags(uint32_t mask) {
854 const auto flags = mTransactionFlags & mask;
855 mTransactionFlags &= ~mask;
856 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800857}
858
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700859void Layer::setTransactionFlags(uint32_t mask) {
860 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800861}
862
Robert Carr1f0a16a2016-10-24 16:27:39 -0700863bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
864 ssize_t idx = mCurrentChildren.indexOf(childLayer);
865 if (idx < 0) {
866 return false;
867 }
868 if (childLayer->setLayer(z)) {
869 mCurrentChildren.removeAt(idx);
870 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800871 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700872 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800873 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700874}
875
Robert Carr503c7042017-09-27 15:06:08 -0700876bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
877 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
878 ssize_t idx = mCurrentChildren.indexOf(childLayer);
879 if (idx < 0) {
880 return false;
881 }
882 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
883 mCurrentChildren.removeAt(idx);
884 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800885 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700886 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800887 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700888}
889
Robert Carrae060832016-11-28 10:51:00 -0800890bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700891 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
892 mDrawingState.sequence++;
893 mDrawingState.z = z;
894 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700895
Robert Carra70e91c2021-06-11 13:59:52 -0700896 mFlinger->mSomeChildrenChanged = true;
897
Robert Carrdb66e622017-04-10 16:55:57 -0700898 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700899 if (mDrawingState.zOrderRelativeOf != nullptr) {
900 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700901 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700902 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700903 }
chaviw606e5cf2019-03-01 10:12:10 -0800904 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700905 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800906 setTransactionFlags(eTransactionNeeded);
907 return true;
908}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700909
Robert Carrdb66e622017-04-10 16:55:57 -0700910void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700911 mDrawingState.zOrderRelatives.remove(relative);
912 mDrawingState.sequence++;
913 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700914 setTransactionFlags(eTransactionNeeded);
915}
916
917void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700918 mDrawingState.zOrderRelatives.add(relative);
919 mDrawingState.modified = true;
920 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700921 setTransactionFlags(eTransactionNeeded);
922}
923
chaviw606e5cf2019-03-01 10:12:10 -0800924void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700925 mDrawingState.zOrderRelativeOf = relativeOf;
926 mDrawingState.sequence++;
927 mDrawingState.modified = true;
928 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700929
chaviw606e5cf2019-03-01 10:12:10 -0800930 setTransactionFlags(eTransactionNeeded);
931}
932
Robert Carr503d2bd2017-12-04 15:49:47 -0800933bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000934 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700935 if (relative == nullptr) {
936 return false;
937 }
938
Robert Carr6a160312021-05-17 12:08:20 -0700939 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
940 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800941 return false;
942 }
943
Robert Carr88b85e12022-03-21 15:47:35 -0700944 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
945 (relative->mDrawingState.zOrderRelativeOf == this)) {
946 ALOGE("Detected relative layer loop between %s and %s",
947 mName.c_str(), relative->mName.c_str());
948 ALOGE("Ignoring new call to set relative layer");
949 return false;
950 }
951
Robert Carra70e91c2021-06-11 13:59:52 -0700952 mFlinger->mSomeChildrenChanged = true;
953
Robert Carr6a160312021-05-17 12:08:20 -0700954 mDrawingState.sequence++;
955 mDrawingState.modified = true;
956 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700957
Robert Carr6a160312021-05-17 12:08:20 -0700958 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700959 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700960 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700961 }
chaviw606e5cf2019-03-01 10:12:10 -0800962 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700963 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700964
965 setTransactionFlags(eTransactionNeeded);
966
967 return true;
968}
969
Winson Chunga30f7c92021-06-29 15:42:56 -0700970bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
971 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
972 mDrawingState.isTrustedOverlay = isTrustedOverlay;
973 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000974 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700975 setTransactionFlags(eTransactionNeeded);
976 return true;
977}
978
979bool Layer::isTrustedOverlay() const {
980 if (getDrawingState().isTrustedOverlay) {
981 return true;
982 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000983 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700984 return (p != nullptr) && p->isTrustedOverlay();
985}
986
Dan Stoza9e56aa02015-11-02 13:00:03 -0800987bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700988 if (mDrawingState.color.a == alpha) return false;
989 mDrawingState.sequence++;
990 mDrawingState.color.a = alpha;
991 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800992 setTransactionFlags(eTransactionNeeded);
993 return true;
994}
chaviw13fdc492017-06-27 12:40:18 -0700995
Valerie Haudd0b7572019-01-29 14:59:27 -0800996bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700997 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700998 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800999 }
Robert Carr6a160312021-05-17 12:08:20 -07001000 mDrawingState.sequence++;
1001 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -08001002 setTransactionFlags(eTransactionNeeded);
1003
Robert Carr6a160312021-05-17 12:08:20 -07001004 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001005 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001006 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001007 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001008 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Kean Mariotti4ba343c2023-04-19 13:31:02 +00001009 surfaceflinger::LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
1010 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001011
Valerie Haudd0b7572019-01-29 14:59:27 -08001012 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001013 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001014 mFlinger->mLayersAdded = true;
1015 // set up SF to handle added color layer
1016 if (isRemovedFromCurrentState()) {
Josh Gao194ff392022-09-08 16:19:29 -07001017 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001018 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001019 }
1020 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001021 } else if (mDrawingState.bgColorLayer && alpha == 0) {
Josh Gao194ff392022-09-08 16:19:29 -07001022 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001023 mDrawingState.bgColorLayer->reparent(nullptr);
1024 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001025 return true;
1026 }
1027
Robert Carr6a160312021-05-17 12:08:20 -07001028 mDrawingState.bgColorLayer->setColor(color);
1029 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1030 mDrawingState.bgColorLayer->setAlpha(alpha);
1031 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001032
chaviw13fdc492017-06-27 12:40:18 -07001033 return true;
1034}
1035
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001036bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001037 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001038
Robert Carr6a160312021-05-17 12:08:20 -07001039 mDrawingState.sequence++;
1040 mDrawingState.cornerRadius = cornerRadius;
1041 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001042 setTransactionFlags(eTransactionNeeded);
1043 return true;
1044}
1045
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001046bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001047 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001048 // If we start or stop drawing blur then the layer's visibility state may change so increment
1049 // the magic sequence number.
1050 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1051 mDrawingState.sequence++;
1052 }
Robert Carr6a160312021-05-17 12:08:20 -07001053 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1054 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001055 setTransactionFlags(eTransactionNeeded);
1056 return true;
1057}
Marissa Wall61c58622018-07-18 10:12:20 -07001058
Mathias Agopian13127d82013-03-05 17:47:11 -08001059bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001060 mDrawingState.sequence++;
1061 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001062 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001063 setTransactionFlags(eTransactionNeeded);
1064 return true;
1065}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001066
Lucas Dupinc3800b82020-10-02 16:24:48 -07001067bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001068 // If we start or stop drawing blur then the layer's visibility state may change so increment
1069 // the magic sequence number.
1070 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1071 mDrawingState.sequence++;
1072 }
Robert Carr6a160312021-05-17 12:08:20 -07001073 mDrawingState.blurRegions = blurRegions;
1074 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001075 setTransactionFlags(eTransactionNeeded);
1076 return true;
1077}
1078
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001079bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001080 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1081 if (mDrawingState.flags == newFlags) return false;
1082 mDrawingState.sequence++;
1083 mDrawingState.flags = newFlags;
1084 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001085 setTransactionFlags(eTransactionNeeded);
1086 return true;
1087}
Robert Carr99e27f02016-06-16 15:18:02 -07001088
chaviw25714502021-02-11 10:01:08 -08001089bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001090 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001091 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001092 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001093
Robert Carr6a160312021-05-17 12:08:20 -07001094 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001095 setTransactionFlags(eTransactionNeeded);
1096 return true;
1097}
Robert Carr8d5227b2017-03-16 15:41:03 -07001098
Evan Roskyef876c92019-01-25 17:46:06 -08001099bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001100 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1101 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001102 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001103 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001104}
1105
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001106bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001107 if (mDrawingState.layerStack == layerStack) return false;
1108 mDrawingState.sequence++;
1109 mDrawingState.layerStack = layerStack;
1110 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001111 setTransactionFlags(eTransactionNeeded);
1112 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001113}
1114
Peiyong Linc502cb72019-03-01 15:00:23 -08001115bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001116 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001117 return false;
1118 }
Robert Carr6a160312021-05-17 12:08:20 -07001119 mDrawingState.sequence++;
1120 mDrawingState.colorSpaceAgnostic = agnostic;
1121 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001122 setTransactionFlags(eTransactionNeeded);
1123 return true;
1124}
1125
Sally Qi81d95e62022-03-21 19:41:33 -07001126bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1127 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1128
1129 mDrawingState.sequence++;
1130 mDrawingState.dimmingEnabled = dimmingEnabled;
1131 mDrawingState.modified = true;
1132 setTransactionFlags(eTransactionNeeded);
1133 return true;
1134}
1135
Ana Krulecc84d09b2019-11-02 23:10:29 +01001136bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001137 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1138 mDrawingState.frameRateSelectionPriority = priority;
1139 mDrawingState.sequence++;
1140 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001141 setTransactionFlags(eTransactionNeeded);
1142 return true;
1143}
1144
1145int32_t Layer::getFrameRateSelectionPriority() const {
1146 // Check if layer has priority set.
1147 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1148 return mDrawingState.frameRateSelectionPriority;
1149 }
1150 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001151 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001152 if (parent != nullptr) {
1153 return parent->getFrameRateSelectionPriority();
1154 }
1155
1156 return Layer::PRIORITY_UNSET;
1157}
1158
Andy Labrada096227e2022-06-15 16:58:11 +00001159bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1160 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1161 mDrawingState.defaultFrameRateCompatibility = compatibility;
1162 mDrawingState.modified = true;
Vishnu Nair80e8cfe2023-09-29 17:03:45 -07001163 mFlinger->mScheduler->setDefaultFrameRateCompatibility(sequence, compatibility);
Andy Labrada096227e2022-06-15 16:58:11 +00001164 setTransactionFlags(eTransactionNeeded);
1165 return true;
1166}
1167
Vishnu Nair3fbe3262023-09-29 17:07:00 -07001168scheduler::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
Andy Labrada096227e2022-06-15 16:58:11 +00001169 return mDrawingState.defaultFrameRateCompatibility;
1170}
1171
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001172bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1173 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1174};
1175
Vishnu Nair73908d12022-10-24 21:46:42 -07001176ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1177 bool useDrawing = state == LayerVector::StateSet::Drawing;
1178 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1179 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001180 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001181 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001182 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001183}
1184
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001185bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001186 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001187 return false;
1188 }
1189
Robert Carr6a160312021-05-17 12:08:20 -07001190 mDrawingState.sequence++;
1191 mDrawingState.shadowRadius = shadowRadius;
1192 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001193 setTransactionFlags(eTransactionNeeded);
1194 return true;
1195}
1196
Vishnu Nair6213bd92020-05-08 17:42:25 -07001197bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001198 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001199 return false;
1200 }
1201
Robert Carr6a160312021-05-17 12:08:20 -07001202 mDrawingState.sequence++;
1203 mDrawingState.fixedTransformHint = fixedTransformHint;
1204 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001205 setTransactionFlags(eTransactionNeeded);
1206 return true;
1207}
1208
John Reckcdb4ed72021-02-04 13:39:33 -05001209bool Layer::setStretchEffect(const StretchEffect& effect) {
1210 StretchEffect temp = effect;
1211 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001212 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001213 return false;
1214 }
Robert Carr6a160312021-05-17 12:08:20 -07001215 mDrawingState.sequence++;
1216 mDrawingState.stretchEffect = temp;
1217 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001218 setTransactionFlags(eTransactionNeeded);
1219 return true;
1220}
1221
John Reckc00c6692021-02-16 11:37:33 -05001222StretchEffect Layer::getStretchEffect() const {
1223 if (mDrawingState.stretchEffect.hasEffect()) {
1224 return mDrawingState.stretchEffect;
1225 }
1226
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001227 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001228 if (parent != nullptr) {
1229 auto effect = parent->getStretchEffect();
1230 if (effect.hasEffect()) {
1231 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1232 return effect;
1233 }
1234 }
1235 return StretchEffect{};
1236}
1237
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001238bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1239 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001240 return false;
1241 }
1242 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001243 mBorderWidth = width;
1244 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001245 return true;
1246}
1247
1248bool Layer::isBorderEnabled() {
1249 return mBorderEnabled;
1250}
1251
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001252float Layer::getBorderWidth() {
1253 return mBorderWidth;
1254}
1255
1256const half4& Layer::getBorderColor() {
1257 return mBorderColor;
1258}
1259
Rachel Lee0faad6c2023-09-08 13:34:34 -07001260bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool overrideChildren,
1261 bool* transactionNeeded) {
1262 // Gets the frame rate to propagate to children.
Ady Abrahama850c182021-08-04 13:04:37 -07001263 const auto frameRate = [&] {
Rachel Lee0faad6c2023-09-08 13:34:34 -07001264 if (overrideChildren && parentFrameRate.isValid()) {
1265 return parentFrameRate;
1266 }
1267
Rachel Leece6e0042023-06-27 11:22:54 -07001268 if (mDrawingState.frameRate.isValid()) {
Ady Abrahama850c182021-08-04 13:04:37 -07001269 return mDrawingState.frameRate;
1270 }
1271
1272 return parentFrameRate;
1273 }();
1274
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001275 auto now = systemTime();
1276 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate, now);
Ady Abrahama850c182021-08-04 13:04:37 -07001277
Rachel Leea021bb02023-11-20 21:51:09 -08001278 // The frame rate is propagated to the children by default, but some properties may override it.
Ady Abrahama850c182021-08-04 13:04:37 -07001279 bool childrenHaveFrameRate = false;
Rachel Leea021bb02023-11-20 21:51:09 -08001280 const bool overrideChildrenFrameRate = overrideChildren || shouldOverrideChildrenFrameRate();
1281 const bool canPropagateFrameRate = shouldPropagateFrameRate() || overrideChildrenFrameRate;
Ady Abrahama850c182021-08-04 13:04:37 -07001282 for (const sp<Layer>& child : mCurrentChildren) {
1283 childrenHaveFrameRate |=
Rachel Leea021bb02023-11-20 21:51:09 -08001284 child->propagateFrameRateForLayerTree(canPropagateFrameRate ? frameRate
1285 : FrameRate(),
1286 overrideChildrenFrameRate, transactionNeeded);
Ady Abrahama850c182021-08-04 13:04:37 -07001287 }
1288
Rachel Leece6e0042023-06-27 11:22:54 -07001289 // If we don't have a valid frame rate specification, but the children do, we set this
Ady Abrahama850c182021-08-04 13:04:37 -07001290 // layer as NoVote to allow the children to control the refresh rate
Rachel Leece6e0042023-06-27 11:22:54 -07001291 if (!frameRate.isValid() && childrenHaveFrameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001292 *transactionNeeded |=
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001293 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote),
1294 now);
Ady Abrahama850c182021-08-04 13:04:37 -07001295 }
1296
Rachel Leece6e0042023-06-27 11:22:54 -07001297 // We return whether this layer or its children has a vote. We ignore ExactOrMultiple votes for
Ady Abrahama850c182021-08-04 13:04:37 -07001298 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001299 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001300 const auto layerVotedWithDefaultCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001301 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Default;
1302 const auto layerVotedWithNoVote = frameRate.vote.type == FrameRateCompatibility::NoVote;
1303 const auto layerVotedWithCategory = frameRate.category != FrameRateCategory::Default;
Ady Abrahama850c182021-08-04 13:04:37 -07001304 const auto layerVotedWithExactCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001305 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Exact;
1306 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote || layerVotedWithCategory ||
Ady Abrahama850c182021-08-04 13:04:37 -07001307 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1308}
1309
Ady Abraham60e42ea2020-03-09 19:17:31 -07001310void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001311 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001312 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001313 while (auto parent = layer->getParent()) {
1314 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001315 }
Ady Abrahama850c182021-08-04 13:04:37 -07001316 return layer;
1317 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001318
Ady Abraham60e42ea2020-03-09 19:17:31 -07001319 bool transactionNeeded = false;
Rachel Lee0faad6c2023-09-08 13:34:34 -07001320 root->propagateFrameRateForLayerTree({}, false, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001321
Ady Abrahama850c182021-08-04 13:04:37 -07001322 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001323 if (transactionNeeded) {
1324 mFlinger->setTransactionFlags(eTraversalNeeded);
1325 }
1326}
1327
Rachel Leece6e0042023-06-27 11:22:54 -07001328bool Layer::setFrameRate(FrameRate::FrameRateVote frameRateVote) {
1329 if (mDrawingState.frameRate.vote == frameRateVote) {
Steven Thomas3172e202020-01-06 19:25:30 -08001330 return false;
1331 }
1332
Robert Carr6a160312021-05-17 12:08:20 -07001333 mDrawingState.sequence++;
Rachel Leece6e0042023-06-27 11:22:54 -07001334 mDrawingState.frameRate.vote = frameRateVote;
1335 mDrawingState.modified = true;
1336
1337 updateTreeHasFrameRateVote();
1338
1339 setTransactionFlags(eTransactionNeeded);
1340 return true;
1341}
1342
Rachel Lee67afbea2023-09-28 15:35:07 -07001343bool Layer::setFrameRateCategory(FrameRateCategory category, bool smoothSwitchOnly) {
1344 if (mDrawingState.frameRate.category == category &&
1345 mDrawingState.frameRate.categorySmoothSwitchOnly == smoothSwitchOnly) {
Rachel Leece6e0042023-06-27 11:22:54 -07001346 return false;
1347 }
1348
1349 mDrawingState.sequence++;
1350 mDrawingState.frameRate.category = category;
Rachel Lee67afbea2023-09-28 15:35:07 -07001351 mDrawingState.frameRate.categorySmoothSwitchOnly = smoothSwitchOnly;
Robert Carr6a160312021-05-17 12:08:20 -07001352 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001353
1354 updateTreeHasFrameRateVote();
1355
Steven Thomas3172e202020-01-06 19:25:30 -08001356 setTransactionFlags(eTransactionNeeded);
1357 return true;
1358}
1359
Rachel Lee58cc90d2023-09-05 18:50:20 -07001360bool Layer::setFrameRateSelectionStrategy(FrameRateSelectionStrategy strategy) {
1361 if (mDrawingState.frameRateSelectionStrategy == strategy) return false;
1362 mDrawingState.frameRateSelectionStrategy = strategy;
1363 mDrawingState.sequence++;
1364 mDrawingState.modified = true;
Rachel Leed7479502023-09-25 17:02:35 -07001365
1366 updateTreeHasFrameRateVote();
Rachel Lee58cc90d2023-09-05 18:50:20 -07001367 setTransactionFlags(eTransactionNeeded);
1368 return true;
1369}
1370
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001371void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1372 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001373 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001374
1375 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1376 // there are two transactions with the same token, the first one without a buffer and the
1377 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1378 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001379 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1380 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001381 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001382 mDrawingState.bufferSurfaceFrameTX = it->second;
1383 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1384 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1385 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001386 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001387 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001388 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1389 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001390
1391 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001392}
1393
1394void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1395 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001396 mDrawingState.frameTimelineInfo = info;
1397 mDrawingState.postTime = postTime;
1398 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001399 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001400
Robert Carr6a160312021-05-17 12:08:20 -07001401 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001402 bufferSurfaceFrameTX != nullptr) {
1403 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1404 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1405 // being used for BufferSurfaceFrame, don't create a new one.
1406 return;
1407 }
1408 }
1409 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1410 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1411 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001412 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1413 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001414 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001415 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001416 } else {
1417 if (it->second->getPresentState() == PresentState::Presented) {
1418 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1419 // have been from previous vsync.
1420 it->second = createSurfaceFrameForTransaction(info, postTime);
1421 }
1422 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001423
1424 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001425}
1426
1427void Layer::addSurfaceFrameDroppedForBuffer(
Ady Abraham5a3e3562023-06-07 10:32:08 -07001428 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t dropTime) {
1429 surfaceFrame->setDropTime(dropTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001430 surfaceFrame->setPresentState(PresentState::Dropped);
1431 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1432}
1433
1434void Layer::addSurfaceFramePresentedForBuffer(
1435 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1436 nsecs_t currentLatchTime) {
1437 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1438 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1439 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001440 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001441}
1442
1443std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1444 const FrameTimelineInfo& info, nsecs_t postTime) {
1445 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001446 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1447 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001448 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001449 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001450 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001451 // For Transactions, the post time is considered to be both queue and acquire fence time.
1452 surfaceFrame->setActualQueueTime(postTime);
1453 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001454 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1455 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001456 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001457 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001458 onSurfaceFrameCreated(surfaceFrame);
1459 return surfaceFrame;
1460}
1461
1462std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1463 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1464 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001465 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001466 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001467 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001468 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001469 // For buffers, acquire fence time will set during latch.
1470 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001471 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1472 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001473 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001474 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001475 onSurfaceFrameCreated(surfaceFrame);
1476 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001477}
1478
Ady Abraham5a3e3562023-06-07 10:32:08 -07001479void Layer::setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
1480 std::string debugName) {
1481 if (info.skippedFrameVsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
1482 return;
1483 }
1484
1485 FrameTimelineInfo skippedFrameTimelineInfo = info;
1486 skippedFrameTimelineInfo.vsyncId = info.skippedFrameVsyncId;
1487
1488 auto surfaceFrame =
1489 mFlinger->mFrameTimeline->createSurfaceFrameForToken(skippedFrameTimelineInfo,
1490 mOwnerPid, mOwnerUid,
1491 getSequence(), mName, debugName,
1492 /*isBuffer*/ false, getGameMode());
1493 surfaceFrame->setActualStartTime(skippedFrameTimelineInfo.skippedFrameStartTimeNanos);
1494 // For Transactions, the post time is considered to be both queue and acquire fence time.
1495 surfaceFrame->setActualQueueTime(postTime);
1496 surfaceFrame->setAcquireFenceTime(postTime);
1497 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1498 if (fps) {
1499 surfaceFrame->setRenderRate(*fps);
1500 }
1501 onSurfaceFrameCreated(surfaceFrame);
1502 addSurfaceFrameDroppedForBuffer(surfaceFrame, postTime);
1503}
1504
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001505bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate, nsecs_t now) {
Ady Abrahama850c182021-08-04 13:04:37 -07001506 if (mDrawingState.frameRateForLayerTree == frameRate) {
1507 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001508 }
1509
Ady Abrahama850c182021-08-04 13:04:37 -07001510 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001511
Ady Abrahama850c182021-08-04 13:04:37 -07001512 // TODO(b/195668952): we probably don't need to dirty visible regions here
1513 // or even store frameRateForLayerTree in mDrawingState
1514 mDrawingState.sequence++;
1515 mDrawingState.modified = true;
1516 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001517
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001518 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001519 ->recordLayerHistory(sequence, getLayerProps(), now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001520 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1521 return true;
1522}
Ady Abrahama850c182021-08-04 13:04:37 -07001523
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001524bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps,
1525 nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001526 if (mDrawingState.frameRateForLayerTree == frameRate) {
1527 return false;
1528 }
1529
1530 mDrawingState.frameRateForLayerTree = frameRate;
1531 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001532 ->recordLayerHistory(sequence, layerProps, now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001533 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001534 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001535}
1536
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001537Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1538 return getDrawingState().frameRateForLayerTree;
1539}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001540
Robert Carr1f0a16a2016-10-24 16:27:39 -07001541bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001542 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001543 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001544 if (parent != nullptr && parent->isHiddenByPolicy()) {
1545 return true;
1546 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001547 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1548 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1549 if (zOrderRelativeOf != nullptr) {
1550 if (zOrderRelativeOf->isHiddenByPolicy()) {
1551 return true;
1552 }
1553 }
1554 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001555 if (CC_UNLIKELY(!isTransformValid())) {
1556 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1557 return true;
1558 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001559 return s.flags & layer_state_t::eLayerHidden;
1560}
1561
David Sodman41fdfc92017-11-06 16:09:56 -08001562uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001563 // TODO: should we do something special if mSecure is set?
1564 if (mProtectedByApp) {
1565 // need a hardware-protected path to external video sink
1566 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001567 }
Riley Andrews03414a12014-07-01 14:22:59 -07001568 if (mPotentialCursor) {
1569 usage |= GraphicBuffer::USAGE_CURSOR;
1570 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001571 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001572 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001573}
1574
Vishnu Nair71fcf912022-10-18 09:14:20 -07001575void Layer::skipReportingTransformHint() {
1576 mSkipReportingTransformHint = true;
1577}
1578
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001579void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1580 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1581 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001582 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001583
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001584 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001585}
1586
Mathias Agopian13127d82013-03-05 17:47:11 -08001587// ----------------------------------------------------------------------------
1588// debugging
1589// ----------------------------------------------------------------------------
1590
Marissa Wall61c58622018-07-18 10:12:20 -07001591// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001592gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001593 using namespace std::string_literals;
1594
Huihong Luo05539a12022-02-23 10:29:40 -08001595 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001596 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001597 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001598 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001599 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001600 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001601
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001602 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001603 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001604 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001605 info.mX = ds.transform.tx();
1606 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001607 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001608 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001609 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001610 info.mFlags = ds.flags;
1611 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001612 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001613 info.mMatrix[0][0] = ds.transform[0][0];
1614 info.mMatrix[0][1] = ds.transform[0][1];
1615 info.mMatrix[1][0] = ds.transform[1][0];
1616 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001617 {
chaviwd62d3062019-09-04 14:48:02 -07001618 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001619 if (buffer != 0) {
1620 info.mActiveBufferWidth = buffer->getWidth();
1621 info.mActiveBufferHeight = buffer->getHeight();
1622 info.mActiveBufferStride = buffer->getStride();
1623 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001624 } else {
1625 info.mActiveBufferWidth = 0;
1626 info.mActiveBufferHeight = 0;
1627 info.mActiveBufferStride = 0;
1628 info.mActiveBufferFormat = 0;
1629 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001630 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001631 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001632 info.mIsOpaque = isOpaque(ds);
1633 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001634 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001635 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001636}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001637
Yiwei Zhang5434a782018-12-05 18:06:32 -08001638void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001639 result.append(kDumpTableRowLength, '-');
1640 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001641 result.append(" Layer name\n");
1642 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001643 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001644 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001645 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001646 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001647 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001648 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1649 result.append(kDumpTableRowLength, '-');
1650 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001651}
1652
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001653void Layer::miniDumpLegacy(std::string& result, const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001654 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001655 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001656 return;
1657 }
1658
Yiwei Zhang5434a782018-12-05 18:06:32 -08001659 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001660 if (mName.length() > 77) {
1661 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001662 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001663 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001664 shortened.append(mName, mName.length() - 36);
1665 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001666 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001667 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001668 }
1669
Yiwei Zhang5434a782018-12-05 18:06:32 -08001670 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001671
Alec Mourib416efd2018-09-06 21:01:59 +00001672 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001673 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001674
Chia-I Wu1e043612018-03-01 09:45:09 -08001675 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001676 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001677 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001678 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001679 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001680 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001681 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001682 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1683 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001684 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001685 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001686 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001687 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001688 const auto frameRate = getFrameRateForLayerTree();
Rachel Leece6e0042023-06-27 11:22:54 -07001689 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
1690 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.vote.rate).c_str(),
1691 ftl::enum_string(frameRate.vote.type).c_str(),
1692 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001693 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001694 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001695 }
Dan Stozae22aec72016-08-01 13:20:59 -07001696
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001697 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1698 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1699
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001700 result.append(kDumpTableRowLength, '-');
1701 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001702}
Dan Stozae22aec72016-08-01 13:20:59 -07001703
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001704void Layer::miniDump(std::string& result, const frontend::LayerSnapshot& snapshot,
1705 const DisplayDevice& display) const {
1706 const auto outputLayer = findOutputLayerForDisplay(&display, snapshot.path);
1707 if (!outputLayer) {
1708 return;
1709 }
1710
1711 StringAppendF(&result, " %s\n", snapshot.debugName.c_str());
1712 StringAppendF(&result, " %10zu | ", snapshot.globalZ);
1713 StringAppendF(&result, " %10d | ",
1714 snapshot.layerMetadata.getInt32(gui::METADATA_WINDOW_TYPE, 0));
1715 StringAppendF(&result, "%10s | ", toString(getCompositionType(outputLayer)).c_str());
1716 const auto& outputLayerState = outputLayer->getState();
1717 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1718 const Rect& frame = outputLayerState.displayFrame;
1719 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1720 const FloatRect& crop = outputLayerState.sourceCrop;
1721 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
1722 crop.bottom);
1723 const auto frameRate = snapshot.frameRate;
Ady Abraham77d406d2023-11-22 15:00:23 -08001724 std::string frameRateStr;
1725 if (frameRate.vote.rate.isValid()) {
1726 StringAppendF(&frameRateStr, "%.2f", frameRate.vote.rate.getValue());
1727 }
Rachel Leece6e0042023-06-27 11:22:54 -07001728 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
Ady Abraham77d406d2023-11-22 15:00:23 -08001729 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
Rachel Leece6e0042023-06-27 11:22:54 -07001730 ftl::enum_string(frameRate.vote.type).c_str(),
1731 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abraham77d406d2023-11-22 15:00:23 -08001732 } else if (frameRate.category != FrameRateCategory::Default) {
1733 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
1734 (std::string("Cat::") + ftl::enum_string(frameRate.category)).c_str(),
1735 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001736 } else {
1737 result.append(41, ' ');
1738 }
1739
1740 const auto focused = isLayerFocusedBasedOnPriority(snapshot.frameRateSelectionPriority);
1741 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1742
1743 result.append(kDumpTableRowLength, '-');
1744 result.append("\n");
1745}
1746
Yiwei Zhang5434a782018-12-05 18:06:32 -08001747void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001748 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001749}
1750
Svetoslavd85084b2014-03-20 10:28:31 -07001751void Layer::clearFrameStats() {
1752 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001753}
1754
Jamie Gennis6547ff42013-07-16 20:12:42 -07001755void Layer::logFrameStats() {
1756 mFrameTracker.logAndResetStats(mName);
1757}
1758
Svetoslavd85084b2014-03-20 10:28:31 -07001759void Layer::getFrameStats(FrameStats* outStats) const {
1760 mFrameTracker.getStats(outStats);
1761}
1762
Vishnu Nair76554eb2022-12-09 03:38:36 +00001763void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1764 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
Vishnu Nair3be61902023-04-26 19:47:29 -07001765 StringAppendF(&result, "Layer %s%s pid:%d uid:%d%s\n", getName().c_str(), hasBuffer.c_str(),
1766 mOwnerPid, mOwnerUid, isHandleAlive() ? " handleAlive" : "");
Vishnu Nair0f085c62019-08-30 08:49:12 -07001767}
1768
Brian Anderson5ea5e592016-12-01 16:54:33 -08001769void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001770 const int32_t layerId = getSequence();
1771 mFlinger->mTimeStats->onDestroy(layerId);
1772 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001773}
1774
Vishnu Nair787aa782023-03-17 13:46:46 -07001775size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001776 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001777 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001778 count += 1 + child->getChildrenCount();
1779 }
1780 return count;
1781}
1782
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001783void Layer::setGameModeForTree(GameMode gameMode) {
1784 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001785 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1786 gameMode =
1787 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001788 }
1789 setGameMode(gameMode);
1790 for (const sp<Layer>& child : mCurrentChildren) {
1791 child->setGameModeForTree(gameMode);
1792 }
1793}
1794
Robert Carr1f0a16a2016-10-24 16:27:39 -07001795void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001796 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001797 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001798
Robert Carr1f0a16a2016-10-24 16:27:39 -07001799 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001800 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001801 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001802 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001803}
1804
1805ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001806 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001807 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001808
Robert Carr1323c952019-01-28 18:13:27 -08001809 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001810 const auto removeResult = mCurrentChildren.remove(layer);
1811
1812 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001813 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001814 layer->updateTreeHasFrameRateVote();
1815
1816 return removeResult;
1817}
1818
Robert Carr15eae092018-03-23 13:43:53 -07001819void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001820 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001821 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001822 const float parentShadowRadius =
1823 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001824 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001825 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001826 }
1827}
1828
chaviwf1961f72017-09-18 16:41:07 -07001829bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001830 sp<Layer> newParent;
1831 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001832 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001833 if (newParent == nullptr) {
1834 ALOGE("Unable to promote Layer handle");
1835 return false;
1836 }
1837 if (newParent == this) {
1838 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1839 return false;
1840 }
1841 }
1842
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001843 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001844 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001845 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001846 }
1847
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001848 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001849 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001850 if (!newParent->isRemovedFromCurrentState()) {
1851 addToCurrentState();
1852 } else {
1853 onRemovedFromCurrentState();
1854 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001855 } else {
1856 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001857 }
1858
chaviw06178942017-07-27 10:25:59 -07001859 return true;
1860}
1861
Peiyong Lind3788632018-09-18 16:01:31 -07001862bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001863 static const mat4 identityMatrix = mat4();
1864
Robert Carr6a160312021-05-17 12:08:20 -07001865 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001866 return false;
1867 }
Robert Carr6a160312021-05-17 12:08:20 -07001868 ++mDrawingState.sequence;
1869 mDrawingState.colorTransform = matrix;
1870 mDrawingState.hasColorTransform = matrix != identityMatrix;
1871 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001872 setTransactionFlags(eTransactionNeeded);
1873 return true;
1874}
1875
chaviwf66724d2018-11-28 16:35:21 -08001876mat4 Layer::getColorTransform() const {
1877 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001878 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001879 colorTransform = parent->getColorTransform() * colorTransform;
1880 }
1881 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001882}
1883
1884bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001885 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001886 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001887 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1888 }
1889 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001890}
1891
Chia-I Wu11481472018-05-04 10:43:19 -07001892bool Layer::isLegacyDataSpace() const {
1893 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001894 return !(getDataSpace() &
1895 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1896 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001897}
1898
Robert Carr1f0a16a2016-10-24 16:27:39 -07001899void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001900 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001901}
1902
Robert Carr6a160312021-05-17 12:08:20 -07001903int32_t Layer::getZ(LayerVector::StateSet) const {
1904 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001905}
1906
Robert Carr1c5481e2019-07-01 14:42:27 -07001907bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001908 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001909 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001910 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001911}
1912
David Sodman41fdfc92017-11-06 16:09:56 -08001913__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001914 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001915 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1916 "makeTraversalList received invalid stateSet");
1917 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1918 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001919 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001920
Robert Carr29abff82017-12-04 13:51:20 -08001921 if (state.zOrderRelatives.size() == 0) {
1922 *outSkipRelativeZUsers = true;
1923 return children;
1924 }
1925
chaviwfd462612018-05-31 16:11:27 -07001926 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001927 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001928 sp<Layer> strongRelative = weakRelative.promote();
1929 if (strongRelative != nullptr) {
1930 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001931 }
1932 }
1933
Dan Stoza412903f2017-04-27 13:42:17 -07001934 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001935 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001936 continue;
1937 }
Robert Carrdb66e622017-04-10 16:55:57 -07001938 traverse.add(child);
1939 }
1940
1941 return traverse;
1942}
1943
Robert Carr1f0a16a2016-10-24 16:27:39 -07001944/**
Robert Carrdb66e622017-04-10 16:55:57 -07001945 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001946 */
Dan Stoza412903f2017-04-27 13:42:17 -07001947void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001948 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1949 // produce a new list for traversing, including our relatives, and not including our children
1950 // who are relatives of another surface. In the case that there are no relative Z,
1951 // makeTraversalList returns our children directly to avoid significant overhead.
1952 // However in this case we need to take the responsibility for filtering children which
1953 // are relatives of another surface here.
1954 bool skipRelativeZUsers = false;
1955 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001956
Robert Carr1f0a16a2016-10-24 16:27:39 -07001957 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001958 for (; i < list.size(); i++) {
1959 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001960 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1961 continue;
1962 }
1963
chaviw301b1d82019-11-06 13:15:09 -08001964 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001965 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001966 }
Dan Stoza412903f2017-04-27 13:42:17 -07001967 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001968 }
Robert Carr29abff82017-12-04 13:51:20 -08001969
Dan Stoza412903f2017-04-27 13:42:17 -07001970 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001971 for (; i < list.size(); i++) {
1972 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001973
Robert Carr29abff82017-12-04 13:51:20 -08001974 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1975 continue;
1976 }
Dan Stoza412903f2017-04-27 13:42:17 -07001977 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001978 }
1979}
1980
1981/**
Robert Carrdb66e622017-04-10 16:55:57 -07001982 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001983 */
Dan Stoza412903f2017-04-27 13:42:17 -07001984void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1985 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001986 // See traverseInZOrder for documentation.
1987 bool skipRelativeZUsers = false;
1988 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001989
Robert Carr1f0a16a2016-10-24 16:27:39 -07001990 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001991 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001992 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001993
1994 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1995 continue;
1996 }
1997
chaviw301b1d82019-11-06 13:15:09 -08001998 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001999 break;
2000 }
Dan Stoza412903f2017-04-27 13:42:17 -07002001 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002002 }
Dan Stoza412903f2017-04-27 13:42:17 -07002003 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08002004 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002005 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08002006
2007 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
2008 continue;
2009 }
2010
Dan Stoza412903f2017-04-27 13:42:17 -07002011 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002012 }
2013}
2014
Edgar Arriaga844fa672020-01-16 14:21:42 -08002015void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
2016 visitor(this);
2017 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07002018 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002019 for (const sp<Layer>& child : children) {
2020 child->traverse(state, visitor);
2021 }
2022}
2023
Vishnu Nair787aa782023-03-17 13:46:46 -07002024void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
2025 for (const sp<Layer>& child : mDrawingChildren) {
2026 visitor(child.get());
2027 }
2028}
2029
chaviw4b129c22018-04-09 16:19:43 -07002030LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
2031 const std::vector<Layer*>& layersInTree) {
2032 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2033 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07002034 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2035 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002036 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002037
chaviwfd462612018-05-31 16:11:27 -07002038 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07002039 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2040 sp<Layer> strongRelative = weakRelative.promote();
2041 // Only add relative layers that are also descendents of the top most parent of the tree.
2042 // If a relative layer is not a descendent, then it should be ignored.
2043 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
2044 traverse.add(strongRelative);
2045 }
2046 }
2047
2048 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07002049 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002050 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
2051 // descendent of the top most parent of the tree. If it's not a descendent, then just add
2052 // the child here since it won't be added later as a relative.
2053 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
2054 childState.zOrderRelativeOf.promote().get())) {
2055 continue;
2056 }
2057 traverse.add(child);
2058 }
2059
2060 return traverse;
2061}
2062
2063void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
2064 LayerVector::StateSet stateSet,
2065 const LayerVector::Visitor& visitor) {
2066 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07002067
2068 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07002069 for (; i < list.size(); i++) {
2070 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08002071 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07002072 break;
2073 }
chaviw4b129c22018-04-09 16:19:43 -07002074 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002075 }
chaviw4b129c22018-04-09 16:19:43 -07002076
chaviwa76b2712017-09-20 12:02:26 -07002077 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07002078 for (; i < list.size(); i++) {
2079 const auto& relative = list[i];
2080 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002081 }
2082}
2083
chaviw4b129c22018-04-09 16:19:43 -07002084std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2085 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2086 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2087
2088 std::vector<Layer*> layersInTree = {this};
2089 for (size_t i = 0; i < children.size(); i++) {
2090 const auto& child = children[i];
2091 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2092 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2093 }
2094
2095 return layersInTree;
2096}
2097
2098void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2099 const LayerVector::Visitor& visitor) {
2100 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2101 std::sort(layersInTree.begin(), layersInTree.end());
2102 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2103}
2104
Peiyong Linefefaac2018-08-17 12:27:51 -07002105ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08002106 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002107}
2108
Garfield Tan2c1782c2022-02-16 15:25:05 -08002109bool Layer::isTransformValid() const {
2110 float transformDet = getTransform().det();
2111 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2112}
2113
chaviw13fdc492017-06-27 12:40:18 -07002114half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002115 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002116
chaviw13fdc492017-06-27 12:40:18 -07002117 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2118 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002119}
Robert Carr6452f122017-03-21 10:41:29 -07002120
Vishnu Nair6213bd92020-05-08 17:42:25 -07002121ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002122 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002123 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2124 return fixedTransformHint;
2125 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002126 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002127 if (!p) return fixedTransformHint;
2128 return p->getFixedTransformHint();
2129}
2130
chaviw13fdc492017-06-27 12:40:18 -07002131half4 Layer::getColor() const {
2132 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002133 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002134}
Robert Carr6452f122017-03-21 10:41:29 -07002135
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002136int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002137 if (getDrawingState().backgroundBlurRadius == 0) {
2138 return 0;
2139 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002140
Vishnu Nair29810f72022-07-01 16:38:41 +00002141 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002142 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2143 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002144}
2145
Galia Peychevae0acf382021-04-12 21:22:34 +02002146const std::vector<BlurRegion> Layer::getBlurRegions() const {
2147 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002148 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002149 for (auto& region : regionsCopy) {
2150 region.alpha = region.alpha * layerAlpha;
2151 }
2152 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002153}
2154
Vishnu Naire14c6b32022-08-06 04:20:15 +00002155RoundedCornerState Layer::getRoundedCornerState() const {
Leon Scroggins IIIc1dbfcb2022-03-21 16:48:10 -04002156 // Today's DPUs cannot do rounded corners. If RenderEngine cannot render
2157 // protected content, remove rounded corners from protected content so it
2158 // can be rendered by the DPU.
2159 if (isProtected() && !mFlinger->getRenderEngine().supportsProtectedContent()) {
2160 return {};
2161 }
2162
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002163 // Get parent settings
2164 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002165 const auto& parent = mDrawingParent.promote();
2166 if (parent != nullptr) {
2167 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002168 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002169 ui::Transform t = getActiveTransform(getDrawingState());
2170 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002171 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002172 parentSettings.radius.x *= t.getScaleX();
2173 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002174 }
2175 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002176
2177 // Get layer settings
2178 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002179 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002180 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002181 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002182
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002183 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002184 // If the parent and the layer have rounded corner settings, use the parent settings if the
2185 // parent crop is entirely inside the layer crop.
2186 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2187 if (parentSettings.cropRect.left > layerCropRect.left &&
2188 parentSettings.cropRect.top > layerCropRect.top &&
2189 parentSettings.cropRect.right < layerCropRect.right &&
2190 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2191 return parentSettings;
2192 } else {
2193 return layerSettings;
2194 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002195 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002196 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002197 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002198 return parentSettings;
2199 }
2200 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002201}
2202
Robert Carr88b85e12022-03-21 15:47:35 -07002203bool Layer::findInHierarchy(const sp<Layer>& l) {
2204 if (l == this) {
2205 return true;
2206 }
2207 for (auto& child : mDrawingChildren) {
2208 if (child->findInHierarchy(l)) {
2209 return true;
2210 }
2211 }
2212 return false;
2213}
2214
Robert Carr1f0a16a2016-10-24 16:27:39 -07002215void Layer::commitChildList() {
2216 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2217 const auto& child = mCurrentChildren[i];
2218 child->commitChildList();
2219 }
2220 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002221 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002222 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2223 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2224 if (zOrderRelativeOf == nullptr) return;
2225 if (findInHierarchy(zOrderRelativeOf)) {
2226 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2227 zOrderRelativeOf->mName.c_str());
2228 ALOGE("Severing rel Z loop, potentially dangerous");
2229 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002230 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002231 }
2232 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002233}
2234
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002235
chaviw3277faf2021-05-19 16:45:23 -05002236void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002237 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002238 mDrawingState.touchableRegionCrop =
2239 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002240 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002241 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002242 setTransactionFlags(eTransactionNeeded);
2243}
2244
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002245perfetto::protos::LayerProto* Layer::writeToProto(perfetto::protos::LayersProto& layersProto,
2246 uint32_t traceFlags) {
2247 perfetto::protos::LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002248 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002249 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2250
Vishnu Nair00b90132021-11-05 14:03:40 -07002251 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nair2f65e972023-04-04 16:36:28 +00002252 ui::LayerStack layerStack =
2253 (mSnapshot) ? mSnapshot->outputFilter.layerStack : ui::INVALID_LAYER_STACK;
2254 writeCompositionStateToProto(layerProto, layerStack);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002255 }
2256
chaviw08f3cb22020-01-13 13:17:21 -08002257 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002258 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002259 }
chaviw6d89e2d2020-01-14 14:42:01 -08002260
2261 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002262}
2263
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002264void Layer::writeCompositionStateToProto(perfetto::protos::LayerProto* layerProto,
2265 ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002266 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002267 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +00002268
2269 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002270 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002271 const auto compositionType = getCompositionType(*display);
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002272 layerProto->set_hwc_composition_type(
2273 static_cast<perfetto::protos::HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +00002274 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +00002275 [&]() { return layerProto->mutable_visible_region(); });
2276 }
2277}
2278
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002279void Layer::writeToProtoDrawingState(perfetto::protos::LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002280 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002281 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002282 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002283 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002284 [&]() { return layerInfo->mutable_active_buffer(); });
2285 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2286 layerInfo->mutable_buffer_transform());
2287 }
2288 layerInfo->set_invalidate(contentDirty);
2289 layerInfo->set_is_protected(isProtected());
2290 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2291 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002292 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002293 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002294 layerInfo->set_corner_radius(
2295 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002296 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2297 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2298 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2299 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2300 [&]() { return layerInfo->mutable_position(); });
2301 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002302 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2303 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002304
Vishnu Nair00b90132021-11-05 14:03:40 -07002305 if (hasColorTransform()) {
2306 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002307 }
2308
Vishnu Nair60db8c02020-04-02 11:55:16 -07002309 LayerProtoHelper::writeToProto(mSourceBounds,
2310 [&]() { return layerInfo->mutable_source_bounds(); });
2311 LayerProtoHelper::writeToProto(mScreenBounds,
2312 [&]() { return layerInfo->mutable_screen_bounds(); });
2313 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2314 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2315 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002316}
2317
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002318void Layer::writeToProtoCommonState(perfetto::protos::LayerProto* layerInfo,
2319 LayerVector::StateSet stateSet, uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002320 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2321 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002322 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002323
chaviw766c9c52021-02-10 17:36:47 -08002324 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002325
Vishnu Nair00b90132021-11-05 14:03:40 -07002326 layerInfo->set_id(sequence);
2327 layerInfo->set_name(getName().c_str());
2328 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002329
Vishnu Nair00b90132021-11-05 14:03:40 -07002330 for (const auto& child : children) {
2331 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002332 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002333
Vishnu Nair00b90132021-11-05 14:03:40 -07002334 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2335 sp<Layer> strongRelative = weakRelative.promote();
2336 if (strongRelative != nullptr) {
2337 layerInfo->add_relatives(strongRelative->sequence);
2338 }
2339 }
2340
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002341 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002342 [&]() { return layerInfo->mutable_transparent_region(); });
2343
2344 layerInfo->set_layer_stack(getLayerStack().id);
2345 layerInfo->set_z(state.z);
2346
2347 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2348 return layerInfo->mutable_requested_position();
2349 });
2350
Vishnu Nair00b90132021-11-05 14:03:40 -07002351 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2352
2353 layerInfo->set_is_opaque(isOpaque(state));
2354
2355 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2356 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2357 LayerProtoHelper::writeToProto(state.color,
2358 [&]() { return layerInfo->mutable_requested_color(); });
2359 layerInfo->set_flags(state.flags);
2360
2361 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2362 layerInfo->mutable_requested_transform());
2363
2364 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2365 if (parent != nullptr) {
2366 layerInfo->set_parent(parent->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002367 }
2368
2369 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2370 if (zOrderRelativeOf != nullptr) {
2371 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002372 }
2373
2374 layerInfo->set_is_relative_of(state.isRelativeOf);
2375
2376 layerInfo->set_owner_uid(mOwnerUid);
2377
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002378 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002379 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002380 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002381 info = fillInputInfo(
2382 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002383 } else {
2384 info = state.inputInfo;
2385 }
2386
2387 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002388 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002389 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002390
Vishnu Nair00b90132021-11-05 14:03:40 -07002391 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002392 auto protoMap = layerInfo->mutable_metadata();
2393 for (const auto& entry : state.metadata.mMap) {
2394 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2395 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002396 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002397
2398 LayerProtoHelper::writeToProto(state.destinationFrame,
2399 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002400}
2401
Robert Carr2e102c92018-10-23 12:11:15 -07002402bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002403 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002404}
2405
Prabir Pradhan33da9462022-06-14 14:55:57 +00002406// Applies the given transform to the region, while protecting against overflows caused by any
2407// offsets. If applying the offset in the transform to any of the Rects in the region would result
2408// in an overflow, they are not added to the output Region.
2409static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2410 const std::string& debugWindowName) {
2411 // Round the translation using the same rounding strategy used by ui::Transform.
2412 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2413 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2414
2415 ui::Transform transformWithoutOffset = t;
2416 transformWithoutOffset.set(0.f, 0.f);
2417
2418 const Region transformed = transformWithoutOffset.transform(r);
2419
2420 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2421 Region ret;
2422 for (const auto& rect : transformed) {
2423 Rect newRect;
2424 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2425 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2426 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2427 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2428 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2429 debugWindowName.c_str());
2430 continue;
2431 }
2432 ret.orSelf(newRect);
2433 }
2434 return ret;
2435}
2436
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002437void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002438 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2439 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002440 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002441 }
2442
Chavi Weingarten7f019192023-08-08 20:39:01 +00002443 info.frame = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
chaviw1ff3d1e2020-07-01 15:53:47 -07002444
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002445 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002446 inputToLayer.set(inputBounds.left, inputBounds.top);
2447 const ui::Transform layerToScreen = getInputTransform();
2448 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002449
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002450 // InputDispatcher expects a display-to-input transform.
2451 info.transform = inputToDisplay.inverse();
2452
2453 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002454 info.touchableRegion =
2455 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002456}
2457
chaviw3277faf2021-05-19 16:45:23 -05002458void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002459 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002460 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002461 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002462 }
2463 if (p != nullptr) {
2464 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2465 }
2466}
2467
Vishnu Naira066d902021-09-13 18:40:17 -07002468gui::DropInputMode Layer::getDropInputMode() const {
2469 gui::DropInputMode mode = mDrawingState.dropInputMode;
2470 if (mode == gui::DropInputMode::ALL) {
2471 return mode;
2472 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002473 sp<Layer> parent = mDrawingParent.promote();
2474 if (parent) {
2475 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002476 if (parentMode != gui::DropInputMode::NONE) {
2477 return parentMode;
2478 }
2479 }
2480 return mode;
2481}
2482
2483void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002484 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002485 return;
2486 }
2487
2488 // Check if we need to drop input unconditionally
2489 gui::DropInputMode dropInputMode = getDropInputMode();
2490 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002491 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002492 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2493 return;
2494 }
2495
2496 // Check if we need to check if the window is obscured by parent
2497 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2498 return;
2499 }
2500
2501 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002502 sp<Layer> parent = mDrawingParent.promote();
2503 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002504 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002505 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2506 static_cast<float>(getAlpha()));
2507 }
2508
2509 // Check if the parent has cropped the buffer
2510 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2511 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002512 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002513 return;
2514 }
2515
2516 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2517 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2518 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2519 // match then the layer has not been cropped by its parents.
2520 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2521 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2522
2523 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002524 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002525 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2526 getDebugName());
2527 } else {
2528 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2529 // input if the window is obscured. This check should be done in surfaceflinger but the
2530 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2531 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002532 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002533 }
2534}
2535
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002536WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002537 if (!hasInputInfo()) {
2538 mDrawingState.inputInfo.name = getName();
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002539 mDrawingState.inputInfo.ownerUid = gui::Uid{mOwnerUid};
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00002540 mDrawingState.inputInfo.ownerPid = gui::Pid{mOwnerPid};
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002541 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002542 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002543 }
2544
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002545 const ui::Transform& displayTransform =
2546 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2547
chaviw3277faf2021-05-19 16:45:23 -05002548 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002549 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002550 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002551
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002552 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002553
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002554 if (displayArgs.transform == nullptr) {
2555 // Do not let the window receive touches if it is not associated with a valid display
2556 // transform. We still allow the window to receive keys and prevent ANRs.
2557 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2558 }
2559
Patrick Williams1caf3b72023-03-31 10:59:10 -05002560 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !isVisibleForInput());
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002561
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002562 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002563 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002564 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002565
Vishnu Nair16a938f2021-09-24 07:14:54 -07002566 // If the window will be blacked out on a display because the display does not have the secure
2567 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002568 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002569 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002570 }
2571
Vishnu Nairfed7c122023-03-18 01:54:43 +00002572 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002573 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002574 Rect inputBoundsInDisplaySpace;
2575 if (!cropLayer) {
2576 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2577 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2578 } else {
2579 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2580 inputBoundsInDisplaySpace =
2581 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2582 }
2583 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002584 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002585 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2586 Rect inputBoundsInDisplaySpace =
2587 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2588 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002589 }
2590
Winson Chunga30f7c92021-06-29 15:42:56 -07002591 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2592 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002593 if (isTrustedOverlay()) {
2594 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2595 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002596
chaviwaf87b3e2019-10-01 16:59:28 -07002597 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2598 // touches from going outside the cloned area.
2599 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002600 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002601 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2602 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002603 info.touchableRegion = info.touchableRegion.intersect(rect);
2604 }
2605 }
2606
Vishnu Nair494a2e42023-11-10 17:21:19 -08002607 Rect bufferSize = getBufferSize(getDrawingState());
2608 info.contentSize = Size(bufferSize.width(), bufferSize.height());
2609
Robert Carr720e5062018-07-30 17:45:14 -07002610 return info;
2611}
2612
Vishnu Nairfed7c122023-03-18 01:54:43 +00002613Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2614 const ui::Transform& screenToDisplay) {
2615 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2616 // frame and transform used for the layer, which determines the bounds and the coordinate space
2617 // within which the layer will receive input.
2618
2619 // Coordinate space definitions:
2620 // - display: The display device's coordinate space. Correlates to pixels on the display.
2621 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2622 // - layer: The coordinate space of this layer.
2623 // - input: The coordinate space in which this layer will receive input events. This could be
2624 // different than layer space if a surfaceInset is used, which changes the origin
2625 // of the input space.
2626
2627 // Crop the input bounds to ensure it is within the parent's bounds.
2628 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2629 const ui::Transform layerToScreen = getInputTransform();
2630 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2631 return Rect{layerToDisplay.transform(croppedInputBounds)};
2632}
2633
chaviwaf87b3e2019-10-01 16:59:28 -07002634sp<Layer> Layer::getClonedRoot() {
2635 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002636 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002637 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002638 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002639 return nullptr;
2640 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002641 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002642}
2643
Robert Carredd13602020-04-13 17:24:34 -07002644bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002645 return mDrawingState.inputInfo.token != nullptr ||
2646 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002647}
2648
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002649compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002650 const DisplayDevice* display) const {
2651 if (!display) return nullptr;
Lloyd Pique30db6402023-06-26 18:56:51 +00002652 if (!mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00002653 return display->getCompositionDisplay()->getOutputLayerForLayer(
2654 getCompositionEngineLayerFE());
2655 }
2656 sp<LayerFE> layerFE;
2657 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2658 for (auto& [p, layer] : mLayerFEs) {
2659 if (p == path) {
2660 layerFE = layer;
2661 }
2662 }
2663
2664 if (!layerFE) return nullptr;
2665 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002666}
2667
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002668compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
2669 const DisplayDevice* display, const frontend::LayerHierarchy::TraversalPath& path) const {
2670 if (!display) return nullptr;
Vishnu Naire9ee0002023-07-01 03:14:51 +00002671 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2672 return display->getCompositionDisplay()->getOutputLayerForLayer(
2673 getCompositionEngineLayerFE());
2674 }
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002675 sp<LayerFE> layerFE;
2676 for (auto& [p, layer] : mLayerFEs) {
2677 if (p == path) {
2678 layerFE = layer;
2679 }
2680 }
2681
2682 if (!layerFE) return nullptr;
2683 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
2684}
2685
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002686Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2687 const auto outputLayer = findOutputLayerForDisplay(display);
2688 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002689}
2690
Vishnu Nairde177252023-04-21 12:44:10 -07002691void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom, uint32_t mirrorRootId) {
Vishnu Nair83d91622023-12-08 23:00:22 +00002692 if (mFlinger->mLayerLifecycleManagerEnabled) return;
Vishnu Nairde177252023-04-21 12:44:10 -07002693 mSnapshot->path.id = clonedFrom->getSequence();
Vishnu Nair6f878312023-09-08 11:05:01 -07002694 mSnapshot->path.mirrorRootIds.emplace_back(mirrorRootId);
Vishnu Nairde177252023-04-21 12:44:10 -07002695
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002696 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002697 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002698 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2699 mPotentialCursor = clonedFrom->mPotentialCursor;
2700 mProtectedByApp = clonedFrom->mProtectedByApp;
2701 updateCloneBufferInfo();
2702}
2703
2704void Layer::updateCloneBufferInfo() {
2705 if (!isClone() || !isClonedFromAlive()) {
2706 return;
2707 }
2708
2709 sp<Layer> clonedFrom = getClonedFrom();
2710 mBufferInfo = clonedFrom->mBufferInfo;
2711 mSidebandStream = clonedFrom->mSidebandStream;
2712 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2713 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2714 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2715
2716 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2717 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2718 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2719 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2720 // the cloned drawingState again.
2721 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2722 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2723 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2724 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2725
2726 cloneDrawingState(clonedFrom.get());
2727
2728 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2729 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2730 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2731 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002732}
chaviw74b03172019-08-19 11:09:03 -07002733
Vishnu Nair3be61902023-04-26 19:47:29 -07002734bool Layer::updateMirrorInfo(const std::deque<Layer*>& cloneRootsPendingUpdates) {
chaviw74b03172019-08-19 11:09:03 -07002735 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2736 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2737 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2738 // that case, we want to delete the reference to the clone since we want it to get
2739 // destroyed. The root, this layer, will still be around since the client can continue
2740 // to hold a reference, but no cloned layers will be displayed.
2741 mClonedChild = nullptr;
Vishnu Nair3be61902023-04-26 19:47:29 -07002742 return true;
chaviw74b03172019-08-19 11:09:03 -07002743 }
2744
2745 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2746 // If the real layer exists and is in current state, add the clone as a child of the root.
2747 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2748 // copied to drawingState for the root layer. So the clonedChild is always removed from
2749 // drawingState and then needs to be added back each traversal.
2750 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2751 addChildToDrawing(mClonedChild);
2752 }
2753
2754 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002755 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002756 mClonedChild->updateClonedRelatives(clonedLayersMap);
Vishnu Nair3be61902023-04-26 19:47:29 -07002757
2758 for (Layer* root : cloneRootsPendingUpdates) {
2759 if (clonedLayersMap.find(sp<Layer>::fromExisting(root)) != clonedLayersMap.end()) {
2760 return false;
2761 }
2762 }
2763 return true;
chaviw74b03172019-08-19 11:09:03 -07002764}
2765
2766void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2767 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2768 // to the clone. If the real layer is no longer alive, continue traversing the children
2769 // since we may be able to pull out other children that are still alive.
2770 if (isClonedFromAlive()) {
2771 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002772 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002773 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002774 }
2775
2776 // The clone layer may have children in drawingState since they may have been created and
2777 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2778 // that already exist, since we can just re-use them.
2779 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2780 // not updated in the regular traversal. They are skipped since the root will lose the
2781 // reference to them when it copies its currentChildren to drawing.
2782 for (sp<Layer>& child : mDrawingChildren) {
2783 child->updateClonedDrawingState(clonedLayersMap);
2784 }
2785}
2786
2787void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2788 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2789 mDrawingChildren.clear();
2790
2791 if (!isClonedFromAlive()) {
2792 return;
2793 }
2794
2795 sp<Layer> clonedFrom = getClonedFrom();
2796 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2797 if (child == mirrorRoot) {
2798 // This is to avoid cyclical mirroring.
2799 continue;
2800 }
2801 sp<Layer> clonedChild = clonedLayersMap[child];
2802 if (clonedChild == nullptr) {
Vishnu Nairde177252023-04-21 12:44:10 -07002803 clonedChild = child->createClone(mirrorRoot->getSequence());
chaviw74b03172019-08-19 11:09:03 -07002804 clonedLayersMap[child] = clonedChild;
2805 }
2806 addChildToDrawing(clonedChild);
2807 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2808 }
2809}
2810
chaviwaf87b3e2019-10-01 16:59:28 -07002811void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2812 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2813 if (cropLayer != nullptr) {
2814 if (clonedLayersMap.count(cropLayer) == 0) {
2815 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2816 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002817 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002818 } else {
2819 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2820 mDrawingState.touchableRegionCrop = clonedCropLayer;
2821 }
2822 }
2823 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2824 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002825 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002826}
2827
2828void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002829 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002830 mDrawingState.zOrderRelatives.clear();
2831
2832 if (!isClonedFromAlive()) {
2833 return;
2834 }
2835
chaviwaf87b3e2019-10-01 16:59:28 -07002836 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002837 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002838 const sp<Layer>& relative = relativeWeak.promote();
2839 if (clonedLayersMap.count(relative) > 0) {
2840 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002841 mDrawingState.zOrderRelatives.add(clonedRelative);
2842 }
2843 }
2844
2845 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2846 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2847 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2848 // still traverse the children, but the layer with the missing relativeOf will not be shown
2849 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002850 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2851 if (clonedLayersMap.count(relativeOf) > 0) {
2852 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002853 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2854 }
2855
chaviwaf87b3e2019-10-01 16:59:28 -07002856 updateClonedInputInfo(clonedLayersMap);
2857
chaviw74b03172019-08-19 11:09:03 -07002858 for (sp<Layer>& child : mDrawingChildren) {
2859 child->updateClonedRelatives(clonedLayersMap);
2860 }
2861}
2862
2863void Layer::addChildToDrawing(const sp<Layer>& layer) {
2864 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002865 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002866}
2867
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002868bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002869 const State& s(mDrawingState);
2870 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2871 return true;
2872 }
2873
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002874 sp<Layer> parent = mDrawingParent.promote();
2875 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002876}
2877
Robert Carr6a0382d2021-07-01 15:57:17 -07002878void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2879 mClonedChild = clonedChild;
2880 mHadClonedChild = true;
Vishnu Nair3be61902023-04-26 19:47:29 -07002881 mFlinger->mLayerMirrorRoots.push_back(this);
Robert Carr6a0382d2021-07-01 15:57:17 -07002882}
2883
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002884bool Layer::setDropInputMode(gui::DropInputMode mode) {
2885 if (mDrawingState.dropInputMode == mode) {
2886 return false;
2887 }
2888 mDrawingState.dropInputMode = mode;
2889 return true;
2890}
2891
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002892void Layer::cloneDrawingState(const Layer* from) {
2893 mDrawingState = from->mDrawingState;
2894 // Skip callback info since they are not applicable for cloned layers.
2895 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002896 // TODO (b/238781169) currently broken for mirror layers because we do not
2897 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002898 mDrawingState.callbackHandles = {};
2899}
2900
Patrick Williamsbb25f802022-08-30 23:02:34 +00002901void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2902 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002903 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002904 if (!listener) {
2905 return;
2906 }
2907 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002908 uint32_t currentMaxAcquiredBufferCount =
2909 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002910 listener->onReleaseBuffer({buffer->getId(), framenumber},
2911 releaseFence ? releaseFence : Fence::NO_FENCE,
2912 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002913}
2914
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002915void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
Alec Mouri9892aac2023-12-11 21:16:59 +00002916 ui::LayerStack layerStack,
2917 std::function<FenceResult(FenceResult)>&& continuation) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002918 // If we are displayed on multiple displays in a single composition cycle then we would
2919 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2920 // For example we can only use it if all the displays are client comp, and we need
2921 // to merge all the client comp fences. We could do this, but for now we just
2922 // disable the optimization when a layer is composed on multiple displays.
2923 if (mClearClientCompositionFenceOnLayerDisplayed) {
2924 mLastClientCompositionFence = nullptr;
2925 } else {
2926 mClearClientCompositionFenceOnLayerDisplayed = true;
2927 }
2928
2929 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2930 // buffer that was presented on this layer. The first transaction that came in this frame that
2931 // replaced the previous buffer on this layer needs this release fence, because the fence will
2932 // let the client know when that previous buffer is removed from the screen.
2933 //
2934 // Every other transaction on this layer does not need a release fence because no other
2935 // Transactions that were set on this layer this frame are going to have their preceding buffer
2936 // removed from the display this frame.
2937 //
2938 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2939 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2940 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2941 // the previous buffer will be released this frame. The third transaction also contains a
2942 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2943 // transaction will now no longer be presented so it is released immediately and the third
2944 // transaction doesn't need a previous release fence.
2945 sp<CallbackHandle> ch;
2946 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002947 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002948 ch = handle;
2949 break;
2950 }
2951 }
Alec Mouri9892aac2023-12-11 21:16:59 +00002952
2953 if (!FlagManager::getInstance().screenshot_fence_preservation() && continuation) {
2954 futureFenceResult = ftl::Future(futureFenceResult).then(std::move(continuation)).share();
2955 }
2956
Patrick Williamsbb25f802022-08-30 23:02:34 +00002957 if (ch != nullptr) {
2958 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2959 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2960 ch->name = mName;
Alec Mouri9892aac2023-12-11 21:16:59 +00002961 } else if (FlagManager::getInstance().screenshot_fence_preservation()) {
2962 // If we didn't get a release callback yet, e.g. some scenarios when capturing screenshots
2963 // asynchronously, then make sure we don't drop the fence.
2964 mAdditionalPreviousReleaseFences.emplace_back(std::move(futureFenceResult),
2965 std::move(continuation));
2966 std::vector<FenceAndContinuation> mergedFences;
2967 sp<Fence> prevFence = nullptr;
2968 // For a layer that's frequently screenshotted, try to merge fences to make sure we don't
2969 // grow unbounded.
2970 for (const auto& futureAndContinution : mAdditionalPreviousReleaseFences) {
2971 auto result = futureAndContinution.future.wait_for(0s);
2972 if (result != std::future_status::ready) {
2973 mergedFences.emplace_back(futureAndContinution);
2974 continue;
2975 }
2976
2977 mergeFence(getDebugName(), futureAndContinution.chain().get().value_or(Fence::NO_FENCE),
2978 prevFence);
2979 }
2980 if (prevFence != nullptr) {
2981 mergedFences.emplace_back(ftl::yield(FenceResult(std::move(prevFence))).share());
2982 }
2983
2984 mAdditionalPreviousReleaseFences.swap(mergedFences);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002985 }
Alec Mouri9892aac2023-12-11 21:16:59 +00002986
Vishnu Nair316b7f42023-10-13 23:44:46 +00002987 if (mBufferInfo.mBuffer) {
2988 mPreviouslyPresentedLayerStacks.push_back(layerStack);
2989 }
Alec Mouri21d94322023-10-17 19:51:39 +00002990
2991 if (mDrawingState.frameNumber > 0) {
2992 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
2993 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002994}
2995
2996void Layer::onSurfaceFrameCreated(
2997 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2998 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2999 // Too many SurfaceFrames pending classification. The front of the deque is probably not
3000 // tracked by FrameTimeline and will never be presented. This will only result in a memory
3001 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01003002 if (hasBufferOrSidebandStreamInDrawing()) {
3003 // Only log for layers with a buffer, since we expect the jank data to be drained for
3004 // these, while there may be no jank listeners for bufferless layers.
3005 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
3006 mName.c_str());
3007 std::string miniDump = mPendingJankClassifications.front()->miniDump();
3008 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
3009 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003010 mPendingJankClassifications.pop_front();
3011 }
3012 mPendingJankClassifications.emplace_back(surfaceFrame);
3013}
3014
3015void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
3016 for (const auto& handle : mDrawingState.callbackHandles) {
Lloyd Pique30db6402023-06-26 18:56:51 +00003017 if (mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -07003018 handle->transformHint = mTransformHint;
3019 } else {
3020 handle->transformHint = mSkipReportingTransformHint
3021 ? std::nullopt
3022 : std::make_optional<uint32_t>(mTransformHintLegacy);
3023 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003024 handle->dequeueReadyTime = dequeueReadyTime;
3025 handle->currentMaxAcquiredBufferCount =
3026 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
3027 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
3028 handle->previousReleaseCallbackId.framenumber);
3029 }
3030
3031 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003032 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003033 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
3034 break;
3035 }
3036 }
3037
3038 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01003039 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003040 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
3041 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003042 mDrawingState.callbackHandles = {};
3043}
3044
3045bool Layer::willPresentCurrentTransaction() const {
3046 // Returns true if the most recent Transaction applied to CurrentState will be presented.
3047 return (getSidebandStreamChanged() || getAutoRefresh() ||
3048 (mDrawingState.modified &&
3049 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
3050}
3051
3052bool Layer::setTransform(uint32_t transform) {
3053 if (mDrawingState.bufferTransform == transform) return false;
3054 mDrawingState.bufferTransform = transform;
3055 mDrawingState.modified = true;
3056 setTransactionFlags(eTransactionNeeded);
3057 return true;
3058}
3059
3060bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
3061 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
3062 mDrawingState.sequence++;
3063 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
3064 mDrawingState.modified = true;
3065 setTransactionFlags(eTransactionNeeded);
3066 return true;
3067}
3068
3069bool Layer::setBufferCrop(const Rect& bufferCrop) {
3070 if (mDrawingState.bufferCrop == bufferCrop) return false;
3071
3072 mDrawingState.sequence++;
3073 mDrawingState.bufferCrop = bufferCrop;
3074
3075 mDrawingState.modified = true;
3076 setTransactionFlags(eTransactionNeeded);
3077 return true;
3078}
3079
3080bool Layer::setDestinationFrame(const Rect& destinationFrame) {
3081 if (mDrawingState.destinationFrame == destinationFrame) return false;
3082
3083 mDrawingState.sequence++;
3084 mDrawingState.destinationFrame = destinationFrame;
3085
3086 mDrawingState.modified = true;
3087 setTransactionFlags(eTransactionNeeded);
3088 return true;
3089}
3090
3091// Translate destination frame into scale and position. If a destination frame is not set, use the
3092// provided scale and position
3093bool Layer::updateGeometry() {
3094 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
3095 mDrawingState.destinationFrame.isEmpty()) {
3096 // If destination frame is not set, use the requested transform set via
3097 // Layer::setPosition and Layer::setMatrix.
3098 return assignTransform(&mDrawingState.transform, mRequestedTransform);
3099 }
3100
3101 Rect destRect = mDrawingState.destinationFrame;
3102 int32_t destW = destRect.width();
3103 int32_t destH = destRect.height();
3104 if (destRect.left < 0) {
3105 destRect.left = 0;
3106 destRect.right = destW;
3107 }
3108 if (destRect.top < 0) {
3109 destRect.top = 0;
3110 destRect.bottom = destH;
3111 }
3112
3113 if (!mDrawingState.buffer) {
3114 ui::Transform t;
3115 t.set(destRect.left, destRect.top);
3116 return assignTransform(&mDrawingState.transform, t);
3117 }
3118
3119 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3120 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3121 // Undo any transformations on the buffer.
3122 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3123 std::swap(bufferWidth, bufferHeight);
3124 }
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003125 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003126 if (mDrawingState.transformToDisplayInverse) {
3127 if (invTransform & ui::Transform::ROT_90) {
3128 std::swap(bufferWidth, bufferHeight);
3129 }
3130 }
3131
3132 float sx = destW / static_cast<float>(bufferWidth);
3133 float sy = destH / static_cast<float>(bufferHeight);
3134 ui::Transform t;
3135 t.set(sx, 0, 0, sy);
3136 t.set(destRect.left, destRect.top);
3137 return assignTransform(&mDrawingState.transform, t);
3138}
3139
3140bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3141 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3142 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3143 return false;
3144 }
3145
3146 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3147
3148 mDrawingState.sequence++;
3149 mDrawingState.modified = true;
3150 setTransactionFlags(eTransactionNeeded);
3151
3152 return true;
3153}
3154
3155bool Layer::setPosition(float x, float y) {
3156 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3157 return false;
3158 }
3159
3160 mRequestedTransform.set(x, y);
3161
3162 mDrawingState.sequence++;
3163 mDrawingState.modified = true;
3164 setTransactionFlags(eTransactionNeeded);
3165
3166 return true;
3167}
3168
Dorin Drimuse5374e52023-08-02 17:52:43 +00003169void Layer::releasePreviousBuffer() {
3170 mReleasePreviousBuffer = true;
3171 if (!mBufferInfo.mBuffer ||
3172 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3173 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3174 // If mDrawingState has a buffer, and we are about to update again
3175 // before swapping to drawing state, then the first buffer will be
3176 // dropped and we should decrement the pending buffer count and
3177 // call any release buffer callbacks if set.
3178 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3179 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3180 mDrawingState.acquireFence);
3181 decrementPendingBufferCount();
3182 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3183 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3184 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX, systemTime());
3185 mDrawingState.bufferSurfaceFrameTX.reset();
3186 }
3187 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3188 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3189 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3190 mLastClientCompositionFence);
3191 mLastClientCompositionFence = nullptr;
3192 }
3193}
3194
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003195void Layer::resetDrawingStateBufferInfo() {
3196 mDrawingState.producerId = 0;
3197 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +00003198 mDrawingState.previousFrameNumber = 0;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003199 mDrawingState.releaseBufferListener = nullptr;
3200 mDrawingState.buffer = nullptr;
3201 mDrawingState.acquireFence = sp<Fence>::make(-1);
3202 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3203 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3204 mDrawingState.releaseBufferEndpoint = nullptr;
3205}
3206
Patrick Williamsbb25f802022-08-30 23:02:34 +00003207bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3208 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3209 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003210 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003211 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003212
3213 const bool frameNumberChanged =
3214 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3215 const uint64_t frameNumber =
3216 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003217 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003218
3219 if (mDrawingState.buffer) {
Dorin Drimuse5374e52023-08-02 17:52:43 +00003220 releasePreviousBuffer();
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003221 } else if (buffer) {
Vishnu Nairc09c0232023-03-02 03:22:35 +00003222 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3223 // we don't want to incorrectly classify a frame if we miss the desired present time.
3224 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003225 }
3226
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003227 mDrawingState.desiredPresentTime = desiredPresentTime;
3228 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3229 mDrawingState.latchedVsyncId = info.vsyncId;
Ady Abraham55269162023-05-09 11:26:06 -07003230 mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003231 mDrawingState.modified = true;
3232 if (!buffer) {
3233 resetDrawingStateBufferInfo();
3234 setTransactionFlags(eTransactionNeeded);
3235 mDrawingState.bufferSurfaceFrameTX = nullptr;
3236 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3237 return true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003238 } else {
3239 // release sideband stream if it exists and a non null buffer is being set
3240 if (mDrawingState.sidebandStream != nullptr) {
Dorin Drimus66ed1c42023-09-27 13:10:16 +00003241 setSidebandStream(nullptr, info, postTime);
Dorin Drimuse5374e52023-08-02 17:52:43 +00003242 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003243 }
3244
Vishnu Naird1f74982023-06-15 20:16:51 -07003245 if ((mDrawingState.producerId > bufferData.producerId) ||
3246 ((mDrawingState.producerId == bufferData.producerId) &&
3247 (mDrawingState.frameNumber > frameNumber))) {
3248 ALOGE("Out of order buffers detected for %s producedId=%d frameNumber=%" PRIu64
3249 " -> producedId=%d frameNumber=%" PRIu64,
3250 getDebugName(), mDrawingState.producerId, mDrawingState.frameNumber,
3251 bufferData.producerId, frameNumber);
3252 TransactionTraceWriter::getInstance().invoke("out_of_order_buffers_", /*overwrite=*/false);
3253 }
3254
liulijuneb489f62022-10-17 22:02:14 +08003255 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -07003256 mDrawingState.barrierProducerId =
3257 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003258 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -07003259 mDrawingState.barrierFrameNumber =
3260 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
3261
Patrick Williamsbb25f802022-08-30 23:02:34 +00003262 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3263 mDrawingState.buffer = std::move(buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003264 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3265 ? bufferData.acquireFence
3266 : Fence::NO_FENCE;
3267 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3268 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3269 // We latched this buffer unsiganled, so we need to pass the acquire fence
3270 // on the callback instead of just the acquire time, since it's unknown at
3271 // this point.
3272 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3273 } else {
3274 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3275 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003276 setTransactionFlags(eTransactionNeeded);
3277
3278 const int32_t layerId = getSequence();
3279 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3280 mOwnerUid, postTime, getGameMode());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003281
Lloyd Pique30db6402023-06-26 18:56:51 +00003282 if (mFlinger->mLegacyFrontEndEnabled) {
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003283 recordLayerHistoryBufferUpdate(getLayerProps(), systemTime());
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003284 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003285
3286 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3287
3288 if (dequeueTime && *dequeueTime != 0) {
3289 const uint64_t bufferId = mDrawingState.buffer->getId();
3290 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3291 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3292 FrameTracer::FrameEvent::DEQUEUE);
3293 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3294 FrameTracer::FrameEvent::QUEUE);
3295 }
3296
3297 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
Arthur Hungc70bee22023-06-02 01:35:52 +00003298
3299 // If the layer had been updated a TextureView, this would make sure the present time could be
3300 // same to TextureView update when it's a small dirty, and get the correct heuristic rate.
Jerry Chang36678002023-11-29 16:56:17 +00003301 if (mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00003302 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3303 mUsedVsyncIdForRefreshRateSelection = true;
3304 }
3305 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003306 return true;
3307}
3308
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003309void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3310 mDrawingState.desiredPresentTime = desiredPresentTime;
3311 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3312}
3313
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003314void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps, nsecs_t now) {
Ady Abraham55269162023-05-09 11:26:06 -07003315 ATRACE_CALL();
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003316 const nsecs_t presentTime = [&] {
Ady Abraham55269162023-05-09 11:26:06 -07003317 if (!mDrawingState.isAutoTimestamp) {
3318 ATRACE_FORMAT_INSTANT("desiredPresentTime");
3319 return mDrawingState.desiredPresentTime;
3320 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003321
Ady Abraham55269162023-05-09 11:26:06 -07003322 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3323 const auto prediction =
3324 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3325 mDrawingState.latchedVsyncId);
3326 if (prediction.has_value()) {
3327 ATRACE_FORMAT_INSTANT("predictedPresentTime");
Arthur Hungc70bee22023-06-02 01:35:52 +00003328 mMaxTimeForUseVsyncId = prediction->presentTime +
3329 scheduler::LayerHistory::kMaxPeriodForHistory.count();
Ady Abraham55269162023-05-09 11:26:06 -07003330 return prediction->presentTime;
3331 }
3332 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003333
Jerry Chang36678002023-11-29 16:56:17 +00003334 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00003335 return static_cast<nsecs_t>(0);
3336 }
3337
3338 // If the layer is not an application and didn't set an explicit rate or desiredPresentTime,
3339 // return "0" to tell the layer history that it will use the max refresh rate without
3340 // calculating the adaptive rate.
3341 if (mWindowType != WindowInfo::Type::APPLICATION &&
3342 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
3343 return static_cast<nsecs_t>(0);
3344 }
3345
3346 // Return the valid present time only when the layer potentially updated a TextureView so
3347 // LayerHistory could heuristically calculate the rate if the UI is continually updating.
3348 if (mUsedVsyncIdForRefreshRateSelection) {
3349 const auto prediction =
3350 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3351 mDrawingState.latchedVsyncId);
3352 if (prediction.has_value()) {
3353 if (mMaxTimeForUseVsyncId >= prediction->presentTime) {
3354 return prediction->presentTime;
3355 }
3356 mUsedVsyncIdForRefreshRateSelection = false;
3357 }
3358 }
3359
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003360 return static_cast<nsecs_t>(0);
3361 }();
Ady Abraham55269162023-05-09 11:26:06 -07003362
3363 if (ATRACE_ENABLED() && presentTime > 0) {
3364 const auto presentIn = TimePoint::fromNs(presentTime) - TimePoint::now();
3365 ATRACE_FORMAT_INSTANT("presentIn %s", to_string(presentIn).c_str());
3366 }
3367
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003368 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003369 scheduler::LayerHistory::LayerUpdateType::Buffer);
3370}
3371
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003372void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps, nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003373 const nsecs_t presentTime =
3374 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003375 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003376 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3377}
3378
Patrick Williamsbb25f802022-08-30 23:02:34 +00003379bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003380 if (mDrawingState.dataspace == dataspace) return false;
3381 mDrawingState.dataspace = dataspace;
3382 mDrawingState.modified = true;
3383 setTransactionFlags(eTransactionNeeded);
3384 return true;
3385}
3386
John Reck68796592023-01-25 13:47:12 -05003387bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07003388 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3389 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05003390 return false;
Sally Qi963049b2023-03-23 14:06:21 -07003391 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3392 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05003393 mDrawingState.modified = true;
3394 setTransactionFlags(eTransactionNeeded);
3395 return true;
3396}
3397
Alec Mouri1b0d4e12024-02-12 22:27:19 +00003398bool Layer::setDesiredHdrHeadroom(float desiredRatio) {
3399 if (mDrawingState.desiredHdrSdrRatio == desiredRatio) return false;
3400 mDrawingState.desiredHdrSdrRatio = desiredRatio;
3401 mDrawingState.modified = true;
3402 setTransactionFlags(eTransactionNeeded);
3403 return true;
3404}
3405
Alec Mourif4af03e2023-02-11 00:25:24 +00003406bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3407 if (mDrawingState.cachingHint == cachingHint) return false;
3408 mDrawingState.cachingHint = cachingHint;
3409 mDrawingState.modified = true;
3410 setTransactionFlags(eTransactionNeeded);
3411 return true;
3412}
3413
Patrick Williamsbb25f802022-08-30 23:02:34 +00003414bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3415 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3416 mDrawingState.hdrMetadata = hdrMetadata;
3417 mDrawingState.modified = true;
3418 setTransactionFlags(eTransactionNeeded);
3419 return true;
3420}
3421
3422bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003423 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003424 mDrawingState.surfaceDamageRegion = surfaceDamage;
3425 mDrawingState.modified = true;
3426 setTransactionFlags(eTransactionNeeded);
Arthur Hung69f95222023-10-04 07:39:02 +00003427 setIsSmallDirty(surfaceDamage, getTransform());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003428 return true;
3429}
3430
3431bool Layer::setApi(int32_t api) {
3432 if (mDrawingState.api == api) return false;
3433 mDrawingState.api = api;
3434 mDrawingState.modified = true;
3435 setTransactionFlags(eTransactionNeeded);
3436 return true;
3437}
3438
Dorin Drimuse5374e52023-08-02 17:52:43 +00003439bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream, const FrameTimelineInfo& info,
3440 nsecs_t postTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003441 if (mDrawingState.sidebandStream == sidebandStream) return false;
3442
3443 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3444 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3445 } else if (sidebandStream != nullptr) {
3446 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3447 }
3448
3449 mDrawingState.sidebandStream = sidebandStream;
3450 mDrawingState.modified = true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003451 if (sidebandStream != nullptr && mDrawingState.buffer != nullptr) {
3452 releasePreviousBuffer();
3453 resetDrawingStateBufferInfo();
3454 mDrawingState.bufferSurfaceFrameTX = nullptr;
3455 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3456 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003457 setTransactionFlags(eTransactionNeeded);
3458 if (!mSidebandStreamChanged.exchange(true)) {
3459 // mSidebandStreamChanged was false
3460 mFlinger->onLayerUpdate();
3461 }
3462 return true;
3463}
3464
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003465bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3466 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003467 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3468 if (handles.empty()) {
3469 mReleasePreviousBuffer = false;
3470 return false;
3471 }
3472
Pascal Muetschard81cef292023-02-06 12:18:52 +01003473 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003474 for (const auto& handle : handles) {
3475 // If this transaction set a buffer on this layer, release its previous buffer
3476 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3477
3478 // If this layer will be presented in this frame
3479 if (willPresent) {
3480 // If this transaction set an acquire fence on this layer, set its acquire time
3481 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3482 handle->frameNumber = mDrawingState.frameNumber;
Alec Mouri21d94322023-10-17 19:51:39 +00003483 handle->previousFrameNumber = mDrawingState.previousFrameNumber;
Alec Mouri9892aac2023-12-11 21:16:59 +00003484 if (FlagManager::getInstance().screenshot_fence_preservation() &&
3485 mPreviousReleaseBufferEndpoint == handle->listener) {
3486 // Add fences from previous screenshots now so that they can be dispatched to the
3487 // client.
3488 for (const auto& futureAndContinution : mAdditionalPreviousReleaseFences) {
3489 handle->previousReleaseFences.emplace_back(futureAndContinution.chain());
3490 }
3491 mAdditionalPreviousReleaseFences.clear();
3492 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003493
3494 // Store so latched time and release fence can be set
3495 mDrawingState.callbackHandles.push_back(handle);
3496
3497 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003498 // Queue this handle to be notified below.
3499 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003500 }
3501 }
3502
Pascal Muetschard81cef292023-02-06 12:18:52 +01003503 if (!remainingHandles.empty()) {
3504 // Notify the transaction completed threads these handles are done. These are only the
3505 // handles that were not added to the mDrawingState, which will be notified later.
3506 std::vector<JankData> jankData;
3507 transferAvailableJankData(remainingHandles, jankData);
3508 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3509 }
3510
Patrick Williamsbb25f802022-08-30 23:02:34 +00003511 mReleasePreviousBuffer = false;
3512 mCallbackHandleAcquireTimeOrFence = -1;
3513
3514 return willPresent;
3515}
3516
3517Rect Layer::getBufferSize(const State& /*s*/) const {
3518 // for buffer state layers we use the display frame size as the buffer size.
3519
3520 if (mBufferInfo.mBuffer == nullptr) {
3521 return Rect::INVALID_RECT;
3522 }
3523
3524 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3525 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3526
3527 // Undo any transformations on the buffer and return the result.
3528 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3529 std::swap(bufWidth, bufHeight);
3530 }
3531
3532 if (getTransformToDisplayInverse()) {
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003533 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003534 if (invTransform & ui::Transform::ROT_90) {
3535 std::swap(bufWidth, bufHeight);
3536 }
3537 }
3538
3539 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3540}
3541
3542FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3543 if (mBufferInfo.mBuffer == nullptr) {
3544 return parentBounds;
3545 }
3546
3547 return getBufferSize(getDrawingState()).toFloatRect();
3548}
3549
3550bool Layer::fenceHasSignaled() const {
3551 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3552 return true;
3553 }
3554
3555 const bool fenceSignaled =
3556 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3557 if (!fenceSignaled) {
3558 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3559 TimeStats::LatchSkipReason::LateAcquire);
3560 }
3561
3562 return fenceSignaled;
3563}
3564
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003565void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003566 for (const auto& handle : mDrawingState.callbackHandles) {
3567 handle->refreshStartTime = refreshStartTime;
3568 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003569}
3570
3571void Layer::setAutoRefresh(bool autoRefresh) {
3572 mDrawingState.autoRefresh = autoRefresh;
3573}
3574
3575bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3576 // 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 +00003577 auto* snapshot = editLayerSnapshot();
3578 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003579
3580 if (mSidebandStreamChanged.exchange(false)) {
3581 const State& s(getDrawingState());
3582 // mSidebandStreamChanged was true
3583 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003584 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003585 if (mSidebandStream != nullptr) {
3586 setTransactionFlags(eTransactionNeeded);
3587 mFlinger->setTransactionFlags(eTraversalNeeded);
3588 }
3589 recomputeVisibleRegions = true;
3590
3591 return true;
3592 }
3593 return false;
3594}
3595
3596bool Layer::hasFrameUpdate() const {
3597 const State& c(getDrawingState());
3598 return (mDrawingStateModified || mDrawingState.modified) &&
3599 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3600}
3601
Vishnu Naird47bcee2023-02-24 18:08:51 +00003602void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003603 const State& s(getDrawingState());
3604
3605 if (!s.buffer) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003606 if (bgColorOnly || mBufferInfo.mBuffer) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003607 for (auto& handle : mDrawingState.callbackHandles) {
3608 handle->latchTime = latchTime;
3609 }
3610 }
3611 return;
3612 }
3613
3614 for (auto& handle : mDrawingState.callbackHandles) {
3615 if (handle->frameNumber == mDrawingState.frameNumber) {
3616 handle->latchTime = latchTime;
3617 }
3618 }
3619
3620 const int32_t layerId = getSequence();
3621 const uint64_t bufferId = mDrawingState.buffer->getId();
3622 const uint64_t frameNumber = mDrawingState.frameNumber;
3623 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3624 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3625 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3626
3627 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3628 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3629 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3630 FrameTracer::FrameEvent::LATCH);
3631
3632 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3633 if (bufferSurfaceFrame != nullptr &&
3634 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3635 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3636 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3637 // are processing the next state.
3638 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3639 mDrawingState.acquireFenceTime->getSignalTime(),
3640 latchTime);
3641 mDrawingState.bufferSurfaceFrameTX.reset();
3642 }
3643
3644 std::deque<sp<CallbackHandle>> remainingHandles;
3645 mFlinger->getTransactionCallbackInvoker()
3646 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3647 mDrawingState.callbackHandles = remainingHandles;
3648
3649 mDrawingStateModified = false;
3650}
3651
3652void Layer::gatherBufferInfo() {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003653 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3654 mPreviousReleaseBufferEndpoint = mBufferInfo.mReleaseBufferEndpoint;
3655 if (!mDrawingState.buffer) {
3656 mBufferInfo = {};
3657 return;
3658 }
3659
3660 if ((!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer))) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003661 decrementPendingBufferCount();
3662 }
3663
Patrick Williamsbb25f802022-08-30 23:02:34 +00003664 mBufferInfo.mBuffer = mDrawingState.buffer;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003665 mBufferInfo.mReleaseBufferEndpoint = mDrawingState.releaseBufferEndpoint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003666 mBufferInfo.mFence = mDrawingState.acquireFence;
3667 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3668 mBufferInfo.mPixelFormat =
3669 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3670 mBufferInfo.mFrameLatencyNeeded = true;
3671 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3672 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3673 mBufferInfo.mFence = mDrawingState.acquireFence;
3674 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3675 auto lastDataspace = mBufferInfo.mDataspace;
3676 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003677 if (mBufferInfo.mBuffer != nullptr) {
3678 auto& mapper = GraphicBufferMapper::get();
3679 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
3680 // and don't need to possibly remaps buffers.
3681 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
3682 status_t err = OK;
3683 {
3684 ATRACE_NAME("getDataspace");
3685 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
3686 }
3687 if (err != OK || dataspace != mBufferInfo.mDataspace) {
3688 {
3689 ATRACE_NAME("setDataspace");
3690 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
3691 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
3692 }
3693
3694 // Some GPU drivers may cache gralloc metadata which means before we composite we need
3695 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
3696 // compatible with old vendors, with a ticking clock.
3697 static const int32_t kVendorVersion =
Alec Mouri8a06fb72023-11-16 22:07:13 +00003698 base::GetIntProperty("ro.board.api_level", __ANDROID_API_FUTURE__);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003699 if (const auto format =
3700 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
3701 mBufferInfo.mBuffer->getPixelFormat());
3702 err == OK && kVendorVersion < __ANDROID_API_U__ &&
3703 (format ==
3704 aidl::android::hardware::graphics::common::PixelFormat::
3705 IMPLEMENTATION_DEFINED ||
3706 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
3707 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
3708 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
3709 mBufferInfo.mBuffer->remapBuffer();
3710 }
3711 }
3712 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003713 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003714 mFlinger->mHdrLayerInfoChanged = true;
3715 }
Sally Qi963049b2023-03-23 14:06:21 -07003716 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3717 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05003718 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003719 }
3720 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3721 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3722 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3723 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3724 mBufferInfo.mApi = mDrawingState.api;
3725 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003726}
3727
3728Rect Layer::computeBufferCrop(const State& s) {
3729 if (s.buffer && !s.bufferCrop.isEmpty()) {
3730 Rect bufferCrop;
3731 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3732 return bufferCrop;
3733 } else if (s.buffer) {
3734 return s.buffer->getBounds();
3735 } else {
3736 return s.bufferCrop;
3737 }
3738}
3739
Vishnu Nairde177252023-04-21 12:44:10 -07003740sp<Layer> Layer::createClone(uint32_t mirrorRootId) {
Kean Mariotti4ba343c2023-04-19 13:31:02 +00003741 surfaceflinger::LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0,
3742 LayerMetadata());
Patrick Williams83f36b22022-09-14 17:57:35 +00003743 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Vishnu Nairde177252023-04-21 12:44:10 -07003744 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this), mirrorRootId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003745 return layer;
3746}
3747
Patrick Williamsbb25f802022-08-30 23:02:34 +00003748void Layer::decrementPendingBufferCount() {
3749 int32_t pendingBuffers = --mPendingBufferTransactions;
3750 tracePendingBufferCount(pendingBuffers);
3751}
3752
3753void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3754 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3755}
3756
3757/*
3758 * We don't want to send the layer's transform to input, but rather the
3759 * parent's transform. This is because Layer's transform is
3760 * information about how the buffer is placed on screen. The parent's
3761 * transform makes more sense to send since it's information about how the
3762 * layer is placed on screen. This transform is used by input to determine
3763 * how to go from screen space back to window space.
3764 */
3765ui::Transform Layer::getInputTransform() const {
3766 if (!hasBufferOrSidebandStream()) {
3767 return getTransform();
3768 }
3769 sp<Layer> parent = mDrawingParent.promote();
3770 if (parent == nullptr) {
3771 return ui::Transform();
3772 }
3773
3774 return parent->getTransform();
3775}
3776
3777/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003778 * Returns the bounds used to fill the input frame and the touchable region.
3779 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003780 * Similar to getInputTransform, we need to update the bounds to include the transform.
3781 * This is because bounds don't include the buffer transform, where the input assumes
3782 * that's already included.
3783 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003784std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3785 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3786 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3787 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3788 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3789 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003790 }
3791
Vishnu Nairfed7c122023-03-18 01:54:43 +00003792 bool inputBoundsValid = croppedBufferSize.isValid();
3793 if (!inputBoundsValid) {
3794 /**
3795 * Input bounds are based on the layer crop or buffer size. But if we are using
3796 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3797 * we can use the parent bounds as the input bounds if the layer does not have buffer
3798 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3799 * use the parent bounds. A layer without a buffer can get input. So when a window is
3800 * initially added, its touchable region can fill its parent layer bounds and that can
3801 * have negative consequences.
3802 */
3803 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003804 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003805
3806 // Clamp surface inset to the input bounds.
3807 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3808 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3809 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3810
3811 // Apply the insets to the input bounds.
3812 inputBounds.left += xSurfaceInset;
3813 inputBounds.top += ySurfaceInset;
3814 inputBounds.right -= xSurfaceInset;
3815 inputBounds.bottom -= ySurfaceInset;
3816
3817 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003818}
3819
Ady Abraham005398b2023-06-05 13:59:41 -07003820bool Layer::isSimpleBufferUpdate(const layer_state_t& s) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003821 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3822
3823 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3824 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3825 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3826 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3827 layer_state_t::eReparent;
3828
Patrick Williamsbb25f802022-08-30 23:02:34 +00003829 if ((s.what & requiredFlags) != requiredFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003830 ATRACE_FORMAT_INSTANT("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3831 (s.what | requiredFlags) & ~s.what);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003832 return false;
3833 }
3834
3835 if (s.what & deniedFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003836 ATRACE_FORMAT_INSTANT("%s: false [has denied flags 0x%" PRIx64 "]", __func__,
3837 s.what & deniedFlags);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003838 return false;
3839 }
3840
Patrick Williamsbb25f802022-08-30 23:02:34 +00003841 if (s.what & layer_state_t::ePositionChanged) {
3842 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
Ady Abraham005398b2023-06-05 13:59:41 -07003843 ATRACE_FORMAT_INSTANT("%s: false [ePositionChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003844 return false;
3845 }
3846 }
3847
3848 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003849 if (mDrawingState.color.a != s.color.a) {
Ady Abraham005398b2023-06-05 13:59:41 -07003850 ATRACE_FORMAT_INSTANT("%s: false [eAlphaChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003851 return false;
3852 }
3853 }
3854
3855 if (s.what & layer_state_t::eColorTransformChanged) {
3856 if (mDrawingState.colorTransform != s.colorTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003857 ATRACE_FORMAT_INSTANT("%s: false [eColorTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003858 return false;
3859 }
3860 }
3861
3862 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003863 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Ady Abraham005398b2023-06-05 13:59:41 -07003864 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundColorChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003865 return false;
3866 }
3867 }
3868
3869 if (s.what & layer_state_t::eMatrixChanged) {
3870 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3871 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3872 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3873 mRequestedTransform.dsdy() != s.matrix.dsdy) {
Ady Abraham005398b2023-06-05 13:59:41 -07003874 ATRACE_FORMAT_INSTANT("%s: false [eMatrixChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003875 return false;
3876 }
3877 }
3878
3879 if (s.what & layer_state_t::eCornerRadiusChanged) {
3880 if (mDrawingState.cornerRadius != s.cornerRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003881 ATRACE_FORMAT_INSTANT("%s: false [eCornerRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003882 return false;
3883 }
3884 }
3885
3886 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3887 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
Ady Abraham005398b2023-06-05 13:59:41 -07003888 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003889 return false;
3890 }
3891 }
3892
Vishnu Nairbbceb462022-10-10 04:52:13 +00003893 if (s.what & layer_state_t::eBufferTransformChanged) {
3894 if (mDrawingState.bufferTransform != s.bufferTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003895 ATRACE_FORMAT_INSTANT("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003896 return false;
3897 }
3898 }
3899
3900 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3901 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
Ady Abraham005398b2023-06-05 13:59:41 -07003902 ATRACE_FORMAT_INSTANT("%s: false [eTransformToDisplayInverseChanged changed]",
3903 __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003904 return false;
3905 }
3906 }
3907
3908 if (s.what & layer_state_t::eCropChanged) {
3909 if (mDrawingState.crop != s.crop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003910 ATRACE_FORMAT_INSTANT("%s: false [eCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003911 return false;
3912 }
3913 }
3914
3915 if (s.what & layer_state_t::eDataspaceChanged) {
3916 if (mDrawingState.dataspace != s.dataspace) {
Ady Abraham005398b2023-06-05 13:59:41 -07003917 ATRACE_FORMAT_INSTANT("%s: false [eDataspaceChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003918 return false;
3919 }
3920 }
3921
3922 if (s.what & layer_state_t::eHdrMetadataChanged) {
3923 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
Ady Abraham005398b2023-06-05 13:59:41 -07003924 ATRACE_FORMAT_INSTANT("%s: false [eHdrMetadataChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003925 return false;
3926 }
3927 }
3928
3929 if (s.what & layer_state_t::eSidebandStreamChanged) {
3930 if (mDrawingState.sidebandStream != s.sidebandStream) {
Ady Abraham005398b2023-06-05 13:59:41 -07003931 ATRACE_FORMAT_INSTANT("%s: false [eSidebandStreamChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003932 return false;
3933 }
3934 }
3935
3936 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3937 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
Ady Abraham005398b2023-06-05 13:59:41 -07003938 ATRACE_FORMAT_INSTANT("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003939 return false;
3940 }
3941 }
3942
3943 if (s.what & layer_state_t::eShadowRadiusChanged) {
3944 if (mDrawingState.shadowRadius != s.shadowRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003945 ATRACE_FORMAT_INSTANT("%s: false [eShadowRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003946 return false;
3947 }
3948 }
3949
3950 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3951 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
Ady Abraham005398b2023-06-05 13:59:41 -07003952 ATRACE_FORMAT_INSTANT("%s: false [eFixedTransformHintChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003953 return false;
3954 }
3955 }
3956
3957 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3958 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
Ady Abraham005398b2023-06-05 13:59:41 -07003959 ATRACE_FORMAT_INSTANT("%s: false [eTrustedOverlayChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003960 return false;
3961 }
3962 }
3963
3964 if (s.what & layer_state_t::eStretchChanged) {
3965 StretchEffect temp = s.stretchEffect;
3966 temp.sanitize();
3967 if (mDrawingState.stretchEffect != temp) {
Ady Abraham005398b2023-06-05 13:59:41 -07003968 ATRACE_FORMAT_INSTANT("%s: false [eStretchChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003969 return false;
3970 }
3971 }
3972
3973 if (s.what & layer_state_t::eBufferCropChanged) {
3974 if (mDrawingState.bufferCrop != s.bufferCrop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003975 ATRACE_FORMAT_INSTANT("%s: false [eBufferCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003976 return false;
3977 }
3978 }
3979
3980 if (s.what & layer_state_t::eDestinationFrameChanged) {
3981 if (mDrawingState.destinationFrame != s.destinationFrame) {
Ady Abraham005398b2023-06-05 13:59:41 -07003982 ATRACE_FORMAT_INSTANT("%s: false [eDestinationFrameChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003983 return false;
3984 }
3985 }
3986
3987 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3988 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
Ady Abraham005398b2023-06-05 13:59:41 -07003989 ATRACE_FORMAT_INSTANT("%s: false [eDimmingEnabledChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003990 return false;
3991 }
3992 }
3993
John Reck68796592023-01-25 13:47:12 -05003994 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07003995 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
3996 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
Ady Abraham005398b2023-06-05 13:59:41 -07003997 ATRACE_FORMAT_INSTANT("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05003998 return false;
3999 }
4000 }
4001
Alec Mouri1b0d4e12024-02-12 22:27:19 +00004002 if (s.what & layer_state_t::eDesiredHdrHeadroomChanged) {
4003 if (mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
4004 ATRACE_FORMAT_INSTANT("%s: false [eDesiredHdrHeadroomChanged changed]", __func__);
4005 return false;
4006 }
4007 }
4008
Patrick Williamsbb25f802022-08-30 23:02:34 +00004009 return true;
4010}
4011
Vishnu Naire14c6b32022-08-06 04:20:15 +00004012sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004013 // 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 +00004014 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004015}
4016
Vishnu Naire14c6b32022-08-06 04:20:15 +00004017const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004018 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00004019}
4020
Vishnu Naire14c6b32022-08-06 04:20:15 +00004021LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004022 return mSnapshot.get();
4023}
Vishnu Naire14c6b32022-08-06 04:20:15 +00004024
Vishnu Nair3af0ec02023-02-10 04:13:48 +00004025std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
4026 return std::move(mSnapshot);
4027}
4028
4029void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
4030 mSnapshot = std::move(snapshot);
4031}
4032
Patrick Williamsbb25f802022-08-30 23:02:34 +00004033const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004034 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00004035}
4036
Patrick Williams7584c6a2022-10-29 02:10:58 +00004037sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00004038 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00004039 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
4040 return result;
4041}
4042
Vishnu Nair3af0ec02023-02-10 04:13:48 +00004043sp<LayerFE> Layer::getCompositionEngineLayerFE(
4044 const frontend::LayerHierarchy::TraversalPath& path) {
4045 for (auto& [p, layerFE] : mLayerFEs) {
4046 if (p == path) {
4047 return layerFE;
4048 }
4049 }
4050 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
4051 mLayerFEs.emplace_back(path, layerFE);
4052 return layerFE;
4053}
4054
Patrick Williamsbb25f802022-08-30 23:02:34 +00004055void Layer::useSurfaceDamage() {
4056 if (mFlinger->mForceFullDamage) {
4057 surfaceDamageRegion = Region::INVALID_REGION;
4058 } else {
4059 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
4060 }
4061}
4062
4063void Layer::useEmptyDamage() {
4064 surfaceDamageRegion.clear();
4065}
4066
4067bool Layer::isOpaque(const Layer::State& s) const {
4068 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
4069 // layer's opaque flag.
4070 if (!hasSomethingToDraw()) {
4071 return false;
4072 }
4073
4074 // if the layer has the opaque flag, then we're always opaque
4075 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
4076 return true;
4077 }
4078
4079 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004080 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004081 return true;
4082 }
4083
4084 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
4085 return fillsColor() && getAlpha() == 1.0_hf;
4086}
4087
4088bool Layer::canReceiveInput() const {
4089 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
4090}
4091
4092bool Layer::isVisible() const {
4093 if (!hasSomethingToDraw()) {
4094 return false;
4095 }
4096
4097 if (isHiddenByPolicy()) {
4098 return false;
4099 }
4100
4101 return getAlpha() > 0.0f || hasBlur();
4102}
4103
Leon Scroggins III5b581492023-10-31 14:29:41 -04004104void Layer::onCompositionPresented(const DisplayDevice* display,
4105 const std::shared_ptr<FenceTime>& glDoneFence,
4106 const std::shared_ptr<FenceTime>& presentFence,
4107 const CompositorTiming& compositorTiming) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004108 // mFrameLatencyNeeded is true when a new frame was latched for the
4109 // composition.
4110 if (!mBufferInfo.mFrameLatencyNeeded) return;
4111
4112 for (const auto& handle : mDrawingState.callbackHandles) {
4113 handle->gpuCompositionDoneFence = glDoneFence;
4114 handle->compositorTiming = compositorTiming;
4115 }
4116
4117 // Update mFrameTracker.
4118 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
4119 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
4120
4121 const int32_t layerId = getSequence();
4122 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
4123
4124 const auto outputLayer = findOutputLayerForDisplay(display);
4125 if (outputLayer && outputLayer->requiresClientComposition()) {
4126 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
4127 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4128 clientCompositionTimestamp,
4129 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
4130 // Update the SurfaceFrames in the drawing state
4131 if (mDrawingState.bufferSurfaceFrameTX) {
4132 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
4133 }
4134 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
4135 surfaceFrame->setGpuComposition();
4136 }
4137 }
4138
4139 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
4140 if (frameReadyFence->isValid()) {
4141 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
4142 } else {
4143 // There was no fence for this frame, so assume that it was ready
4144 // to be presented at the desired present time.
4145 mFrameTracker.setFrameReadyTime(desiredPresentTime);
4146 }
4147
4148 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08004149 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004150 const std::optional<Fps> renderRate =
4151 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
4152
Alec Mouri7c1d8b52023-08-29 20:14:46 +00004153 const auto vote = frameRateToSetFrameRateVotePayload(getFrameRateForLayerTree());
Patrick Williamsbb25f802022-08-30 23:02:34 +00004154 const auto gameMode = getGameMode();
4155
4156 if (presentFence->isValid()) {
4157 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
4158 refreshRate, renderRate, vote, gameMode);
4159 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4160 presentFence,
4161 FrameTracer::FrameEvent::PRESENT_FENCE);
4162 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
4163 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
4164 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04004165 // The HWC doesn't support present fences, so use the present timestamp instead.
4166 const nsecs_t presentTimestamp =
4167 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
4168
4169 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
4170 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
4171 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
4172
Patrick Williamsbb25f802022-08-30 23:02:34 +00004173 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
4174 refreshRate, renderRate, vote, gameMode);
4175 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
4176 mCurrentFrameNumber, actualPresentTime,
4177 FrameTracer::FrameEvent::PRESENT_FENCE);
4178 mFrameTracker.setActualPresentTime(actualPresentTime);
4179 }
4180 }
4181
4182 mFrameTracker.advanceFrame();
4183 mBufferInfo.mFrameLatencyNeeded = false;
4184}
4185
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004186bool Layer::willReleaseBufferOnLatch() const {
4187 return !mDrawingState.buffer && mBufferInfo.mBuffer;
4188}
4189
Patrick Williamsbb25f802022-08-30 23:02:34 +00004190bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00004191 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
4192 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
4193}
4194
4195bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004196 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
4197 getDrawingState().frameNumber);
4198
4199 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
4200
4201 if (refreshRequired) {
4202 return refreshRequired;
4203 }
4204
4205 // If the head buffer's acquire fence hasn't signaled yet, return and
4206 // try again later
4207 if (!fenceHasSignaled()) {
4208 ATRACE_NAME("!fenceHasSignaled()");
4209 mFlinger->onLayerUpdate();
4210 return false;
4211 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00004212 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004213
4214 // Capture the old state of the layer for comparisons later
4215 BufferInfo oldBufferInfo = mBufferInfo;
4216 const bool oldOpacity = isOpaque(mDrawingState);
4217 mPreviousFrameNumber = mCurrentFrameNumber;
4218 mCurrentFrameNumber = mDrawingState.frameNumber;
4219 gatherBufferInfo();
4220
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004221 if (mBufferInfo.mBuffer) {
4222 // We latched a buffer that will be presented soon. Clear the previously presented layer
4223 // stack list.
4224 mPreviouslyPresentedLayerStacks.clear();
4225 }
4226
4227 if (mDrawingState.buffer == nullptr) {
4228 const bool bufferReleased = oldBufferInfo.mBuffer != nullptr;
4229 recomputeVisibleRegions = bufferReleased;
4230 return bufferReleased;
4231 }
4232
Patrick Williamsbb25f802022-08-30 23:02:34 +00004233 if (oldBufferInfo.mBuffer == nullptr) {
4234 // the first time we receive a buffer, we need to trigger a
4235 // geometry invalidation.
4236 recomputeVisibleRegions = true;
4237 }
4238
4239 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
4240 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
4241 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
4242 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
4243 recomputeVisibleRegions = true;
4244 }
4245
4246 if (oldBufferInfo.mBuffer != nullptr) {
4247 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
4248 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
4249 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
4250 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
4251 recomputeVisibleRegions = true;
4252 }
4253 }
4254
4255 if (oldOpacity != isOpaque(mDrawingState)) {
4256 recomputeVisibleRegions = true;
4257 }
4258
4259 return true;
4260}
4261
4262bool Layer::hasReadyFrame() const {
4263 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4264}
4265
4266bool Layer::isProtected() const {
4267 return (mBufferInfo.mBuffer != nullptr) &&
4268 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4269}
4270
Patrick Williamsbb25f802022-08-30 23:02:34 +00004271void Layer::latchAndReleaseBuffer() {
4272 if (hasReadyFrame()) {
4273 bool ignored = false;
4274 latchBuffer(ignored, systemTime());
4275 }
4276 releasePendingBuffer(systemTime());
4277}
4278
4279PixelFormat Layer::getPixelFormat() const {
4280 return mBufferInfo.mPixelFormat;
4281}
4282
4283bool Layer::getTransformToDisplayInverse() const {
4284 return mBufferInfo.mTransformToDisplayInverse;
4285}
4286
4287Rect Layer::getBufferCrop() const {
4288 // this is the crop rectangle that applies to the buffer
4289 // itself (as opposed to the window)
4290 if (!mBufferInfo.mCrop.isEmpty()) {
4291 // if the buffer crop is defined, we use that
4292 return mBufferInfo.mCrop;
4293 } else if (mBufferInfo.mBuffer != nullptr) {
4294 // otherwise we use the whole buffer
4295 return mBufferInfo.mBuffer->getBounds();
4296 } else {
4297 // if we don't have a buffer yet, we use an empty/invalid crop
4298 return Rect();
4299 }
4300}
4301
4302uint32_t Layer::getBufferTransform() const {
4303 return mBufferInfo.mTransform;
4304}
4305
4306ui::Dataspace Layer::getDataSpace() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004307 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4308}
4309
Alec Mouri89f5d4e2023-10-20 17:12:49 +00004310bool Layer::isFrontBuffered() const {
4311 if (mBufferInfo.mBuffer == nullptr) {
4312 return false;
4313 }
4314
4315 return mBufferInfo.mBuffer->getUsage() & AHARDWAREBUFFER_USAGE_FRONT_BUFFER;
4316}
4317
Patrick Williamsbb25f802022-08-30 23:02:34 +00004318ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4319 ui::Dataspace updatedDataspace = dataspace;
4320 // translate legacy dataspaces to modern dataspaces
4321 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00004322 // Treat unknown dataspaces as V0_sRGB
4323 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00004324 case ui::Dataspace::SRGB:
4325 updatedDataspace = ui::Dataspace::V0_SRGB;
4326 break;
4327 case ui::Dataspace::SRGB_LINEAR:
4328 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4329 break;
4330 case ui::Dataspace::JFIF:
4331 updatedDataspace = ui::Dataspace::V0_JFIF;
4332 break;
4333 case ui::Dataspace::BT601_625:
4334 updatedDataspace = ui::Dataspace::V0_BT601_625;
4335 break;
4336 case ui::Dataspace::BT601_525:
4337 updatedDataspace = ui::Dataspace::V0_BT601_525;
4338 break;
4339 case ui::Dataspace::BT709:
4340 updatedDataspace = ui::Dataspace::V0_BT709;
4341 break;
4342 default:
4343 break;
4344 }
4345
4346 return updatedDataspace;
4347}
4348
4349sp<GraphicBuffer> Layer::getBuffer() const {
4350 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4351}
4352
Vishnu Nairb76d99a2023-03-19 18:22:31 -07004353void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4354 mTransformHintLegacy = getFixedTransformHint();
4355 if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4356 mTransformHintLegacy = displayTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004357 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004358 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004359}
4360
4361const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4362 return mBufferInfo.mBuffer;
4363}
4364
4365bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004366 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004367 return false;
4368 }
4369
4370 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004371 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004372 mDrawingState.modified = true;
4373 setTransactionFlags(eTransactionNeeded);
4374 return true;
4375}
4376
4377bool Layer::fillsColor() const {
4378 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4379 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4380}
4381
4382bool Layer::hasBlur() const {
4383 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4384}
4385
Vishnu Nairba354102022-08-01 00:14:18 +00004386void Layer::updateSnapshot(bool updateGeometry) {
4387 if (!getCompositionEngineLayerFE()) {
4388 return;
4389 }
4390
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004391 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004392 if (updateGeometry) {
4393 prepareBasicGeometryCompositionState();
4394 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004395 snapshot->roundedCorner = getRoundedCornerState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004396 snapshot->transformedBounds = mScreenBounds;
4397 if (mEffectiveShadowRadius > 0.f) {
4398 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4399
4400 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4401 // it if transparent regions are present. This may not be necessary since shadows are
4402 // typically cast by layers without transparent regions.
4403 snapshot->shadowSettings.boundaries = mBounds;
4404
4405 const float casterAlpha = snapshot->alpha;
4406 const bool casterIsOpaque =
4407 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4408
4409 // If the casting layer is translucent, we need to fill in the shadow underneath the
4410 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4411 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4412 snapshot->shadowSettings.ambientColor *= casterAlpha;
4413 snapshot->shadowSettings.spotColor *= casterAlpha;
4414 }
4415 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004416 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004417 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004418 snapshot->layerOpaqueFlagSet =
4419 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004420 sp<Layer> p = mDrawingParent.promote();
4421 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004422 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004423 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004424 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004425 }
4426 snapshot->bufferSize = getBufferSize(mDrawingState);
4427 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004428 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004429 preparePerFrameCompositionState();
4430}
4431
Vishnu Naire14c6b32022-08-06 04:20:15 +00004432void Layer::updateChildrenSnapshots(bool updateGeometry) {
4433 for (const sp<Layer>& child : mDrawingChildren) {
4434 child->updateSnapshot(updateGeometry);
4435 child->updateChildrenSnapshots(updateGeometry);
4436 }
4437}
4438
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004439void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4440 mSnapshot->layerMetadata = parentMetadata;
4441 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4442 for (const sp<Layer>& child : mDrawingChildren) {
4443 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4444 }
4445}
4446
4447void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4448 std::unordered_set<Layer*>& visited) {
4449 if (visited.find(this) != visited.end()) {
4450 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4451 return;
4452 }
4453 visited.insert(this);
4454
4455 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4456
4457 if (mDrawingState.zOrderRelatives.empty()) {
4458 return;
4459 }
4460 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4461 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4462 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4463 sp<Layer> relative = weakRelative.promote();
4464 if (!relative) {
4465 continue;
4466 }
4467 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4468 }
4469}
4470
Chavi Weingarten328a8312023-01-26 21:17:52 +00004471bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004472 TrustedPresentationListener const& listener) {
4473 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4474 mTrustedPresentationListener = listener;
4475 mTrustedPresentationThresholds = thresholds;
4476 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4477 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4478 mFlinger->mNumTrustedPresentationListeners++;
4479 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4480 mFlinger->mNumTrustedPresentationListeners--;
4481 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004482
4483 // Reset trusted presentation states to ensure we start the time again.
4484 mEnteredTrustedPresentationStateTime = -1;
4485 mLastReportedTrustedPresentationState = false;
4486 mLastComputedTrustedPresentationState = false;
4487
4488 // If there's a new trusted presentation listener, the code needs to go through the composite
4489 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4490 // we're already in the requested state.
4491 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004492}
4493
Vishnu Naira156f482023-02-22 00:23:38 +00004494void Layer::updateLastLatchTime(nsecs_t latchTime) {
4495 mLastLatchTime = latchTime;
4496}
4497
Arthur Hung69f95222023-10-04 07:39:02 +00004498void Layer::setIsSmallDirty(const Region& damageRegion,
4499 const ui::Transform& layerToDisplayTransform) {
4500 mSmallDirty = false;
Jerry Chang36678002023-11-29 16:56:17 +00004501 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00004502 return;
4503 }
4504
4505 if (mWindowType != WindowInfo::Type::APPLICATION &&
4506 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
4507 return;
4508 }
Arthur Hung69f95222023-10-04 07:39:02 +00004509
4510 Rect bounds = damageRegion.getBounds();
Arthur Hungc70bee22023-06-02 01:35:52 +00004511 if (!bounds.isValid()) {
4512 return;
4513 }
4514
Arthur Hung69f95222023-10-04 07:39:02 +00004515 // Transform to screen space.
4516 bounds = layerToDisplayTransform.transform(bounds);
4517
Arthur Hungc70bee22023-06-02 01:35:52 +00004518 // If the damage region is a small dirty, this could give the hint for the layer history that
4519 // it could suppress the heuristic rate when calculating.
Tony Huangf3621102023-09-04 17:14:22 +08004520 mSmallDirty = mFlinger->mScheduler->isSmallDirtyArea(mOwnerAppId,
Tony Huang9ac5e6e2023-08-24 09:01:44 +00004521 bounds.getWidth() * bounds.getHeight());
Arthur Hungc70bee22023-06-02 01:35:52 +00004522}
4523
Arthur Hung69f95222023-10-04 07:39:02 +00004524void Layer::setIsSmallDirty(frontend::LayerSnapshot* snapshot) {
4525 setIsSmallDirty(snapshot->surfaceDamage, snapshot->localTransform);
4526 snapshot->isSmallDirty = mSmallDirty;
4527}
4528
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004529} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004530
4531#if defined(__gl_h_)
4532#error "don't include gl/gl.h in this file"
4533#endif
4534
4535#if defined(__gl2_h_)
4536#error "don't include gl2/gl2.h in this file"
4537#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004538
4539// TODO(b/129481165): remove the #pragma below and fix conversion issues
4540#pragma clang diagnostic pop // ignored "-Wconversion"