blob: c1920bae50ac04b4ac87ac8153dccdf9de288019 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Dan Stoza9e56aa02015-11-02 13:00:03 -080021//#define LOG_NDEBUG 0
22#undef LOG_TAG
23#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080024#define ATRACE_TAG ATRACE_TAG_GRAPHICS
25
Alec Mourie60041e2019-06-14 18:59:51 -070026#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080027
[1;3C2b9fc252021-02-04 16:16:50 -080028#include <android-base/properties.h>
Yiwei Zhang5434a782018-12-05 18:06:32 -080029#include <android-base/stringprintf.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080030#include <android/native_window.h>
Vishnu Nair0f085c62019-08-30 08:49:12 -070031#include <binder/IPCThreadState.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000032#include <compositionengine/CompositionEngine.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080033#include <compositionengine/Display.h>
Lloyd Piquea83776c2019-01-29 18:42:32 -080034#include <compositionengine/LayerFECompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080035#include <compositionengine/OutputLayer.h>
36#include <compositionengine/impl/OutputLayerCompositionState.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070037#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070038#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070039#include <cutils/properties.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070040#include <ftl/enum.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080041#include <ftl/fake_guard.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080042#include <gui/BufferItem.h>
43#include <gui/LayerDebugInfo.h>
44#include <gui/Surface.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000045#include <gui/TraceUtils.h>
Alec Mourie60041e2019-06-14 18:59:51 -070046#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070047#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070049#include <stdint.h>
50#include <stdlib.h>
51#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000052#include <system/graphics-base-v1.0.h>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070053#include <ui/DataspaceUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080054#include <ui/DebugUtils.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000055#include <ui/FloatRect.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080056#include <ui/GraphicBuffer.h>
57#include <ui/PixelFormat.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000058#include <ui/Rect.h>
59#include <ui/Transform.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060#include <utils/Errors.h>
61#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080062#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080064#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065
Alec Mourie60041e2019-06-14 18:59:51 -070066#include <algorithm>
67#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070068#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070069#include <sstream>
70
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070071#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080072#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070073#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070074#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +000075#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000076#include "FrontEnd/LayerHandle.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080077#include "LayerProtoHelper.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080079#include "TimeStats/TimeStats.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070080#include "TunnelModeEnabledReporter.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070081
David Sodman41fdfc92017-11-06 16:09:56 -080082#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000083#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085namespace android {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010086namespace {
87constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000088
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000089const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000090
Patrick Williamsbb25f802022-08-30 23:02:34 +000091bool assignTransform(ui::Transform* dst, ui::Transform& from) {
92 if (*dst == from) {
93 return false;
94 }
95 *dst = from;
96 return true;
97}
98
99TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
100 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
101 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
102 const auto frameRateCompatibility = [frameRate] {
103 switch (frameRate.type) {
104 case Layer::FrameRateCompatibility::Default:
105 return FrameRateCompatibility::Default;
106 case Layer::FrameRateCompatibility::ExactOrMultiple:
107 return FrameRateCompatibility::ExactOrMultiple;
108 default:
109 return FrameRateCompatibility::Undefined;
110 }
111 }();
112
113 const auto seamlessness = [frameRate] {
114 switch (frameRate.seamlessness) {
115 case scheduler::Seamlessness::OnlySeamless:
116 return Seamlessness::ShouldBeSeamless;
117 case scheduler::Seamlessness::SeamedAndSeamless:
118 return Seamlessness::NotRequired;
119 default:
120 return Seamlessness::Undefined;
121 }
122 }();
123
124 return TimeStats::SetFrameRateVote{.frameRate = frameRate.rate.getValue(),
125 .frameRateCompatibility = frameRateCompatibility,
126 .seamlessness = seamlessness};
127}
128
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100129} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800130
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700131using namespace ftl::flag_operators;
132
Yiwei Zhang5434a782018-12-05 18:06:32 -0800133using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000134using frontend::LayerSnapshot;
135using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800136using gui::GameMode;
137using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500138using gui::WindowInfo;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800139
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700140using PresentState = frametimeline::SurfaceFrame::PresentState;
141
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700142Layer::Layer(const LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000143 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700144 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000145 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700146 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800147 mWindowType(static_cast<WindowInfo::Type>(
148 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000149 mLayerCreationFlags(args.flags),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000150 mBorderEnabled(false),
151 mTextureName(args.textureName),
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000152 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000153 ALOGV("Creating Layer %s", getDebugName());
154
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700155 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700156 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
157 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
158 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700159 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
160 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700161 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700162 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700163 mDrawingState.z = 0;
164 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700165 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700166 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700167 mDrawingState.transform.set(0, 0);
168 mDrawingState.frameNumber = 0;
169 mDrawingState.bufferTransform = 0;
170 mDrawingState.transformToDisplayInverse = false;
171 mDrawingState.crop.makeInvalid();
172 mDrawingState.acquireFence = sp<Fence>::make(-1);
173 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
174 mDrawingState.dataspace = ui::Dataspace::UNKNOWN;
Vishnu Nairbc4ee5c2022-08-16 03:19:37 +0000175 mDrawingState.dataspaceRequested = false;
Robert Carr6a160312021-05-17 12:08:20 -0700176 mDrawingState.hdrMetadata.validTypes = 0;
177 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
178 mDrawingState.cornerRadius = 0.0f;
179 mDrawingState.backgroundBlurRadius = 0;
180 mDrawingState.api = -1;
181 mDrawingState.hasColorTransform = false;
182 mDrawingState.colorSpaceAgnostic = false;
183 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
184 mDrawingState.metadata = args.metadata;
185 mDrawingState.shadowRadius = 0.f;
186 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
187 mDrawingState.frameTimelineInfo = {};
188 mDrawingState.postTime = -1;
189 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000190 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700191 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700192 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000193 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700194
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700195 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
196 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700197 mDrawingState.color.r = -1.0_hf;
198 mDrawingState.color.g = -1.0_hf;
199 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700200 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700201
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500202 mFrameTracker.setDisplayRefreshPeriod(
203 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700204
Vishnu Naircb8be502022-10-12 19:03:23 +0000205 mOwnerUid = args.ownerUid;
206 mOwnerPid = args.ownerPid;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000207
208 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
209 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
210 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
211 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000212
213 mSnapshot->sequence = sequence;
214 mSnapshot->name = getDebugName();
215 mSnapshot->textureName = mTextureName;
216 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000217 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800218}
219
220void Layer::onFirstRef() {
221 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700222}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700223
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700224Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000225 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
226 "Layer destructor called off the main thread.");
227
Patrick Williamsbb25f802022-08-30 23:02:34 +0000228 // The original layer and the clone layer share the same texture and buffer. Therefore, only
229 // one of the layers, in this case the original layer, needs to handle the deletion. The
230 // original layer and the clone should be removed at the same time so there shouldn't be any
231 // issue with the clone layer trying to use the texture.
232 if (mBufferInfo.mBuffer != nullptr) {
233 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
234 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800235 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000236 }
237 if (!isClone()) {
238 // The original layer and the clone layer share the same texture. Therefore, only one of
239 // the layers, in this case the original layer, needs to handle the deletion. The original
240 // layer and the clone should be removed at the same time so there shouldn't be any issue
241 // with the clone layer trying to use the deleted texture.
242 mFlinger->deleteTextureAsync(mTextureName);
243 }
244 const int32_t layerId = getSequence();
245 mFlinger->mTimeStats->onDestroy(layerId);
246 mFlinger->mFrameTracer->onDestroy(layerId);
247
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000248 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700249 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700250
251 if (mDrawingState.sidebandStream != nullptr) {
252 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
253 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700254 if (mHadClonedChild) {
255 mFlinger->mNumClones--;
256 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000257 if (hasTrustedPresentationListener()) {
258 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000259 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000260 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700261}
262
Mathias Agopian13127d82013-03-05 17:47:11 -0800263// ---------------------------------------------------------------------------
264// callbacks
265// ---------------------------------------------------------------------------
266
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700267void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700268 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700269 return;
270 }
Robert Carr2e102c92018-10-23 12:11:15 -0700271
Robert Carr6a160312021-05-17 12:08:20 -0700272 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700273 if (strongRelative == nullptr) {
274 setZOrderRelativeOf(nullptr);
275 return;
276 }
277
278 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700279 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700280 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800281 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700282 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700283}
284
285void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700286 if (!mRemovedFromDrawingState) {
287 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700288 mFlinger->mScheduler->deregisterLayer(this);
289 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000290 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000291
Ady Abrahamd11bade2022-08-01 16:18:03 -0700292 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700293}
Chia-I Wu38512252017-05-17 14:36:16 -0700294
chaviw68d4dab2020-06-08 15:07:32 -0700295sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000296 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700297 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700298 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700299 }
300 return parent->getRootLayer();
301}
302
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700303void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700304 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
305 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700306 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700307
308 traverse(LayerVector::StateSet::Current, [&](Layer* layer) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700309 layer->removeFromCurrentState();
310 layer->removeRelativeZ(layersInTree);
chaviw68d4dab2020-06-08 15:07:32 -0700311 });
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) {
400 const auto outputLayer = findOutputLayerForDisplay(display);
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;
579 snapshot->shadowRadius = 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;
592 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
593 snapshot->blurRegions = drawingState.blurRegions;
594 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();
John Reck68796592023-01-25 13:47:12 -0500646 snapshot->currentSdrHdrRatio = getCurrentSdrHdrRatio();
647 snapshot->desiredSdrHdrRatio = getDesiredSdrHdrRatio();
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.
657 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000658 snapshot->stretchEffect.hasEffect()) {
659 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800660 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700661 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000662 snapshot->blurRegions = drawingState.blurRegions;
663 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400664
665 // Layer framerate is used in caching decisions.
666 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
667 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000668 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000669
670 if (hasBufferOrSidebandStream()) {
671 preparePerFrameBufferCompositionState();
672 } else {
673 preparePerFrameEffectsCompositionState();
674 }
675}
676
677void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000678 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000679 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000680 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000681 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
682 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000683 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
684 return;
685 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000686 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000687 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800688 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
689 snapshot->compositionType =
690 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000691 } else {
692 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000693 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
694 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000695 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
696 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
697 }
698
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000699 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000700 snapshot->acquireFence = mBufferInfo.mFence;
701 snapshot->frameNumber = mBufferInfo.mFrameNumber;
702 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000703}
704
705void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000706 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000707 auto* snapshot = editLayerSnapshot();
708 snapshot->color = getColor();
709 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000710 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800711}
712
Lloyd Piquede196652020-01-22 17:29:58 -0800713void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800714 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000715 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000716 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800717
718 // Apply the layer's transform, followed by the display's global transform
719 // Here we're guaranteed that the layer's transform preserves rects
720 Rect win = getCroppedBufferSize(drawingState);
721 // Subtract the transparent region and snap to the bounds
722 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
723 Rect frame(getTransform().transform(bounds));
724
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000725 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800726}
727
Lloyd Piquea83776c2019-01-29 18:42:32 -0800728const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700729 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800730}
731
Mathias Agopian13127d82013-03-05 17:47:11 -0800732// ---------------------------------------------------------------------------
733// drawing...
734// ---------------------------------------------------------------------------
735
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500736aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
737 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700738 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800739 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500740 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800741 }
742 if (outputLayer->getState().hwc) {
743 return (*outputLayer->getState().hwc).hwcCompositionType;
744 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500745 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800746 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800747}
748
Mathias Agopian13127d82013-03-05 17:47:11 -0800749// ----------------------------------------------------------------------------
750// local state
751// ----------------------------------------------------------------------------
752
David Sodman41fdfc92017-11-06 16:09:56 -0800753bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800754 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700755 if (s.flags & layer_state_t::eLayerSecure) {
756 return true;
757 }
758
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000759 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700760 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700761}
762
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100763void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
764 std::vector<JankData>& jankData) {
765 if (mPendingJankClassifications.empty() ||
766 !mPendingJankClassifications.front()->getJankType()) {
767 return;
768 }
769
770 bool includeJankData = false;
771 for (const auto& handle : handles) {
772 for (const auto& cb : handle->callbackIds) {
773 if (cb.includeJankData) {
774 includeJankData = true;
775 break;
776 }
777 }
778
779 if (includeJankData) {
780 jankData.reserve(mPendingJankClassifications.size());
781 break;
782 }
783 }
784
785 while (!mPendingJankClassifications.empty() &&
786 mPendingJankClassifications.front()->getJankType()) {
787 if (includeJankData) {
788 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
789 mPendingJankClassifications.front();
790 jankData.emplace_back(
791 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
792 }
793 mPendingJankClassifications.pop_front();
794 }
795}
796
Mathias Agopian13127d82013-03-05 17:47:11 -0800797// ----------------------------------------------------------------------------
798// transaction
799// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800800
Vishnu Naira156f482023-02-22 00:23:38 +0000801uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700802 ATRACE_CALL();
803
Robert Carr0758e5d2021-03-11 22:15:04 -0800804 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700805 mDrawingStateModified = mDrawingState.modified;
806 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700807
Alec Mourib416efd2018-09-06 21:01:59 +0000808 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700809
Robert Carr6a160312021-05-17 12:08:20 -0700810 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800811 // invalidate and recompute the visible regions if needed
812 flags |= Layer::eVisibleRegion;
813 }
814
Robert Carr6a160312021-05-17 12:08:20 -0700815 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800816 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000817 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800818 flags |= eVisibleRegion;
819 this->contentDirty = true;
820
821 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700822 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800823 }
824
Arthur Hung9ed43392022-05-27 06:31:57 +0000825 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
826 mFlinger->mUpdateInputInfo = true;
827 }
828
Vishnu Naira156f482023-02-22 00:23:38 +0000829 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800830
Mathias Agopian13127d82013-03-05 17:47:11 -0800831 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800832}
833
Vishnu Naira156f482023-02-22 00:23:38 +0000834void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000835 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
836 // bufferSurfaceFrameTX will be presented in latchBuffer.
837 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
838 if (surfaceFrame->getPresentState() != PresentState::Presented) {
839 // With applyPendingStates, we could end up having presented surfaceframes from previous
840 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800841 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000842 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
843 }
844 }
Robert Carr6a160312021-05-17 12:08:20 -0700845 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700846}
847
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700848uint32_t Layer::clearTransactionFlags(uint32_t mask) {
849 const auto flags = mTransactionFlags & mask;
850 mTransactionFlags &= ~mask;
851 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800852}
853
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700854void Layer::setTransactionFlags(uint32_t mask) {
855 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800856}
857
Robert Carr1f0a16a2016-10-24 16:27:39 -0700858bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
859 ssize_t idx = mCurrentChildren.indexOf(childLayer);
860 if (idx < 0) {
861 return false;
862 }
863 if (childLayer->setLayer(z)) {
864 mCurrentChildren.removeAt(idx);
865 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800866 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700867 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800868 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700869}
870
Robert Carr503c7042017-09-27 15:06:08 -0700871bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
872 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
873 ssize_t idx = mCurrentChildren.indexOf(childLayer);
874 if (idx < 0) {
875 return false;
876 }
877 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
878 mCurrentChildren.removeAt(idx);
879 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800880 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700881 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800882 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700883}
884
Robert Carrae060832016-11-28 10:51:00 -0800885bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700886 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
887 mDrawingState.sequence++;
888 mDrawingState.z = z;
889 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700890
Robert Carra70e91c2021-06-11 13:59:52 -0700891 mFlinger->mSomeChildrenChanged = true;
892
Robert Carrdb66e622017-04-10 16:55:57 -0700893 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700894 if (mDrawingState.zOrderRelativeOf != nullptr) {
895 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700896 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700897 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700898 }
chaviw606e5cf2019-03-01 10:12:10 -0800899 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700900 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800901 setTransactionFlags(eTransactionNeeded);
902 return true;
903}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700904
Robert Carrdb66e622017-04-10 16:55:57 -0700905void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700906 mDrawingState.zOrderRelatives.remove(relative);
907 mDrawingState.sequence++;
908 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700909 setTransactionFlags(eTransactionNeeded);
910}
911
912void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700913 mDrawingState.zOrderRelatives.add(relative);
914 mDrawingState.modified = true;
915 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700916 setTransactionFlags(eTransactionNeeded);
917}
918
chaviw606e5cf2019-03-01 10:12:10 -0800919void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700920 mDrawingState.zOrderRelativeOf = relativeOf;
921 mDrawingState.sequence++;
922 mDrawingState.modified = true;
923 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700924
chaviw606e5cf2019-03-01 10:12:10 -0800925 setTransactionFlags(eTransactionNeeded);
926}
927
Robert Carr503d2bd2017-12-04 15:49:47 -0800928bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000929 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700930 if (relative == nullptr) {
931 return false;
932 }
933
Robert Carr6a160312021-05-17 12:08:20 -0700934 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
935 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800936 return false;
937 }
938
Robert Carr88b85e12022-03-21 15:47:35 -0700939 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
940 (relative->mDrawingState.zOrderRelativeOf == this)) {
941 ALOGE("Detected relative layer loop between %s and %s",
942 mName.c_str(), relative->mName.c_str());
943 ALOGE("Ignoring new call to set relative layer");
944 return false;
945 }
946
Robert Carra70e91c2021-06-11 13:59:52 -0700947 mFlinger->mSomeChildrenChanged = true;
948
Robert Carr6a160312021-05-17 12:08:20 -0700949 mDrawingState.sequence++;
950 mDrawingState.modified = true;
951 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700952
Robert Carr6a160312021-05-17 12:08:20 -0700953 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700954 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700955 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700956 }
chaviw606e5cf2019-03-01 10:12:10 -0800957 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700958 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700959
960 setTransactionFlags(eTransactionNeeded);
961
962 return true;
963}
964
Winson Chunga30f7c92021-06-29 15:42:56 -0700965bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
966 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
967 mDrawingState.isTrustedOverlay = isTrustedOverlay;
968 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000969 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700970 setTransactionFlags(eTransactionNeeded);
971 return true;
972}
973
974bool Layer::isTrustedOverlay() const {
975 if (getDrawingState().isTrustedOverlay) {
976 return true;
977 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000978 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700979 return (p != nullptr) && p->isTrustedOverlay();
980}
981
Dan Stoza9e56aa02015-11-02 13:00:03 -0800982bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700983 if (mDrawingState.color.a == alpha) return false;
984 mDrawingState.sequence++;
985 mDrawingState.color.a = alpha;
986 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800987 setTransactionFlags(eTransactionNeeded);
988 return true;
989}
chaviw13fdc492017-06-27 12:40:18 -0700990
Valerie Haudd0b7572019-01-29 14:59:27 -0800991bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700992 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700993 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800994 }
Robert Carr6a160312021-05-17 12:08:20 -0700995 mDrawingState.sequence++;
996 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800997 setTransactionFlags(eTransactionNeeded);
998
Robert Carr6a160312021-05-17 12:08:20 -0700999 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001000 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001001 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001002 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001003 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08001004 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001005 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001006
Valerie Haudd0b7572019-01-29 14:59:27 -08001007 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001008 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001009 mFlinger->mLayersAdded = true;
1010 // set up SF to handle added color layer
1011 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -07001012 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001013 }
1014 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001015 } else if (mDrawingState.bgColorLayer && alpha == 0) {
1016 mDrawingState.bgColorLayer->reparent(nullptr);
1017 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001018 return true;
1019 }
1020
Robert Carr6a160312021-05-17 12:08:20 -07001021 mDrawingState.bgColorLayer->setColor(color);
1022 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1023 mDrawingState.bgColorLayer->setAlpha(alpha);
1024 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001025
chaviw13fdc492017-06-27 12:40:18 -07001026 return true;
1027}
1028
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001029bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001030 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001031
Robert Carr6a160312021-05-17 12:08:20 -07001032 mDrawingState.sequence++;
1033 mDrawingState.cornerRadius = cornerRadius;
1034 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001035 setTransactionFlags(eTransactionNeeded);
1036 return true;
1037}
1038
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001039bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001040 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001041 // If we start or stop drawing blur then the layer's visibility state may change so increment
1042 // the magic sequence number.
1043 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1044 mDrawingState.sequence++;
1045 }
Robert Carr6a160312021-05-17 12:08:20 -07001046 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1047 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001048 setTransactionFlags(eTransactionNeeded);
1049 return true;
1050}
Marissa Wall61c58622018-07-18 10:12:20 -07001051
Mathias Agopian13127d82013-03-05 17:47:11 -08001052bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001053 mDrawingState.sequence++;
1054 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001055 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001056 setTransactionFlags(eTransactionNeeded);
1057 return true;
1058}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001059
Lucas Dupinc3800b82020-10-02 16:24:48 -07001060bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001061 // If we start or stop drawing blur then the layer's visibility state may change so increment
1062 // the magic sequence number.
1063 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1064 mDrawingState.sequence++;
1065 }
Robert Carr6a160312021-05-17 12:08:20 -07001066 mDrawingState.blurRegions = blurRegions;
1067 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001068 setTransactionFlags(eTransactionNeeded);
1069 return true;
1070}
1071
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001072bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001073 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1074 if (mDrawingState.flags == newFlags) return false;
1075 mDrawingState.sequence++;
1076 mDrawingState.flags = newFlags;
1077 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001078 setTransactionFlags(eTransactionNeeded);
1079 return true;
1080}
Robert Carr99e27f02016-06-16 15:18:02 -07001081
chaviw25714502021-02-11 10:01:08 -08001082bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001083 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001084 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001085 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001086
Robert Carr6a160312021-05-17 12:08:20 -07001087 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001088 setTransactionFlags(eTransactionNeeded);
1089 return true;
1090}
Robert Carr8d5227b2017-03-16 15:41:03 -07001091
Evan Roskyef876c92019-01-25 17:46:06 -08001092bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001093 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1094 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001095 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001096 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001097}
1098
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001099bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001100 if (mDrawingState.layerStack == layerStack) return false;
1101 mDrawingState.sequence++;
1102 mDrawingState.layerStack = layerStack;
1103 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001104 setTransactionFlags(eTransactionNeeded);
1105 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001106}
1107
Peiyong Linc502cb72019-03-01 15:00:23 -08001108bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001109 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001110 return false;
1111 }
Robert Carr6a160312021-05-17 12:08:20 -07001112 mDrawingState.sequence++;
1113 mDrawingState.colorSpaceAgnostic = agnostic;
1114 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001115 setTransactionFlags(eTransactionNeeded);
1116 return true;
1117}
1118
Sally Qi81d95e62022-03-21 19:41:33 -07001119bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1120 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1121
1122 mDrawingState.sequence++;
1123 mDrawingState.dimmingEnabled = dimmingEnabled;
1124 mDrawingState.modified = true;
1125 setTransactionFlags(eTransactionNeeded);
1126 return true;
1127}
1128
Ana Krulecc84d09b2019-11-02 23:10:29 +01001129bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001130 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1131 mDrawingState.frameRateSelectionPriority = priority;
1132 mDrawingState.sequence++;
1133 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001134 setTransactionFlags(eTransactionNeeded);
1135 return true;
1136}
1137
1138int32_t Layer::getFrameRateSelectionPriority() const {
1139 // Check if layer has priority set.
1140 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1141 return mDrawingState.frameRateSelectionPriority;
1142 }
1143 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001144 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001145 if (parent != nullptr) {
1146 return parent->getFrameRateSelectionPriority();
1147 }
1148
1149 return Layer::PRIORITY_UNSET;
1150}
1151
Andy Labrada096227e2022-06-15 16:58:11 +00001152bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1153 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1154 mDrawingState.defaultFrameRateCompatibility = compatibility;
1155 mDrawingState.modified = true;
1156 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1157 setTransactionFlags(eTransactionNeeded);
1158 return true;
1159}
1160
1161scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1162 return mDrawingState.defaultFrameRateCompatibility;
1163}
1164
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001165bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1166 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1167};
1168
Vishnu Nair73908d12022-10-24 21:46:42 -07001169ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1170 bool useDrawing = state == LayerVector::StateSet::Drawing;
1171 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1172 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001173 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001174 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001175 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001176}
1177
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001178bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001179 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001180 return false;
1181 }
1182
Robert Carr6a160312021-05-17 12:08:20 -07001183 mDrawingState.sequence++;
1184 mDrawingState.shadowRadius = shadowRadius;
1185 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001186 setTransactionFlags(eTransactionNeeded);
1187 return true;
1188}
1189
Vishnu Nair6213bd92020-05-08 17:42:25 -07001190bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001191 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001192 return false;
1193 }
1194
Robert Carr6a160312021-05-17 12:08:20 -07001195 mDrawingState.sequence++;
1196 mDrawingState.fixedTransformHint = fixedTransformHint;
1197 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001198 setTransactionFlags(eTransactionNeeded);
1199 return true;
1200}
1201
John Reckcdb4ed72021-02-04 13:39:33 -05001202bool Layer::setStretchEffect(const StretchEffect& effect) {
1203 StretchEffect temp = effect;
1204 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001205 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001206 return false;
1207 }
Robert Carr6a160312021-05-17 12:08:20 -07001208 mDrawingState.sequence++;
1209 mDrawingState.stretchEffect = temp;
1210 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001211 setTransactionFlags(eTransactionNeeded);
1212 return true;
1213}
1214
John Reckc00c6692021-02-16 11:37:33 -05001215StretchEffect Layer::getStretchEffect() const {
1216 if (mDrawingState.stretchEffect.hasEffect()) {
1217 return mDrawingState.stretchEffect;
1218 }
1219
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001220 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001221 if (parent != nullptr) {
1222 auto effect = parent->getStretchEffect();
1223 if (effect.hasEffect()) {
1224 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1225 return effect;
1226 }
1227 }
1228 return StretchEffect{};
1229}
1230
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001231bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1232 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001233 return false;
1234 }
1235 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001236 mBorderWidth = width;
1237 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001238 return true;
1239}
1240
1241bool Layer::isBorderEnabled() {
1242 return mBorderEnabled;
1243}
1244
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001245float Layer::getBorderWidth() {
1246 return mBorderWidth;
1247}
1248
1249const half4& Layer::getBorderColor() {
1250 return mBorderColor;
1251}
1252
Ady Abrahama850c182021-08-04 13:04:37 -07001253bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1254 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1255 const auto frameRate = [&] {
1256 if (mDrawingState.frameRate.rate.isValid() ||
1257 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1258 return mDrawingState.frameRate;
1259 }
1260
1261 return parentFrameRate;
1262 }();
1263
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001264 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001265
1266 // The frame rate is propagated to the children
1267 bool childrenHaveFrameRate = false;
1268 for (const sp<Layer>& child : mCurrentChildren) {
1269 childrenHaveFrameRate |=
1270 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1271 }
1272
1273 // If we don't have a valid frame rate, but the children do, we set this
1274 // layer as NoVote to allow the children to control the refresh rate
1275 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1276 childrenHaveFrameRate) {
1277 *transactionNeeded |=
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001278 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001279 }
1280
1281 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1282 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001283 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001284 const auto layerVotedWithDefaultCompatibility =
1285 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1286 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1287 const auto layerVotedWithExactCompatibility =
1288 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1289 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1290 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1291}
1292
Ady Abraham60e42ea2020-03-09 19:17:31 -07001293void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001294 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001295 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001296 while (auto parent = layer->getParent()) {
1297 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001298 }
Ady Abrahama850c182021-08-04 13:04:37 -07001299 return layer;
1300 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001301
Ady Abraham60e42ea2020-03-09 19:17:31 -07001302 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001303 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001304
Ady Abrahama850c182021-08-04 13:04:37 -07001305 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001306 if (transactionNeeded) {
1307 mFlinger->setTransactionFlags(eTraversalNeeded);
1308 }
1309}
1310
Ady Abraham71c437d2020-01-31 15:56:57 -08001311bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001312 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001313 return false;
1314 }
1315
Robert Carr6a160312021-05-17 12:08:20 -07001316 mDrawingState.sequence++;
1317 mDrawingState.frameRate = frameRate;
1318 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001319
1320 updateTreeHasFrameRateVote();
1321
Steven Thomas3172e202020-01-06 19:25:30 -08001322 setTransactionFlags(eTransactionNeeded);
1323 return true;
1324}
1325
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001326void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1327 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001328 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001329
1330 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1331 // there are two transactions with the same token, the first one without a buffer and the
1332 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1333 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001334 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1335 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001336 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001337 mDrawingState.bufferSurfaceFrameTX = it->second;
1338 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1339 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1340 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001341 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001342 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001343 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1344 }
1345}
1346
1347void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1348 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001349 mDrawingState.frameTimelineInfo = info;
1350 mDrawingState.postTime = postTime;
1351 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001352 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001353
Robert Carr6a160312021-05-17 12:08:20 -07001354 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001355 bufferSurfaceFrameTX != nullptr) {
1356 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1357 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1358 // being used for BufferSurfaceFrame, don't create a new one.
1359 return;
1360 }
1361 }
1362 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1363 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1364 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001365 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1366 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001367 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001368 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001369 } else {
1370 if (it->second->getPresentState() == PresentState::Presented) {
1371 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1372 // have been from previous vsync.
1373 it->second = createSurfaceFrameForTransaction(info, postTime);
1374 }
1375 }
1376}
1377
1378void Layer::addSurfaceFrameDroppedForBuffer(
1379 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001380 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001381 surfaceFrame->setPresentState(PresentState::Dropped);
1382 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1383}
1384
1385void Layer::addSurfaceFramePresentedForBuffer(
1386 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1387 nsecs_t currentLatchTime) {
1388 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1389 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1390 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001391 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001392}
1393
1394std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1395 const FrameTimelineInfo& info, nsecs_t postTime) {
1396 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001397 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1398 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001399 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001400 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001401 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001402 // For Transactions, the post time is considered to be both queue and acquire fence time.
1403 surfaceFrame->setActualQueueTime(postTime);
1404 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001405 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1406 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001407 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001408 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001409 onSurfaceFrameCreated(surfaceFrame);
1410 return surfaceFrame;
1411}
1412
1413std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1414 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1415 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001416 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001417 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001418 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001419 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001420 // For buffers, acquire fence time will set during latch.
1421 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001422 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1423 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001424 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001425 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001426 onSurfaceFrameCreated(surfaceFrame);
1427 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001428}
1429
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001430bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001431 if (mDrawingState.frameRateForLayerTree == frameRate) {
1432 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001433 }
1434
Ady Abrahama850c182021-08-04 13:04:37 -07001435 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001436
Ady Abrahama850c182021-08-04 13:04:37 -07001437 // TODO(b/195668952): we probably don't need to dirty visible regions here
1438 // or even store frameRateForLayerTree in mDrawingState
1439 mDrawingState.sequence++;
1440 mDrawingState.modified = true;
1441 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001442
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001443 mFlinger->mScheduler
1444 ->recordLayerHistory(sequence, getLayerProps(), systemTime(),
1445 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1446 return true;
1447}
Ady Abrahama850c182021-08-04 13:04:37 -07001448
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001449bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps) {
1450 if (mDrawingState.frameRateForLayerTree == frameRate) {
1451 return false;
1452 }
1453
1454 mDrawingState.frameRateForLayerTree = frameRate;
1455 mFlinger->mScheduler
1456 ->recordLayerHistory(sequence, layerProps, systemTime(),
1457 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001458 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001459}
1460
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001461Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1462 return getDrawingState().frameRateForLayerTree;
1463}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001464
Robert Carr1f0a16a2016-10-24 16:27:39 -07001465bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001466 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001467 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001468 if (parent != nullptr && parent->isHiddenByPolicy()) {
1469 return true;
1470 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001471 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1472 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1473 if (zOrderRelativeOf != nullptr) {
1474 if (zOrderRelativeOf->isHiddenByPolicy()) {
1475 return true;
1476 }
1477 }
1478 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001479 if (CC_UNLIKELY(!isTransformValid())) {
1480 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1481 return true;
1482 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001483 return s.flags & layer_state_t::eLayerHidden;
1484}
1485
David Sodman41fdfc92017-11-06 16:09:56 -08001486uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001487 // TODO: should we do something special if mSecure is set?
1488 if (mProtectedByApp) {
1489 // need a hardware-protected path to external video sink
1490 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001491 }
Riley Andrews03414a12014-07-01 14:22:59 -07001492 if (mPotentialCursor) {
1493 usage |= GraphicBuffer::USAGE_CURSOR;
1494 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001495 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001496 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001497}
1498
Vishnu Nair71fcf912022-10-18 09:14:20 -07001499void Layer::skipReportingTransformHint() {
1500 mSkipReportingTransformHint = true;
1501}
1502
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001503void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1504 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1505 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001506 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001507
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001508 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001509}
1510
Mathias Agopian13127d82013-03-05 17:47:11 -08001511// ----------------------------------------------------------------------------
1512// debugging
1513// ----------------------------------------------------------------------------
1514
Marissa Wall61c58622018-07-18 10:12:20 -07001515// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001516gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001517 using namespace std::string_literals;
1518
Huihong Luo05539a12022-02-23 10:29:40 -08001519 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001520 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001521 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001522 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001523 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001524 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001525
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001526 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001527 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001528 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001529 info.mX = ds.transform.tx();
1530 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001531 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001532 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001533 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001534 info.mFlags = ds.flags;
1535 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001536 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001537 info.mMatrix[0][0] = ds.transform[0][0];
1538 info.mMatrix[0][1] = ds.transform[0][1];
1539 info.mMatrix[1][0] = ds.transform[1][0];
1540 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001541 {
chaviwd62d3062019-09-04 14:48:02 -07001542 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001543 if (buffer != 0) {
1544 info.mActiveBufferWidth = buffer->getWidth();
1545 info.mActiveBufferHeight = buffer->getHeight();
1546 info.mActiveBufferStride = buffer->getStride();
1547 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001548 } else {
1549 info.mActiveBufferWidth = 0;
1550 info.mActiveBufferHeight = 0;
1551 info.mActiveBufferStride = 0;
1552 info.mActiveBufferFormat = 0;
1553 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001554 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001555 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001556 info.mIsOpaque = isOpaque(ds);
1557 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001558 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001559 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001560}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001561
Yiwei Zhang5434a782018-12-05 18:06:32 -08001562void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001563 result.append(kDumpTableRowLength, '-');
1564 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001565 result.append(" Layer name\n");
1566 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001567 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001568 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001569 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001570 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001571 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001572 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1573 result.append(kDumpTableRowLength, '-');
1574 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001575}
1576
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001577void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1578 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001579 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001580 return;
1581 }
1582
Yiwei Zhang5434a782018-12-05 18:06:32 -08001583 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001584 if (mName.length() > 77) {
1585 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001586 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001587 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001588 shortened.append(mName, mName.length() - 36);
1589 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001590 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001591 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001592 }
1593
Yiwei Zhang5434a782018-12-05 18:06:32 -08001594 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001595
Alec Mourib416efd2018-09-06 21:01:59 +00001596 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001597 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001598
Chia-I Wu1e043612018-03-01 09:45:09 -08001599 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001600 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001601 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001602 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001603 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001604 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001605 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001606 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1607 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001608 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001609 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001610 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001611 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001612 const auto frameRate = getFrameRateForLayerTree();
1613 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1614 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001615 ftl::enum_string(frameRate.type).c_str(),
1616 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001617 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001618 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001619 }
Dan Stozae22aec72016-08-01 13:20:59 -07001620
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001621 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1622 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1623
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001624 result.append(kDumpTableRowLength, '-');
1625 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001626}
Dan Stozae22aec72016-08-01 13:20:59 -07001627
Yiwei Zhang5434a782018-12-05 18:06:32 -08001628void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001629 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001630}
1631
Svetoslavd85084b2014-03-20 10:28:31 -07001632void Layer::clearFrameStats() {
1633 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001634}
1635
Jamie Gennis6547ff42013-07-16 20:12:42 -07001636void Layer::logFrameStats() {
1637 mFrameTracker.logAndResetStats(mName);
1638}
1639
Svetoslavd85084b2014-03-20 10:28:31 -07001640void Layer::getFrameStats(FrameStats* outStats) const {
1641 mFrameTracker.getStats(outStats);
1642}
1643
Vishnu Nair76554eb2022-12-09 03:38:36 +00001644void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1645 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
1646 StringAppendF(&result, "Layer %s%s pid:%d uid:%d\n", getName().c_str(), hasBuffer.c_str(),
Vishnu Naircb8be502022-10-12 19:03:23 +00001647 mOwnerPid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001648}
1649
Brian Anderson5ea5e592016-12-01 16:54:33 -08001650void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001651 const int32_t layerId = getSequence();
1652 mFlinger->mTimeStats->onDestroy(layerId);
1653 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001654}
1655
Vishnu Nair787aa782023-03-17 13:46:46 -07001656size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001657 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001658 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001659 count += 1 + child->getChildrenCount();
1660 }
1661 return count;
1662}
1663
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001664void Layer::setGameModeForTree(GameMode gameMode) {
1665 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001666 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1667 gameMode =
1668 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001669 }
1670 setGameMode(gameMode);
1671 for (const sp<Layer>& child : mCurrentChildren) {
1672 child->setGameModeForTree(gameMode);
1673 }
1674}
1675
Robert Carr1f0a16a2016-10-24 16:27:39 -07001676void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001677 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001678 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001679
Robert Carr1f0a16a2016-10-24 16:27:39 -07001680 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001681 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001682 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001683 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001684}
1685
1686ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001687 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001688 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001689
Robert Carr1323c952019-01-28 18:13:27 -08001690 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001691 const auto removeResult = mCurrentChildren.remove(layer);
1692
1693 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001694 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001695 layer->updateTreeHasFrameRateVote();
1696
1697 return removeResult;
1698}
1699
Robert Carr15eae092018-03-23 13:43:53 -07001700void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001701 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001702 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001703 const float parentShadowRadius =
1704 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001705 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001706 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001707 }
1708}
1709
chaviwf1961f72017-09-18 16:41:07 -07001710bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001711 sp<Layer> newParent;
1712 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001713 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001714 if (newParent == nullptr) {
1715 ALOGE("Unable to promote Layer handle");
1716 return false;
1717 }
1718 if (newParent == this) {
1719 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1720 return false;
1721 }
1722 }
1723
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001724 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001725 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001726 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001727 }
1728
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001729 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001730 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001731 if (!newParent->isRemovedFromCurrentState()) {
1732 addToCurrentState();
1733 } else {
1734 onRemovedFromCurrentState();
1735 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001736 } else {
1737 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001738 }
1739
chaviw06178942017-07-27 10:25:59 -07001740 return true;
1741}
1742
Peiyong Lind3788632018-09-18 16:01:31 -07001743bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001744 static const mat4 identityMatrix = mat4();
1745
Robert Carr6a160312021-05-17 12:08:20 -07001746 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001747 return false;
1748 }
Robert Carr6a160312021-05-17 12:08:20 -07001749 ++mDrawingState.sequence;
1750 mDrawingState.colorTransform = matrix;
1751 mDrawingState.hasColorTransform = matrix != identityMatrix;
1752 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001753 setTransactionFlags(eTransactionNeeded);
1754 return true;
1755}
1756
chaviwf66724d2018-11-28 16:35:21 -08001757mat4 Layer::getColorTransform() const {
1758 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001759 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001760 colorTransform = parent->getColorTransform() * colorTransform;
1761 }
1762 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001763}
1764
1765bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001766 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001767 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001768 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1769 }
1770 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001771}
1772
Chia-I Wu11481472018-05-04 10:43:19 -07001773bool Layer::isLegacyDataSpace() const {
1774 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001775 return !(getDataSpace() &
1776 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1777 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001778}
1779
Robert Carr1f0a16a2016-10-24 16:27:39 -07001780void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001781 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001782}
1783
Robert Carr6a160312021-05-17 12:08:20 -07001784int32_t Layer::getZ(LayerVector::StateSet) const {
1785 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001786}
1787
Robert Carr1c5481e2019-07-01 14:42:27 -07001788bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001789 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001790 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001791 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001792}
1793
David Sodman41fdfc92017-11-06 16:09:56 -08001794__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001795 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001796 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1797 "makeTraversalList received invalid stateSet");
1798 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1799 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001800 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001801
Robert Carr29abff82017-12-04 13:51:20 -08001802 if (state.zOrderRelatives.size() == 0) {
1803 *outSkipRelativeZUsers = true;
1804 return children;
1805 }
1806
chaviwfd462612018-05-31 16:11:27 -07001807 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001808 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001809 sp<Layer> strongRelative = weakRelative.promote();
1810 if (strongRelative != nullptr) {
1811 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001812 }
1813 }
1814
Dan Stoza412903f2017-04-27 13:42:17 -07001815 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001816 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001817 continue;
1818 }
Robert Carrdb66e622017-04-10 16:55:57 -07001819 traverse.add(child);
1820 }
1821
1822 return traverse;
1823}
1824
Robert Carr1f0a16a2016-10-24 16:27:39 -07001825/**
Robert Carrdb66e622017-04-10 16:55:57 -07001826 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001827 */
Dan Stoza412903f2017-04-27 13:42:17 -07001828void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001829 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1830 // produce a new list for traversing, including our relatives, and not including our children
1831 // who are relatives of another surface. In the case that there are no relative Z,
1832 // makeTraversalList returns our children directly to avoid significant overhead.
1833 // However in this case we need to take the responsibility for filtering children which
1834 // are relatives of another surface here.
1835 bool skipRelativeZUsers = false;
1836 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001837
Robert Carr1f0a16a2016-10-24 16:27:39 -07001838 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001839 for (; i < list.size(); i++) {
1840 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001841 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1842 continue;
1843 }
1844
chaviw301b1d82019-11-06 13:15:09 -08001845 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001846 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001847 }
Dan Stoza412903f2017-04-27 13:42:17 -07001848 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001849 }
Robert Carr29abff82017-12-04 13:51:20 -08001850
Dan Stoza412903f2017-04-27 13:42:17 -07001851 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001852 for (; i < list.size(); i++) {
1853 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001854
Robert Carr29abff82017-12-04 13:51:20 -08001855 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1856 continue;
1857 }
Dan Stoza412903f2017-04-27 13:42:17 -07001858 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001859 }
1860}
1861
1862/**
Robert Carrdb66e622017-04-10 16:55:57 -07001863 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001864 */
Dan Stoza412903f2017-04-27 13:42:17 -07001865void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1866 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001867 // See traverseInZOrder for documentation.
1868 bool skipRelativeZUsers = false;
1869 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001870
Robert Carr1f0a16a2016-10-24 16:27:39 -07001871 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001872 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001873 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001874
1875 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1876 continue;
1877 }
1878
chaviw301b1d82019-11-06 13:15:09 -08001879 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001880 break;
1881 }
Dan Stoza412903f2017-04-27 13:42:17 -07001882 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001883 }
Dan Stoza412903f2017-04-27 13:42:17 -07001884 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001885 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001886 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001887
1888 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1889 continue;
1890 }
1891
Dan Stoza412903f2017-04-27 13:42:17 -07001892 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001893 }
1894}
1895
Edgar Arriaga844fa672020-01-16 14:21:42 -08001896void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1897 visitor(this);
1898 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001899 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001900 for (const sp<Layer>& child : children) {
1901 child->traverse(state, visitor);
1902 }
1903}
1904
Vishnu Nair787aa782023-03-17 13:46:46 -07001905void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
1906 for (const sp<Layer>& child : mDrawingChildren) {
1907 visitor(child.get());
1908 }
1909}
1910
chaviw4b129c22018-04-09 16:19:43 -07001911LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1912 const std::vector<Layer*>& layersInTree) {
1913 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1914 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001915 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1916 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001917 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001918
chaviwfd462612018-05-31 16:11:27 -07001919 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001920 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1921 sp<Layer> strongRelative = weakRelative.promote();
1922 // Only add relative layers that are also descendents of the top most parent of the tree.
1923 // If a relative layer is not a descendent, then it should be ignored.
1924 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1925 traverse.add(strongRelative);
1926 }
1927 }
1928
1929 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001930 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001931 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1932 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1933 // the child here since it won't be added later as a relative.
1934 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1935 childState.zOrderRelativeOf.promote().get())) {
1936 continue;
1937 }
1938 traverse.add(child);
1939 }
1940
1941 return traverse;
1942}
1943
1944void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1945 LayerVector::StateSet stateSet,
1946 const LayerVector::Visitor& visitor) {
1947 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001948
1949 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001950 for (; i < list.size(); i++) {
1951 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001952 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001953 break;
1954 }
chaviw4b129c22018-04-09 16:19:43 -07001955 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001956 }
chaviw4b129c22018-04-09 16:19:43 -07001957
chaviwa76b2712017-09-20 12:02:26 -07001958 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001959 for (; i < list.size(); i++) {
1960 const auto& relative = list[i];
1961 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001962 }
1963}
1964
chaviw4b129c22018-04-09 16:19:43 -07001965std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1966 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1967 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1968
1969 std::vector<Layer*> layersInTree = {this};
1970 for (size_t i = 0; i < children.size(); i++) {
1971 const auto& child = children[i];
1972 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1973 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1974 }
1975
1976 return layersInTree;
1977}
1978
1979void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1980 const LayerVector::Visitor& visitor) {
1981 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1982 std::sort(layersInTree.begin(), layersInTree.end());
1983 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1984}
1985
Peiyong Linefefaac2018-08-17 12:27:51 -07001986ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001987 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001988}
1989
Garfield Tan2c1782c2022-02-16 15:25:05 -08001990bool Layer::isTransformValid() const {
1991 float transformDet = getTransform().det();
1992 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1993}
1994
chaviw13fdc492017-06-27 12:40:18 -07001995half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001996 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001997
chaviw13fdc492017-06-27 12:40:18 -07001998 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1999 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002000}
Robert Carr6452f122017-03-21 10:41:29 -07002001
Vishnu Nair6213bd92020-05-08 17:42:25 -07002002ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002003 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002004 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2005 return fixedTransformHint;
2006 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002007 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002008 if (!p) return fixedTransformHint;
2009 return p->getFixedTransformHint();
2010}
2011
chaviw13fdc492017-06-27 12:40:18 -07002012half4 Layer::getColor() const {
2013 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002014 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002015}
Robert Carr6452f122017-03-21 10:41:29 -07002016
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002017int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002018 if (getDrawingState().backgroundBlurRadius == 0) {
2019 return 0;
2020 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002021
Vishnu Nair29810f72022-07-01 16:38:41 +00002022 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002023 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2024 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002025}
2026
Galia Peychevae0acf382021-04-12 21:22:34 +02002027const std::vector<BlurRegion> Layer::getBlurRegions() const {
2028 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002029 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002030 for (auto& region : regionsCopy) {
2031 region.alpha = region.alpha * layerAlpha;
2032 }
2033 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002034}
2035
Vishnu Naire14c6b32022-08-06 04:20:15 +00002036RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002037 // Get parent settings
2038 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002039 const auto& parent = mDrawingParent.promote();
2040 if (parent != nullptr) {
2041 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002042 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002043 ui::Transform t = getActiveTransform(getDrawingState());
2044 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002045 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002046 parentSettings.radius.x *= t.getScaleX();
2047 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002048 }
2049 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002050
2051 // Get layer settings
2052 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002053 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002054 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002055 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002056
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002057 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002058 // If the parent and the layer have rounded corner settings, use the parent settings if the
2059 // parent crop is entirely inside the layer crop.
2060 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2061 if (parentSettings.cropRect.left > layerCropRect.left &&
2062 parentSettings.cropRect.top > layerCropRect.top &&
2063 parentSettings.cropRect.right < layerCropRect.right &&
2064 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2065 return parentSettings;
2066 } else {
2067 return layerSettings;
2068 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002069 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002070 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002071 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002072 return parentSettings;
2073 }
2074 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002075}
2076
Robert Carr88b85e12022-03-21 15:47:35 -07002077bool Layer::findInHierarchy(const sp<Layer>& l) {
2078 if (l == this) {
2079 return true;
2080 }
2081 for (auto& child : mDrawingChildren) {
2082 if (child->findInHierarchy(l)) {
2083 return true;
2084 }
2085 }
2086 return false;
2087}
2088
Robert Carr1f0a16a2016-10-24 16:27:39 -07002089void Layer::commitChildList() {
2090 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2091 const auto& child = mCurrentChildren[i];
2092 child->commitChildList();
2093 }
2094 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002095 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002096 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2097 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2098 if (zOrderRelativeOf == nullptr) return;
2099 if (findInHierarchy(zOrderRelativeOf)) {
2100 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2101 zOrderRelativeOf->mName.c_str());
2102 ALOGE("Severing rel Z loop, potentially dangerous");
2103 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002104 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002105 }
2106 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002107}
2108
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002109
chaviw3277faf2021-05-19 16:45:23 -05002110void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002111 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002112 mDrawingState.touchableRegionCrop =
2113 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002114 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002115 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002116 setTransactionFlags(eTransactionNeeded);
2117}
2118
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002119LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002120 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002121 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002122 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2123
Vishnu Nair00b90132021-11-05 14:03:40 -07002124 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002125 writeCompositionStateToProto(layerProto);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002126 }
2127
chaviw08f3cb22020-01-13 13:17:21 -08002128 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002129 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002130 }
chaviw6d89e2d2020-01-14 14:42:01 -08002131
2132 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002133}
2134
Vishnu Nairea6ff812023-02-27 17:41:39 +00002135void Layer::writeCompositionStateToProto(LayerProto* layerProto) {
2136 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2137
2138 // Only populate for the primary display.
2139 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
2140 const auto compositionType = getCompositionType(*display);
2141 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
2142 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2143 [&]() { return layerProto->mutable_visible_region(); });
2144 }
2145}
2146
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002147void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002148 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002149 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002150 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002151 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002152 [&]() { return layerInfo->mutable_active_buffer(); });
2153 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2154 layerInfo->mutable_buffer_transform());
2155 }
2156 layerInfo->set_invalidate(contentDirty);
2157 layerInfo->set_is_protected(isProtected());
2158 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2159 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002160 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002161 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002162 layerInfo->set_corner_radius(
2163 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002164 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2165 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2166 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2167 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2168 [&]() { return layerInfo->mutable_position(); });
2169 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002170 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2171 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002172
Vishnu Nair00b90132021-11-05 14:03:40 -07002173 if (hasColorTransform()) {
2174 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002175 }
2176
Vishnu Nair60db8c02020-04-02 11:55:16 -07002177 LayerProtoHelper::writeToProto(mSourceBounds,
2178 [&]() { return layerInfo->mutable_source_bounds(); });
2179 LayerProtoHelper::writeToProto(mScreenBounds,
2180 [&]() { return layerInfo->mutable_screen_bounds(); });
2181 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2182 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2183 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002184}
2185
2186void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002187 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002188 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2189 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002190 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002191
chaviw766c9c52021-02-10 17:36:47 -08002192 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002193
Vishnu Nair00b90132021-11-05 14:03:40 -07002194 layerInfo->set_id(sequence);
2195 layerInfo->set_name(getName().c_str());
2196 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002197
Vishnu Nair00b90132021-11-05 14:03:40 -07002198 for (const auto& child : children) {
2199 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002200 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002201
Vishnu Nair00b90132021-11-05 14:03:40 -07002202 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2203 sp<Layer> strongRelative = weakRelative.promote();
2204 if (strongRelative != nullptr) {
2205 layerInfo->add_relatives(strongRelative->sequence);
2206 }
2207 }
2208
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002209 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002210 [&]() { return layerInfo->mutable_transparent_region(); });
2211
2212 layerInfo->set_layer_stack(getLayerStack().id);
2213 layerInfo->set_z(state.z);
2214
2215 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2216 return layerInfo->mutable_requested_position();
2217 });
2218
Vishnu Nair00b90132021-11-05 14:03:40 -07002219 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2220
2221 layerInfo->set_is_opaque(isOpaque(state));
2222
2223 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2224 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2225 LayerProtoHelper::writeToProto(state.color,
2226 [&]() { return layerInfo->mutable_requested_color(); });
2227 layerInfo->set_flags(state.flags);
2228
2229 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2230 layerInfo->mutable_requested_transform());
2231
2232 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2233 if (parent != nullptr) {
2234 layerInfo->set_parent(parent->sequence);
2235 } else {
2236 layerInfo->set_parent(-1);
2237 }
2238
2239 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2240 if (zOrderRelativeOf != nullptr) {
2241 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2242 } else {
2243 layerInfo->set_z_order_relative_of(-1);
2244 }
2245
2246 layerInfo->set_is_relative_of(state.isRelativeOf);
2247
2248 layerInfo->set_owner_uid(mOwnerUid);
2249
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002250 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002251 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002252 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002253 info = fillInputInfo(
2254 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002255 } else {
2256 info = state.inputInfo;
2257 }
2258
2259 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002260 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002261 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002262
Vishnu Nair00b90132021-11-05 14:03:40 -07002263 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002264 auto protoMap = layerInfo->mutable_metadata();
2265 for (const auto& entry : state.metadata.mMap) {
2266 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2267 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002268 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002269
2270 LayerProtoHelper::writeToProto(state.destinationFrame,
2271 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002272}
2273
Robert Carr2e102c92018-10-23 12:11:15 -07002274bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002275 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002276}
2277
Prabir Pradhan33da9462022-06-14 14:55:57 +00002278// Applies the given transform to the region, while protecting against overflows caused by any
2279// offsets. If applying the offset in the transform to any of the Rects in the region would result
2280// in an overflow, they are not added to the output Region.
2281static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2282 const std::string& debugWindowName) {
2283 // Round the translation using the same rounding strategy used by ui::Transform.
2284 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2285 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2286
2287 ui::Transform transformWithoutOffset = t;
2288 transformWithoutOffset.set(0.f, 0.f);
2289
2290 const Region transformed = transformWithoutOffset.transform(r);
2291
2292 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2293 Region ret;
2294 for (const auto& rect : transformed) {
2295 Rect newRect;
2296 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2297 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2298 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2299 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2300 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2301 debugWindowName.c_str());
2302 continue;
2303 }
2304 ret.orSelf(newRect);
2305 }
2306 return ret;
2307}
2308
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002309void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002310 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2311 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002312 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002313 }
2314
Vishnu Nairfed7c122023-03-18 01:54:43 +00002315 const Rect roundedFrameInDisplay = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002316 info.frameLeft = roundedFrameInDisplay.left;
2317 info.frameTop = roundedFrameInDisplay.top;
2318 info.frameRight = roundedFrameInDisplay.right;
2319 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002320
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002321 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002322 inputToLayer.set(inputBounds.left, inputBounds.top);
2323 const ui::Transform layerToScreen = getInputTransform();
2324 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002325
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002326 // InputDispatcher expects a display-to-input transform.
2327 info.transform = inputToDisplay.inverse();
2328
2329 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002330 info.touchableRegion =
2331 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002332}
2333
chaviw3277faf2021-05-19 16:45:23 -05002334void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002335 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002336 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002337 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002338 }
2339 if (p != nullptr) {
2340 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2341 }
2342}
2343
Vishnu Naira066d902021-09-13 18:40:17 -07002344gui::DropInputMode Layer::getDropInputMode() const {
2345 gui::DropInputMode mode = mDrawingState.dropInputMode;
2346 if (mode == gui::DropInputMode::ALL) {
2347 return mode;
2348 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002349 sp<Layer> parent = mDrawingParent.promote();
2350 if (parent) {
2351 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002352 if (parentMode != gui::DropInputMode::NONE) {
2353 return parentMode;
2354 }
2355 }
2356 return mode;
2357}
2358
2359void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002360 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002361 return;
2362 }
2363
2364 // Check if we need to drop input unconditionally
2365 gui::DropInputMode dropInputMode = getDropInputMode();
2366 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002367 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002368 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2369 return;
2370 }
2371
2372 // Check if we need to check if the window is obscured by parent
2373 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2374 return;
2375 }
2376
2377 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002378 sp<Layer> parent = mDrawingParent.promote();
2379 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002380 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002381 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2382 static_cast<float>(getAlpha()));
2383 }
2384
2385 // Check if the parent has cropped the buffer
2386 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2387 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002388 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002389 return;
2390 }
2391
2392 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2393 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2394 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2395 // match then the layer has not been cropped by its parents.
2396 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2397 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2398
2399 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002400 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002401 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2402 getDebugName());
2403 } else {
2404 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2405 // input if the window is obscured. This check should be done in surfaceflinger but the
2406 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2407 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002408 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002409 }
2410}
2411
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002412WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002413 if (!hasInputInfo()) {
2414 mDrawingState.inputInfo.name = getName();
2415 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2416 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002417 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002418 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002419 }
2420
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002421 const ui::Transform& displayTransform =
2422 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2423
chaviw3277faf2021-05-19 16:45:23 -05002424 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002425 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002426 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002427
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002428 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002429
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002430 if (displayArgs.transform == nullptr) {
2431 // Do not let the window receive touches if it is not associated with a valid display
2432 // transform. We still allow the window to receive keys and prevent ANRs.
2433 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2434 }
2435
Robert Carr5dc426e2020-06-10 14:29:14 -07002436 // For compatibility reasons we let layers which can receive input
2437 // receive input before they have actually submitted a buffer. Because
2438 // of this we use canReceiveInput instead of isVisible to check the
2439 // policy-visibility, ignoring the buffer state. However for layers with
2440 // hasInputInfo()==false we can use the real visibility state.
2441 // We are just using these layers for occlusion detection in
2442 // InputDispatcher, and obviously if they aren't visible they can't occlude
2443 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002444 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2445 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2446
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002447 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002448 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002449 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002450
Vishnu Nair16a938f2021-09-24 07:14:54 -07002451 // If the window will be blacked out on a display because the display does not have the secure
2452 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002453 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002454 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002455 }
2456
Vishnu Nairfed7c122023-03-18 01:54:43 +00002457 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002458 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002459 Rect inputBoundsInDisplaySpace;
2460 if (!cropLayer) {
2461 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2462 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2463 } else {
2464 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2465 inputBoundsInDisplaySpace =
2466 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2467 }
2468 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002469 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002470 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2471 Rect inputBoundsInDisplaySpace =
2472 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2473 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002474 }
2475
Winson Chunga30f7c92021-06-29 15:42:56 -07002476 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2477 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002478 if (isTrustedOverlay()) {
2479 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2480 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002481
chaviwaf87b3e2019-10-01 16:59:28 -07002482 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2483 // touches from going outside the cloned area.
2484 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002485 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002486 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2487 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002488 info.touchableRegion = info.touchableRegion.intersect(rect);
2489 }
2490 }
2491
Robert Carr720e5062018-07-30 17:45:14 -07002492 return info;
2493}
2494
Vishnu Nairfed7c122023-03-18 01:54:43 +00002495Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2496 const ui::Transform& screenToDisplay) {
2497 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2498 // frame and transform used for the layer, which determines the bounds and the coordinate space
2499 // within which the layer will receive input.
2500
2501 // Coordinate space definitions:
2502 // - display: The display device's coordinate space. Correlates to pixels on the display.
2503 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2504 // - layer: The coordinate space of this layer.
2505 // - input: The coordinate space in which this layer will receive input events. This could be
2506 // different than layer space if a surfaceInset is used, which changes the origin
2507 // of the input space.
2508
2509 // Crop the input bounds to ensure it is within the parent's bounds.
2510 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2511 const ui::Transform layerToScreen = getInputTransform();
2512 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2513 return Rect{layerToDisplay.transform(croppedInputBounds)};
2514}
2515
chaviwaf87b3e2019-10-01 16:59:28 -07002516sp<Layer> Layer::getClonedRoot() {
2517 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002518 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002519 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002520 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002521 return nullptr;
2522 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002523 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002524}
2525
Robert Carredd13602020-04-13 17:24:34 -07002526bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002527 return mDrawingState.inputInfo.token != nullptr ||
2528 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002529}
2530
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002531compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002532 const DisplayDevice* display) const {
2533 if (!display) return nullptr;
Vishnu Naird47bcee2023-02-24 18:08:51 +00002534 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2535 return display->getCompositionDisplay()->getOutputLayerForLayer(
2536 getCompositionEngineLayerFE());
2537 }
2538 sp<LayerFE> layerFE;
2539 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2540 for (auto& [p, layer] : mLayerFEs) {
2541 if (p == path) {
2542 layerFE = layer;
2543 }
2544 }
2545
2546 if (!layerFE) return nullptr;
2547 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002548}
2549
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002550Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2551 const auto outputLayer = findOutputLayerForDisplay(display);
2552 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002553}
2554
chaviwb4c6e582019-08-16 14:35:07 -07002555void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002556 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002557 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002558 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2559 mPotentialCursor = clonedFrom->mPotentialCursor;
2560 mProtectedByApp = clonedFrom->mProtectedByApp;
2561 updateCloneBufferInfo();
2562}
2563
2564void Layer::updateCloneBufferInfo() {
2565 if (!isClone() || !isClonedFromAlive()) {
2566 return;
2567 }
2568
2569 sp<Layer> clonedFrom = getClonedFrom();
2570 mBufferInfo = clonedFrom->mBufferInfo;
2571 mSidebandStream = clonedFrom->mSidebandStream;
2572 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2573 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2574 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2575
2576 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2577 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2578 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2579 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2580 // the cloned drawingState again.
2581 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2582 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2583 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2584 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2585
2586 cloneDrawingState(clonedFrom.get());
2587
2588 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2589 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2590 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2591 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002592}
chaviw74b03172019-08-19 11:09:03 -07002593
2594void Layer::updateMirrorInfo() {
2595 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2596 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2597 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2598 // that case, we want to delete the reference to the clone since we want it to get
2599 // destroyed. The root, this layer, will still be around since the client can continue
2600 // to hold a reference, but no cloned layers will be displayed.
2601 mClonedChild = nullptr;
2602 return;
2603 }
2604
2605 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2606 // If the real layer exists and is in current state, add the clone as a child of the root.
2607 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2608 // copied to drawingState for the root layer. So the clonedChild is always removed from
2609 // drawingState and then needs to be added back each traversal.
2610 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2611 addChildToDrawing(mClonedChild);
2612 }
2613
2614 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002615 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002616 mClonedChild->updateClonedRelatives(clonedLayersMap);
2617}
2618
2619void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2620 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2621 // to the clone. If the real layer is no longer alive, continue traversing the children
2622 // since we may be able to pull out other children that are still alive.
2623 if (isClonedFromAlive()) {
2624 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002625 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002626 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002627 }
2628
2629 // The clone layer may have children in drawingState since they may have been created and
2630 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2631 // that already exist, since we can just re-use them.
2632 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2633 // not updated in the regular traversal. They are skipped since the root will lose the
2634 // reference to them when it copies its currentChildren to drawing.
2635 for (sp<Layer>& child : mDrawingChildren) {
2636 child->updateClonedDrawingState(clonedLayersMap);
2637 }
2638}
2639
2640void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2641 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2642 mDrawingChildren.clear();
2643
2644 if (!isClonedFromAlive()) {
2645 return;
2646 }
2647
2648 sp<Layer> clonedFrom = getClonedFrom();
2649 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2650 if (child == mirrorRoot) {
2651 // This is to avoid cyclical mirroring.
2652 continue;
2653 }
2654 sp<Layer> clonedChild = clonedLayersMap[child];
2655 if (clonedChild == nullptr) {
2656 clonedChild = child->createClone();
2657 clonedLayersMap[child] = clonedChild;
2658 }
2659 addChildToDrawing(clonedChild);
2660 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2661 }
2662}
2663
chaviwaf87b3e2019-10-01 16:59:28 -07002664void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2665 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2666 if (cropLayer != nullptr) {
2667 if (clonedLayersMap.count(cropLayer) == 0) {
2668 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2669 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002670 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002671 } else {
2672 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2673 mDrawingState.touchableRegionCrop = clonedCropLayer;
2674 }
2675 }
2676 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2677 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002678 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002679}
2680
2681void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002682 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002683 mDrawingState.zOrderRelatives.clear();
2684
2685 if (!isClonedFromAlive()) {
2686 return;
2687 }
2688
chaviwaf87b3e2019-10-01 16:59:28 -07002689 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002690 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002691 const sp<Layer>& relative = relativeWeak.promote();
2692 if (clonedLayersMap.count(relative) > 0) {
2693 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002694 mDrawingState.zOrderRelatives.add(clonedRelative);
2695 }
2696 }
2697
2698 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2699 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2700 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2701 // still traverse the children, but the layer with the missing relativeOf will not be shown
2702 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002703 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2704 if (clonedLayersMap.count(relativeOf) > 0) {
2705 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002706 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2707 }
2708
chaviwaf87b3e2019-10-01 16:59:28 -07002709 updateClonedInputInfo(clonedLayersMap);
2710
chaviw74b03172019-08-19 11:09:03 -07002711 for (sp<Layer>& child : mDrawingChildren) {
2712 child->updateClonedRelatives(clonedLayersMap);
2713 }
2714}
2715
2716void Layer::addChildToDrawing(const sp<Layer>& layer) {
2717 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002718 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002719}
2720
Steven Thomas62a4cf82020-01-31 12:04:03 -08002721Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2722 switch (compatibility) {
2723 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2724 return FrameRateCompatibility::Default;
2725 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2726 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002727 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2728 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002729 case ANATIVEWINDOW_FRAME_RATE_MIN:
2730 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002731 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2732 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002733 default:
2734 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2735 return FrameRateCompatibility::Default;
2736 }
2737}
2738
Marin Shalamanovc5986772021-03-16 16:09:49 +01002739scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2740 switch (strategy) {
2741 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2742 return Seamlessness::OnlySeamless;
2743 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2744 return Seamlessness::SeamedAndSeamless;
2745 default:
2746 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2747 return Seamlessness::Default;
2748 }
2749}
2750
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002751bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002752 const State& s(mDrawingState);
2753 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2754 return true;
2755 }
2756
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002757 sp<Layer> parent = mDrawingParent.promote();
2758 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002759}
2760
Robert Carr6a0382d2021-07-01 15:57:17 -07002761void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2762 mClonedChild = clonedChild;
2763 mHadClonedChild = true;
2764 mFlinger->mNumClones++;
2765}
2766
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002767bool Layer::setDropInputMode(gui::DropInputMode mode) {
2768 if (mDrawingState.dropInputMode == mode) {
2769 return false;
2770 }
2771 mDrawingState.dropInputMode = mode;
2772 return true;
2773}
2774
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002775void Layer::cloneDrawingState(const Layer* from) {
2776 mDrawingState = from->mDrawingState;
2777 // Skip callback info since they are not applicable for cloned layers.
2778 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002779 // TODO (b/238781169) currently broken for mirror layers because we do not
2780 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002781 mDrawingState.callbackHandles = {};
2782}
2783
Patrick Williamsbb25f802022-08-30 23:02:34 +00002784void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2785 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002786 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002787 if (!listener) {
2788 return;
2789 }
2790 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002791 uint32_t currentMaxAcquiredBufferCount =
2792 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002793 listener->onReleaseBuffer({buffer->getId(), framenumber},
2794 releaseFence ? releaseFence : Fence::NO_FENCE,
2795 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002796}
2797
2798void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2799 // If we are displayed on multiple displays in a single composition cycle then we would
2800 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2801 // For example we can only use it if all the displays are client comp, and we need
2802 // to merge all the client comp fences. We could do this, but for now we just
2803 // disable the optimization when a layer is composed on multiple displays.
2804 if (mClearClientCompositionFenceOnLayerDisplayed) {
2805 mLastClientCompositionFence = nullptr;
2806 } else {
2807 mClearClientCompositionFenceOnLayerDisplayed = true;
2808 }
2809
2810 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2811 // buffer that was presented on this layer. The first transaction that came in this frame that
2812 // replaced the previous buffer on this layer needs this release fence, because the fence will
2813 // let the client know when that previous buffer is removed from the screen.
2814 //
2815 // Every other transaction on this layer does not need a release fence because no other
2816 // Transactions that were set on this layer this frame are going to have their preceding buffer
2817 // removed from the display this frame.
2818 //
2819 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2820 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2821 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2822 // the previous buffer will be released this frame. The third transaction also contains a
2823 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2824 // transaction will now no longer be presented so it is released immediately and the third
2825 // transaction doesn't need a previous release fence.
2826 sp<CallbackHandle> ch;
2827 for (auto& handle : mDrawingState.callbackHandles) {
2828 if (handle->releasePreviousBuffer &&
2829 mDrawingState.releaseBufferEndpoint == handle->listener) {
2830 ch = handle;
2831 break;
2832 }
2833 }
2834
2835 // Prevent tracing the same release multiple times.
2836 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2837 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2838 }
2839
2840 if (ch != nullptr) {
2841 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2842 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2843 ch->name = mName;
2844 }
2845}
2846
2847void Layer::onSurfaceFrameCreated(
2848 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2849 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2850 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2851 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2852 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002853 if (hasBufferOrSidebandStreamInDrawing()) {
2854 // Only log for layers with a buffer, since we expect the jank data to be drained for
2855 // these, while there may be no jank listeners for bufferless layers.
2856 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2857 mName.c_str());
2858 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2859 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2860 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002861 mPendingJankClassifications.pop_front();
2862 }
2863 mPendingJankClassifications.emplace_back(surfaceFrame);
2864}
2865
2866void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2867 for (const auto& handle : mDrawingState.callbackHandles) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -07002868 if (mFlinger->mLayerLifecycleManagerEnabled) {
2869 handle->transformHint = mTransformHint;
2870 } else {
2871 handle->transformHint = mSkipReportingTransformHint
2872 ? std::nullopt
2873 : std::make_optional<uint32_t>(mTransformHintLegacy);
2874 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002875 handle->dequeueReadyTime = dequeueReadyTime;
2876 handle->currentMaxAcquiredBufferCount =
2877 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2878 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2879 handle->previousReleaseCallbackId.framenumber);
2880 }
2881
2882 for (auto& handle : mDrawingState.callbackHandles) {
2883 if (handle->releasePreviousBuffer &&
2884 mDrawingState.releaseBufferEndpoint == handle->listener) {
2885 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2886 break;
2887 }
2888 }
2889
2890 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002891 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002892 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2893 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002894 mDrawingState.callbackHandles = {};
2895}
2896
2897bool Layer::willPresentCurrentTransaction() const {
2898 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2899 return (getSidebandStreamChanged() || getAutoRefresh() ||
2900 (mDrawingState.modified &&
2901 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2902}
2903
2904bool Layer::setTransform(uint32_t transform) {
2905 if (mDrawingState.bufferTransform == transform) return false;
2906 mDrawingState.bufferTransform = transform;
2907 mDrawingState.modified = true;
2908 setTransactionFlags(eTransactionNeeded);
2909 return true;
2910}
2911
2912bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2913 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2914 mDrawingState.sequence++;
2915 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2916 mDrawingState.modified = true;
2917 setTransactionFlags(eTransactionNeeded);
2918 return true;
2919}
2920
2921bool Layer::setBufferCrop(const Rect& bufferCrop) {
2922 if (mDrawingState.bufferCrop == bufferCrop) return false;
2923
2924 mDrawingState.sequence++;
2925 mDrawingState.bufferCrop = bufferCrop;
2926
2927 mDrawingState.modified = true;
2928 setTransactionFlags(eTransactionNeeded);
2929 return true;
2930}
2931
2932bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2933 if (mDrawingState.destinationFrame == destinationFrame) return false;
2934
2935 mDrawingState.sequence++;
2936 mDrawingState.destinationFrame = destinationFrame;
2937
2938 mDrawingState.modified = true;
2939 setTransactionFlags(eTransactionNeeded);
2940 return true;
2941}
2942
2943// Translate destination frame into scale and position. If a destination frame is not set, use the
2944// provided scale and position
2945bool Layer::updateGeometry() {
2946 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2947 mDrawingState.destinationFrame.isEmpty()) {
2948 // If destination frame is not set, use the requested transform set via
2949 // Layer::setPosition and Layer::setMatrix.
2950 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2951 }
2952
2953 Rect destRect = mDrawingState.destinationFrame;
2954 int32_t destW = destRect.width();
2955 int32_t destH = destRect.height();
2956 if (destRect.left < 0) {
2957 destRect.left = 0;
2958 destRect.right = destW;
2959 }
2960 if (destRect.top < 0) {
2961 destRect.top = 0;
2962 destRect.bottom = destH;
2963 }
2964
2965 if (!mDrawingState.buffer) {
2966 ui::Transform t;
2967 t.set(destRect.left, destRect.top);
2968 return assignTransform(&mDrawingState.transform, t);
2969 }
2970
2971 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2972 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2973 // Undo any transformations on the buffer.
2974 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2975 std::swap(bufferWidth, bufferHeight);
2976 }
2977 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
2978 if (mDrawingState.transformToDisplayInverse) {
2979 if (invTransform & ui::Transform::ROT_90) {
2980 std::swap(bufferWidth, bufferHeight);
2981 }
2982 }
2983
2984 float sx = destW / static_cast<float>(bufferWidth);
2985 float sy = destH / static_cast<float>(bufferHeight);
2986 ui::Transform t;
2987 t.set(sx, 0, 0, sy);
2988 t.set(destRect.left, destRect.top);
2989 return assignTransform(&mDrawingState.transform, t);
2990}
2991
2992bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
2993 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
2994 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
2995 return false;
2996 }
2997
2998 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
2999
3000 mDrawingState.sequence++;
3001 mDrawingState.modified = true;
3002 setTransactionFlags(eTransactionNeeded);
3003
3004 return true;
3005}
3006
3007bool Layer::setPosition(float x, float y) {
3008 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3009 return false;
3010 }
3011
3012 mRequestedTransform.set(x, y);
3013
3014 mDrawingState.sequence++;
3015 mDrawingState.modified = true;
3016 setTransactionFlags(eTransactionNeeded);
3017
3018 return true;
3019}
3020
3021bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3022 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3023 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003024 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003025 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003026 if (!buffer) {
3027 return false;
3028 }
3029
3030 const bool frameNumberChanged =
3031 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3032 const uint64_t frameNumber =
3033 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003034 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003035
3036 if (mDrawingState.buffer) {
3037 mReleasePreviousBuffer = true;
3038 if (!mBufferInfo.mBuffer ||
3039 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3040 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3041 // If mDrawingState has a buffer, and we are about to update again
3042 // before swapping to drawing state, then the first buffer will be
3043 // dropped and we should decrement the pending buffer count and
3044 // call any release buffer callbacks if set.
3045 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3046 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003047 mDrawingState.acquireFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003048 decrementPendingBufferCount();
3049 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3050 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3051 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
3052 mDrawingState.bufferSurfaceFrameTX.reset();
3053 }
3054 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3055 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3056 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003057 mLastClientCompositionFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003058 mLastClientCompositionFence = nullptr;
3059 }
Vishnu Nairc09c0232023-03-02 03:22:35 +00003060 } else {
3061 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3062 // we don't want to incorrectly classify a frame if we miss the desired present time.
3063 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003064 }
3065
liulijuneb489f62022-10-17 22:02:14 +08003066 mDrawingState.producerId = bufferData.producerId;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003067 mDrawingState.frameNumber = frameNumber;
3068 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3069 mDrawingState.buffer = std::move(buffer);
3070 mDrawingState.clientCacheId = bufferData.cachedBuffer;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003071 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3072 ? bufferData.acquireFence
3073 : Fence::NO_FENCE;
3074 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3075 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3076 // We latched this buffer unsiganled, so we need to pass the acquire fence
3077 // on the callback instead of just the acquire time, since it's unknown at
3078 // this point.
3079 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3080 } else {
3081 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3082 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003083 mDrawingState.latchedVsyncId = info.vsyncId;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003084 mDrawingState.modified = true;
3085 setTransactionFlags(eTransactionNeeded);
3086
3087 const int32_t layerId = getSequence();
3088 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3089 mOwnerUid, postTime, getGameMode());
3090 mDrawingState.desiredPresentTime = desiredPresentTime;
3091 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3092
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003093 if (mFlinger->mLegacyFrontEndEnabled) {
3094 recordLayerHistoryBufferUpdate(getLayerProps());
3095 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003096
3097 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3098
3099 if (dequeueTime && *dequeueTime != 0) {
3100 const uint64_t bufferId = mDrawingState.buffer->getId();
3101 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3102 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3103 FrameTracer::FrameEvent::DEQUEUE);
3104 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3105 FrameTracer::FrameEvent::QUEUE);
3106 }
3107
3108 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3109 return true;
3110}
3111
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003112void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3113 mDrawingState.desiredPresentTime = desiredPresentTime;
3114 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3115}
3116
3117void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps) {
3118 const nsecs_t presentTime = [&] {
3119 if (!mDrawingState.isAutoTimestamp) return mDrawingState.desiredPresentTime;
3120
3121 const auto prediction = mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3122 mDrawingState.latchedVsyncId);
3123 if (prediction.has_value()) return prediction->presentTime;
3124
3125 return static_cast<nsecs_t>(0);
3126 }();
3127 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3128 scheduler::LayerHistory::LayerUpdateType::Buffer);
3129}
3130
3131void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps) {
3132 const nsecs_t presentTime =
3133 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
3134 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3135 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3136}
3137
Patrick Williamsbb25f802022-08-30 23:02:34 +00003138bool Layer::setDataspace(ui::Dataspace dataspace) {
3139 mDrawingState.dataspaceRequested = true;
3140 if (mDrawingState.dataspace == dataspace) return false;
3141 mDrawingState.dataspace = dataspace;
3142 mDrawingState.modified = true;
3143 setTransactionFlags(eTransactionNeeded);
3144 return true;
3145}
3146
John Reck68796592023-01-25 13:47:12 -05003147bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
3148 if (mDrawingState.currentSdrHdrRatio == currentBufferRatio &&
3149 mDrawingState.desiredSdrHdrRatio == desiredRatio)
3150 return false;
3151 mDrawingState.currentSdrHdrRatio = currentBufferRatio;
3152 mDrawingState.desiredSdrHdrRatio = desiredRatio;
3153 mDrawingState.modified = true;
3154 setTransactionFlags(eTransactionNeeded);
3155 return true;
3156}
3157
Alec Mourif4af03e2023-02-11 00:25:24 +00003158bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3159 if (mDrawingState.cachingHint == cachingHint) return false;
3160 mDrawingState.cachingHint = cachingHint;
3161 mDrawingState.modified = true;
3162 setTransactionFlags(eTransactionNeeded);
3163 return true;
3164}
3165
Patrick Williamsbb25f802022-08-30 23:02:34 +00003166bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3167 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3168 mDrawingState.hdrMetadata = hdrMetadata;
3169 mDrawingState.modified = true;
3170 setTransactionFlags(eTransactionNeeded);
3171 return true;
3172}
3173
3174bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003175 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003176 mDrawingState.surfaceDamageRegion = surfaceDamage;
3177 mDrawingState.modified = true;
3178 setTransactionFlags(eTransactionNeeded);
3179 return true;
3180}
3181
3182bool Layer::setApi(int32_t api) {
3183 if (mDrawingState.api == api) return false;
3184 mDrawingState.api = api;
3185 mDrawingState.modified = true;
3186 setTransactionFlags(eTransactionNeeded);
3187 return true;
3188}
3189
3190bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3191 if (mDrawingState.sidebandStream == sidebandStream) return false;
3192
3193 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3194 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3195 } else if (sidebandStream != nullptr) {
3196 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3197 }
3198
3199 mDrawingState.sidebandStream = sidebandStream;
3200 mDrawingState.modified = true;
3201 setTransactionFlags(eTransactionNeeded);
3202 if (!mSidebandStreamChanged.exchange(true)) {
3203 // mSidebandStreamChanged was false
3204 mFlinger->onLayerUpdate();
3205 }
3206 return true;
3207}
3208
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003209bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3210 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003211 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3212 if (handles.empty()) {
3213 mReleasePreviousBuffer = false;
3214 return false;
3215 }
3216
Pascal Muetschard81cef292023-02-06 12:18:52 +01003217 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003218 for (const auto& handle : handles) {
3219 // If this transaction set a buffer on this layer, release its previous buffer
3220 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3221
3222 // If this layer will be presented in this frame
3223 if (willPresent) {
3224 // If this transaction set an acquire fence on this layer, set its acquire time
3225 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3226 handle->frameNumber = mDrawingState.frameNumber;
3227
3228 // Store so latched time and release fence can be set
3229 mDrawingState.callbackHandles.push_back(handle);
3230
3231 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003232 // Queue this handle to be notified below.
3233 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003234 }
3235 }
3236
Pascal Muetschard81cef292023-02-06 12:18:52 +01003237 if (!remainingHandles.empty()) {
3238 // Notify the transaction completed threads these handles are done. These are only the
3239 // handles that were not added to the mDrawingState, which will be notified later.
3240 std::vector<JankData> jankData;
3241 transferAvailableJankData(remainingHandles, jankData);
3242 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3243 }
3244
Patrick Williamsbb25f802022-08-30 23:02:34 +00003245 mReleasePreviousBuffer = false;
3246 mCallbackHandleAcquireTimeOrFence = -1;
3247
3248 return willPresent;
3249}
3250
3251Rect Layer::getBufferSize(const State& /*s*/) const {
3252 // for buffer state layers we use the display frame size as the buffer size.
3253
3254 if (mBufferInfo.mBuffer == nullptr) {
3255 return Rect::INVALID_RECT;
3256 }
3257
3258 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3259 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3260
3261 // Undo any transformations on the buffer and return the result.
3262 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3263 std::swap(bufWidth, bufHeight);
3264 }
3265
3266 if (getTransformToDisplayInverse()) {
3267 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3268 if (invTransform & ui::Transform::ROT_90) {
3269 std::swap(bufWidth, bufHeight);
3270 }
3271 }
3272
3273 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3274}
3275
3276FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3277 if (mBufferInfo.mBuffer == nullptr) {
3278 return parentBounds;
3279 }
3280
3281 return getBufferSize(getDrawingState()).toFloatRect();
3282}
3283
3284bool Layer::fenceHasSignaled() const {
3285 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3286 return true;
3287 }
3288
3289 const bool fenceSignaled =
3290 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3291 if (!fenceSignaled) {
3292 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3293 TimeStats::LatchSkipReason::LateAcquire);
3294 }
3295
3296 return fenceSignaled;
3297}
3298
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003299void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003300 for (const auto& handle : mDrawingState.callbackHandles) {
3301 handle->refreshStartTime = refreshStartTime;
3302 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003303}
3304
3305void Layer::setAutoRefresh(bool autoRefresh) {
3306 mDrawingState.autoRefresh = autoRefresh;
3307}
3308
3309bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3310 // 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 +00003311 auto* snapshot = editLayerSnapshot();
3312 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003313
3314 if (mSidebandStreamChanged.exchange(false)) {
3315 const State& s(getDrawingState());
3316 // mSidebandStreamChanged was true
3317 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003318 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003319 if (mSidebandStream != nullptr) {
3320 setTransactionFlags(eTransactionNeeded);
3321 mFlinger->setTransactionFlags(eTraversalNeeded);
3322 }
3323 recomputeVisibleRegions = true;
3324
3325 return true;
3326 }
3327 return false;
3328}
3329
3330bool Layer::hasFrameUpdate() const {
3331 const State& c(getDrawingState());
3332 return (mDrawingStateModified || mDrawingState.modified) &&
3333 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3334}
3335
Vishnu Naird47bcee2023-02-24 18:08:51 +00003336void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003337 const State& s(getDrawingState());
3338
3339 if (!s.buffer) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003340 if (bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003341 for (auto& handle : mDrawingState.callbackHandles) {
3342 handle->latchTime = latchTime;
3343 }
3344 }
3345 return;
3346 }
3347
3348 for (auto& handle : mDrawingState.callbackHandles) {
3349 if (handle->frameNumber == mDrawingState.frameNumber) {
3350 handle->latchTime = latchTime;
3351 }
3352 }
3353
3354 const int32_t layerId = getSequence();
3355 const uint64_t bufferId = mDrawingState.buffer->getId();
3356 const uint64_t frameNumber = mDrawingState.frameNumber;
3357 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3358 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3359 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3360
3361 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3362 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3363 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3364 FrameTracer::FrameEvent::LATCH);
3365
3366 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3367 if (bufferSurfaceFrame != nullptr &&
3368 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3369 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3370 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3371 // are processing the next state.
3372 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3373 mDrawingState.acquireFenceTime->getSignalTime(),
3374 latchTime);
3375 mDrawingState.bufferSurfaceFrameTX.reset();
3376 }
3377
3378 std::deque<sp<CallbackHandle>> remainingHandles;
3379 mFlinger->getTransactionCallbackInvoker()
3380 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3381 mDrawingState.callbackHandles = remainingHandles;
3382
3383 mDrawingStateModified = false;
3384}
3385
3386void Layer::gatherBufferInfo() {
3387 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3388 decrementPendingBufferCount();
3389 }
3390
3391 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3392 mBufferInfo.mBuffer = mDrawingState.buffer;
3393 mBufferInfo.mFence = mDrawingState.acquireFence;
3394 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3395 mBufferInfo.mPixelFormat =
3396 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3397 mBufferInfo.mFrameLatencyNeeded = true;
3398 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3399 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3400 mBufferInfo.mFence = mDrawingState.acquireFence;
3401 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3402 auto lastDataspace = mBufferInfo.mDataspace;
3403 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3404 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003405 mFlinger->mHdrLayerInfoChanged = true;
3406 }
3407 if (mBufferInfo.mDesiredSdrHdrRatio != mDrawingState.desiredSdrHdrRatio) {
3408 mBufferInfo.mDesiredSdrHdrRatio = mDrawingState.desiredSdrHdrRatio;
3409 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003410 }
3411 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3412 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3413 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3414 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3415 mBufferInfo.mApi = mDrawingState.api;
3416 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003417}
3418
3419Rect Layer::computeBufferCrop(const State& s) {
3420 if (s.buffer && !s.bufferCrop.isEmpty()) {
3421 Rect bufferCrop;
3422 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3423 return bufferCrop;
3424 } else if (s.buffer) {
3425 return s.buffer->getBounds();
3426 } else {
3427 return s.bufferCrop;
3428 }
3429}
3430
3431sp<Layer> Layer::createClone() {
3432 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3433 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003434 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003435 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3436 return layer;
3437}
3438
Patrick Williamsbb25f802022-08-30 23:02:34 +00003439void Layer::decrementPendingBufferCount() {
3440 int32_t pendingBuffers = --mPendingBufferTransactions;
3441 tracePendingBufferCount(pendingBuffers);
3442}
3443
3444void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3445 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3446}
3447
3448/*
3449 * We don't want to send the layer's transform to input, but rather the
3450 * parent's transform. This is because Layer's transform is
3451 * information about how the buffer is placed on screen. The parent's
3452 * transform makes more sense to send since it's information about how the
3453 * layer is placed on screen. This transform is used by input to determine
3454 * how to go from screen space back to window space.
3455 */
3456ui::Transform Layer::getInputTransform() const {
3457 if (!hasBufferOrSidebandStream()) {
3458 return getTransform();
3459 }
3460 sp<Layer> parent = mDrawingParent.promote();
3461 if (parent == nullptr) {
3462 return ui::Transform();
3463 }
3464
3465 return parent->getTransform();
3466}
3467
3468/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003469 * Returns the bounds used to fill the input frame and the touchable region.
3470 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003471 * Similar to getInputTransform, we need to update the bounds to include the transform.
3472 * This is because bounds don't include the buffer transform, where the input assumes
3473 * that's already included.
3474 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003475std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3476 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3477 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3478 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3479 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3480 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003481 }
3482
Vishnu Nairfed7c122023-03-18 01:54:43 +00003483 bool inputBoundsValid = croppedBufferSize.isValid();
3484 if (!inputBoundsValid) {
3485 /**
3486 * Input bounds are based on the layer crop or buffer size. But if we are using
3487 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3488 * we can use the parent bounds as the input bounds if the layer does not have buffer
3489 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3490 * use the parent bounds. A layer without a buffer can get input. So when a window is
3491 * initially added, its touchable region can fill its parent layer bounds and that can
3492 * have negative consequences.
3493 */
3494 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003495 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003496
3497 // Clamp surface inset to the input bounds.
3498 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3499 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3500 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3501
3502 // Apply the insets to the input bounds.
3503 inputBounds.left += xSurfaceInset;
3504 inputBounds.top += ySurfaceInset;
3505 inputBounds.right -= xSurfaceInset;
3506 inputBounds.bottom -= ySurfaceInset;
3507
3508 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003509}
3510
3511bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3512 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3513
3514 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3515 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3516 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3517 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3518 layer_state_t::eReparent;
3519
3520 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3521 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3522 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3523 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3524 layer_state_t::eInputInfoChanged;
3525
3526 if ((s.what & requiredFlags) != requiredFlags) {
3527 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3528 (s.what | requiredFlags) & ~s.what);
3529 return false;
3530 }
3531
3532 if (s.what & deniedFlags) {
3533 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3534 return false;
3535 }
3536
3537 if (s.what & allowedFlags) {
3538 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3539 }
3540
3541 if (s.what & layer_state_t::ePositionChanged) {
3542 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3543 ALOGV("%s: false [ePositionChanged changed]", __func__);
3544 return false;
3545 }
3546 }
3547
3548 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003549 if (mDrawingState.color.a != s.color.a) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003550 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3551 return false;
3552 }
3553 }
3554
3555 if (s.what & layer_state_t::eColorTransformChanged) {
3556 if (mDrawingState.colorTransform != s.colorTransform) {
3557 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3558 return false;
3559 }
3560 }
3561
3562 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003563 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003564 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3565 return false;
3566 }
3567 }
3568
3569 if (s.what & layer_state_t::eMatrixChanged) {
3570 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3571 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3572 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3573 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3574 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3575 return false;
3576 }
3577 }
3578
3579 if (s.what & layer_state_t::eCornerRadiusChanged) {
3580 if (mDrawingState.cornerRadius != s.cornerRadius) {
3581 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3582 return false;
3583 }
3584 }
3585
3586 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3587 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3588 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3589 return false;
3590 }
3591 }
3592
Vishnu Nairbbceb462022-10-10 04:52:13 +00003593 if (s.what & layer_state_t::eBufferTransformChanged) {
3594 if (mDrawingState.bufferTransform != s.bufferTransform) {
3595 ALOGV("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003596 return false;
3597 }
3598 }
3599
3600 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3601 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3602 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3603 return false;
3604 }
3605 }
3606
3607 if (s.what & layer_state_t::eCropChanged) {
3608 if (mDrawingState.crop != s.crop) {
3609 ALOGV("%s: false [eCropChanged changed]", __func__);
3610 return false;
3611 }
3612 }
3613
3614 if (s.what & layer_state_t::eDataspaceChanged) {
3615 if (mDrawingState.dataspace != s.dataspace) {
3616 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3617 return false;
3618 }
3619 }
3620
3621 if (s.what & layer_state_t::eHdrMetadataChanged) {
3622 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3623 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3624 return false;
3625 }
3626 }
3627
3628 if (s.what & layer_state_t::eSidebandStreamChanged) {
3629 if (mDrawingState.sidebandStream != s.sidebandStream) {
3630 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3631 return false;
3632 }
3633 }
3634
3635 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3636 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3637 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3638 return false;
3639 }
3640 }
3641
3642 if (s.what & layer_state_t::eShadowRadiusChanged) {
3643 if (mDrawingState.shadowRadius != s.shadowRadius) {
3644 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3645 return false;
3646 }
3647 }
3648
3649 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3650 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3651 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3652 return false;
3653 }
3654 }
3655
3656 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3657 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3658 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3659 return false;
3660 }
3661 }
3662
3663 if (s.what & layer_state_t::eStretchChanged) {
3664 StretchEffect temp = s.stretchEffect;
3665 temp.sanitize();
3666 if (mDrawingState.stretchEffect != temp) {
3667 ALOGV("%s: false [eStretchChanged changed]", __func__);
3668 return false;
3669 }
3670 }
3671
3672 if (s.what & layer_state_t::eBufferCropChanged) {
3673 if (mDrawingState.bufferCrop != s.bufferCrop) {
3674 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3675 return false;
3676 }
3677 }
3678
3679 if (s.what & layer_state_t::eDestinationFrameChanged) {
3680 if (mDrawingState.destinationFrame != s.destinationFrame) {
3681 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3682 return false;
3683 }
3684 }
3685
3686 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3687 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3688 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3689 return false;
3690 }
3691 }
3692
John Reck68796592023-01-25 13:47:12 -05003693 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
3694 if (mDrawingState.currentSdrHdrRatio != s.currentSdrHdrRatio ||
3695 mDrawingState.desiredSdrHdrRatio != s.desiredSdrHdrRatio) {
3696 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3697 return false;
3698 }
3699 }
3700
Patrick Williamsbb25f802022-08-30 23:02:34 +00003701 ALOGV("%s: true", __func__);
3702 return true;
3703}
3704
3705bool Layer::isHdrY410() const {
3706 // pixel format is HDR Y410 masquerading as RGBA_1010102
3707 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3708 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3709 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3710}
3711
Vishnu Naire14c6b32022-08-06 04:20:15 +00003712sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003713 // 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 +00003714 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003715}
3716
Vishnu Naire14c6b32022-08-06 04:20:15 +00003717const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003718 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003719}
3720
Vishnu Naire14c6b32022-08-06 04:20:15 +00003721LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003722 return mSnapshot.get();
3723}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003724
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003725std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3726 return std::move(mSnapshot);
3727}
3728
3729void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3730 mSnapshot = std::move(snapshot);
3731}
3732
Patrick Williamsbb25f802022-08-30 23:02:34 +00003733const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003734 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003735}
3736
Patrick Williams7584c6a2022-10-29 02:10:58 +00003737sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003738 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003739 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3740 return result;
3741}
3742
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003743sp<LayerFE> Layer::getCompositionEngineLayerFE(
3744 const frontend::LayerHierarchy::TraversalPath& path) {
3745 for (auto& [p, layerFE] : mLayerFEs) {
3746 if (p == path) {
3747 return layerFE;
3748 }
3749 }
3750 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3751 mLayerFEs.emplace_back(path, layerFE);
3752 return layerFE;
3753}
3754
Patrick Williamsbb25f802022-08-30 23:02:34 +00003755void Layer::useSurfaceDamage() {
3756 if (mFlinger->mForceFullDamage) {
3757 surfaceDamageRegion = Region::INVALID_REGION;
3758 } else {
3759 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3760 }
3761}
3762
3763void Layer::useEmptyDamage() {
3764 surfaceDamageRegion.clear();
3765}
3766
3767bool Layer::isOpaque(const Layer::State& s) const {
3768 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3769 // layer's opaque flag.
3770 if (!hasSomethingToDraw()) {
3771 return false;
3772 }
3773
3774 // if the layer has the opaque flag, then we're always opaque
3775 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3776 return true;
3777 }
3778
3779 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003780 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003781 return true;
3782 }
3783
3784 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3785 return fillsColor() && getAlpha() == 1.0_hf;
3786}
3787
3788bool Layer::canReceiveInput() const {
3789 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3790}
3791
3792bool Layer::isVisible() const {
3793 if (!hasSomethingToDraw()) {
3794 return false;
3795 }
3796
3797 if (isHiddenByPolicy()) {
3798 return false;
3799 }
3800
3801 return getAlpha() > 0.0f || hasBlur();
3802}
3803
3804void Layer::onPostComposition(const DisplayDevice* display,
3805 const std::shared_ptr<FenceTime>& glDoneFence,
3806 const std::shared_ptr<FenceTime>& presentFence,
3807 const CompositorTiming& compositorTiming) {
3808 // mFrameLatencyNeeded is true when a new frame was latched for the
3809 // composition.
3810 if (!mBufferInfo.mFrameLatencyNeeded) return;
3811
3812 for (const auto& handle : mDrawingState.callbackHandles) {
3813 handle->gpuCompositionDoneFence = glDoneFence;
3814 handle->compositorTiming = compositorTiming;
3815 }
3816
3817 // Update mFrameTracker.
3818 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3819 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3820
3821 const int32_t layerId = getSequence();
3822 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3823
3824 const auto outputLayer = findOutputLayerForDisplay(display);
3825 if (outputLayer && outputLayer->requiresClientComposition()) {
3826 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3827 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3828 clientCompositionTimestamp,
3829 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3830 // Update the SurfaceFrames in the drawing state
3831 if (mDrawingState.bufferSurfaceFrameTX) {
3832 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3833 }
3834 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3835 surfaceFrame->setGpuComposition();
3836 }
3837 }
3838
3839 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3840 if (frameReadyFence->isValid()) {
3841 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3842 } else {
3843 // There was no fence for this frame, so assume that it was ready
3844 // to be presented at the desired present time.
3845 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3846 }
3847
3848 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08003849 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003850 const std::optional<Fps> renderRate =
3851 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3852
3853 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3854 const auto gameMode = getGameMode();
3855
3856 if (presentFence->isValid()) {
3857 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3858 refreshRate, renderRate, vote, gameMode);
3859 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3860 presentFence,
3861 FrameTracer::FrameEvent::PRESENT_FENCE);
3862 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3863 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3864 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003865 // The HWC doesn't support present fences, so use the present timestamp instead.
3866 const nsecs_t presentTimestamp =
3867 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3868
3869 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3870 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3871 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3872
Patrick Williamsbb25f802022-08-30 23:02:34 +00003873 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3874 refreshRate, renderRate, vote, gameMode);
3875 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3876 mCurrentFrameNumber, actualPresentTime,
3877 FrameTracer::FrameEvent::PRESENT_FENCE);
3878 mFrameTracker.setActualPresentTime(actualPresentTime);
3879 }
3880 }
3881
3882 mFrameTracker.advanceFrame();
3883 mBufferInfo.mFrameLatencyNeeded = false;
3884}
3885
3886bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003887 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
3888 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
3889}
3890
3891bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003892 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3893 getDrawingState().frameNumber);
3894
3895 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3896
3897 if (refreshRequired) {
3898 return refreshRequired;
3899 }
3900
3901 // If the head buffer's acquire fence hasn't signaled yet, return and
3902 // try again later
3903 if (!fenceHasSignaled()) {
3904 ATRACE_NAME("!fenceHasSignaled()");
3905 mFlinger->onLayerUpdate();
3906 return false;
3907 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00003908 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003909 if (mDrawingState.buffer == nullptr) {
3910 return false;
3911 }
3912
3913 // Capture the old state of the layer for comparisons later
3914 BufferInfo oldBufferInfo = mBufferInfo;
3915 const bool oldOpacity = isOpaque(mDrawingState);
3916 mPreviousFrameNumber = mCurrentFrameNumber;
3917 mCurrentFrameNumber = mDrawingState.frameNumber;
3918 gatherBufferInfo();
3919
3920 if (oldBufferInfo.mBuffer == nullptr) {
3921 // the first time we receive a buffer, we need to trigger a
3922 // geometry invalidation.
3923 recomputeVisibleRegions = true;
3924 }
3925
3926 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3927 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3928 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3929 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3930 recomputeVisibleRegions = true;
3931 }
3932
3933 if (oldBufferInfo.mBuffer != nullptr) {
3934 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3935 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3936 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3937 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3938 recomputeVisibleRegions = true;
3939 }
3940 }
3941
3942 if (oldOpacity != isOpaque(mDrawingState)) {
3943 recomputeVisibleRegions = true;
3944 }
3945
3946 return true;
3947}
3948
3949bool Layer::hasReadyFrame() const {
3950 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
3951}
3952
3953bool Layer::isProtected() const {
3954 return (mBufferInfo.mBuffer != nullptr) &&
3955 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
3956}
3957
Patrick Williamsbb25f802022-08-30 23:02:34 +00003958void Layer::latchAndReleaseBuffer() {
3959 if (hasReadyFrame()) {
3960 bool ignored = false;
3961 latchBuffer(ignored, systemTime());
3962 }
3963 releasePendingBuffer(systemTime());
3964}
3965
3966PixelFormat Layer::getPixelFormat() const {
3967 return mBufferInfo.mPixelFormat;
3968}
3969
3970bool Layer::getTransformToDisplayInverse() const {
3971 return mBufferInfo.mTransformToDisplayInverse;
3972}
3973
3974Rect Layer::getBufferCrop() const {
3975 // this is the crop rectangle that applies to the buffer
3976 // itself (as opposed to the window)
3977 if (!mBufferInfo.mCrop.isEmpty()) {
3978 // if the buffer crop is defined, we use that
3979 return mBufferInfo.mCrop;
3980 } else if (mBufferInfo.mBuffer != nullptr) {
3981 // otherwise we use the whole buffer
3982 return mBufferInfo.mBuffer->getBounds();
3983 } else {
3984 // if we don't have a buffer yet, we use an empty/invalid crop
3985 return Rect();
3986 }
3987}
3988
3989uint32_t Layer::getBufferTransform() const {
3990 return mBufferInfo.mTransform;
3991}
3992
3993ui::Dataspace Layer::getDataSpace() const {
3994 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
3995}
3996
3997ui::Dataspace Layer::getRequestedDataSpace() const {
3998 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
3999}
4000
4001ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4002 ui::Dataspace updatedDataspace = dataspace;
4003 // translate legacy dataspaces to modern dataspaces
4004 switch (dataspace) {
4005 case ui::Dataspace::SRGB:
4006 updatedDataspace = ui::Dataspace::V0_SRGB;
4007 break;
4008 case ui::Dataspace::SRGB_LINEAR:
4009 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4010 break;
4011 case ui::Dataspace::JFIF:
4012 updatedDataspace = ui::Dataspace::V0_JFIF;
4013 break;
4014 case ui::Dataspace::BT601_625:
4015 updatedDataspace = ui::Dataspace::V0_BT601_625;
4016 break;
4017 case ui::Dataspace::BT601_525:
4018 updatedDataspace = ui::Dataspace::V0_BT601_525;
4019 break;
4020 case ui::Dataspace::BT709:
4021 updatedDataspace = ui::Dataspace::V0_BT709;
4022 break;
4023 default:
4024 break;
4025 }
4026
4027 return updatedDataspace;
4028}
4029
4030sp<GraphicBuffer> Layer::getBuffer() const {
4031 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4032}
4033
Vishnu Nairb76d99a2023-03-19 18:22:31 -07004034void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4035 mTransformHintLegacy = getFixedTransformHint();
4036 if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4037 mTransformHintLegacy = displayTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004038 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004039 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004040}
4041
4042const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4043 return mBufferInfo.mBuffer;
4044}
4045
4046bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004047 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004048 return false;
4049 }
4050
4051 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004052 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004053 mDrawingState.modified = true;
4054 setTransactionFlags(eTransactionNeeded);
4055 return true;
4056}
4057
4058bool Layer::fillsColor() const {
4059 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4060 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4061}
4062
4063bool Layer::hasBlur() const {
4064 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4065}
4066
Vishnu Nairba354102022-08-01 00:14:18 +00004067void Layer::updateSnapshot(bool updateGeometry) {
4068 if (!getCompositionEngineLayerFE()) {
4069 return;
4070 }
4071
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004072 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004073 if (updateGeometry) {
4074 prepareBasicGeometryCompositionState();
4075 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004076 snapshot->roundedCorner = getRoundedCornerState();
4077 snapshot->stretchEffect = getStretchEffect();
4078 snapshot->transformedBounds = mScreenBounds;
4079 if (mEffectiveShadowRadius > 0.f) {
4080 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4081
4082 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4083 // it if transparent regions are present. This may not be necessary since shadows are
4084 // typically cast by layers without transparent regions.
4085 snapshot->shadowSettings.boundaries = mBounds;
4086
4087 const float casterAlpha = snapshot->alpha;
4088 const bool casterIsOpaque =
4089 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4090
4091 // If the casting layer is translucent, we need to fill in the shadow underneath the
4092 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4093 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4094 snapshot->shadowSettings.ambientColor *= casterAlpha;
4095 snapshot->shadowSettings.spotColor *= casterAlpha;
4096 }
4097 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004098 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004099 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004100 snapshot->layerOpaqueFlagSet =
4101 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004102 snapshot->isHdrY410 = isHdrY410();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004103 sp<Layer> p = mDrawingParent.promote();
4104 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004105 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004106 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004107 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004108 }
4109 snapshot->bufferSize = getBufferSize(mDrawingState);
4110 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004111 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004112 preparePerFrameCompositionState();
4113}
4114
Vishnu Naire14c6b32022-08-06 04:20:15 +00004115void Layer::updateChildrenSnapshots(bool updateGeometry) {
4116 for (const sp<Layer>& child : mDrawingChildren) {
4117 child->updateSnapshot(updateGeometry);
4118 child->updateChildrenSnapshots(updateGeometry);
4119 }
4120}
4121
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004122void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4123 mSnapshot->layerMetadata = parentMetadata;
4124 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4125 for (const sp<Layer>& child : mDrawingChildren) {
4126 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4127 }
4128}
4129
4130void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4131 std::unordered_set<Layer*>& visited) {
4132 if (visited.find(this) != visited.end()) {
4133 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4134 return;
4135 }
4136 visited.insert(this);
4137
4138 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4139
4140 if (mDrawingState.zOrderRelatives.empty()) {
4141 return;
4142 }
4143 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4144 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4145 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4146 sp<Layer> relative = weakRelative.promote();
4147 if (!relative) {
4148 continue;
4149 }
4150 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4151 }
4152}
4153
Chavi Weingarten328a8312023-01-26 21:17:52 +00004154bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004155 TrustedPresentationListener const& listener) {
4156 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4157 mTrustedPresentationListener = listener;
4158 mTrustedPresentationThresholds = thresholds;
4159 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4160 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4161 mFlinger->mNumTrustedPresentationListeners++;
4162 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4163 mFlinger->mNumTrustedPresentationListeners--;
4164 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004165
4166 // Reset trusted presentation states to ensure we start the time again.
4167 mEnteredTrustedPresentationStateTime = -1;
4168 mLastReportedTrustedPresentationState = false;
4169 mLastComputedTrustedPresentationState = false;
4170
4171 // If there's a new trusted presentation listener, the code needs to go through the composite
4172 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4173 // we're already in the requested state.
4174 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004175}
4176
Vishnu Naira156f482023-02-22 00:23:38 +00004177void Layer::updateLastLatchTime(nsecs_t latchTime) {
4178 mLastLatchTime = latchTime;
4179}
4180
Mathias Agopian13127d82013-03-05 17:47:11 -08004181// ---------------------------------------------------------------------------
4182
Marin Shalamanov46084422020-10-13 12:33:42 +02004183std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004184 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4185 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004186}
4187
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004188} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004189
4190#if defined(__gl_h_)
4191#error "don't include gl/gl.h in this file"
4192#endif
4193
4194#if defined(__gl2_h_)
4195#error "don't include gl2/gl2.h in this file"
4196#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004197
4198// TODO(b/129481165): remove the #pragma below and fix conversion issues
4199#pragma clang diagnostic pop // ignored "-Wconversion"