blob: 7d16aad9bfeecc10efe9de865ccb2f000796e63c [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);
Alec Mouri74c7ae12023-03-26 02:57:47 +0000174 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Robert Carr6a160312021-05-17 12:08:20 -0700175 mDrawingState.hdrMetadata.validTypes = 0;
176 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
177 mDrawingState.cornerRadius = 0.0f;
178 mDrawingState.backgroundBlurRadius = 0;
179 mDrawingState.api = -1;
180 mDrawingState.hasColorTransform = false;
181 mDrawingState.colorSpaceAgnostic = false;
182 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
183 mDrawingState.metadata = args.metadata;
184 mDrawingState.shadowRadius = 0.f;
185 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
186 mDrawingState.frameTimelineInfo = {};
187 mDrawingState.postTime = -1;
188 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000189 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700190 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700191 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000192 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700193
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700194 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
195 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700196 mDrawingState.color.r = -1.0_hf;
197 mDrawingState.color.g = -1.0_hf;
198 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700199 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700200
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500201 mFrameTracker.setDisplayRefreshPeriod(
202 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700203
Vishnu Naircb8be502022-10-12 19:03:23 +0000204 mOwnerUid = args.ownerUid;
205 mOwnerPid = args.ownerPid;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000206
207 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
208 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
209 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000210
211 mSnapshot->sequence = sequence;
212 mSnapshot->name = getDebugName();
213 mSnapshot->textureName = mTextureName;
214 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000215 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800216}
217
218void Layer::onFirstRef() {
219 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700220}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700221
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700222Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000223 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
224 "Layer destructor called off the main thread.");
225
Patrick Williamsbb25f802022-08-30 23:02:34 +0000226 // The original layer and the clone layer share the same texture and buffer. Therefore, only
227 // one of the layers, in this case the original layer, needs to handle the deletion. The
228 // original layer and the clone should be removed at the same time so there shouldn't be any
229 // issue with the clone layer trying to use the texture.
230 if (mBufferInfo.mBuffer != nullptr) {
231 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
232 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800233 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000234 }
235 if (!isClone()) {
236 // The original layer and the clone layer share the same texture. Therefore, only one of
237 // the layers, in this case the original layer, needs to handle the deletion. The original
238 // layer and the clone should be removed at the same time so there shouldn't be any issue
239 // with the clone layer trying to use the deleted texture.
240 mFlinger->deleteTextureAsync(mTextureName);
241 }
242 const int32_t layerId = getSequence();
243 mFlinger->mTimeStats->onDestroy(layerId);
244 mFlinger->mFrameTracer->onDestroy(layerId);
245
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000246 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700247 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700248
249 if (mDrawingState.sidebandStream != nullptr) {
250 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
251 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700252 if (mHadClonedChild) {
253 mFlinger->mNumClones--;
254 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000255 if (hasTrustedPresentationListener()) {
256 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000257 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000258 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700259}
260
Mathias Agopian13127d82013-03-05 17:47:11 -0800261// ---------------------------------------------------------------------------
262// callbacks
263// ---------------------------------------------------------------------------
264
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700265void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700266 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700267 return;
268 }
Robert Carr2e102c92018-10-23 12:11:15 -0700269
Robert Carr6a160312021-05-17 12:08:20 -0700270 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700271 if (strongRelative == nullptr) {
272 setZOrderRelativeOf(nullptr);
273 return;
274 }
275
276 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700277 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700278 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800279 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700280 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700281}
282
283void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700284 if (!mRemovedFromDrawingState) {
285 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700286 mFlinger->mScheduler->deregisterLayer(this);
287 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000288 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000289
Ady Abrahamd11bade2022-08-01 16:18:03 -0700290 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700291}
Chia-I Wu38512252017-05-17 14:36:16 -0700292
chaviw68d4dab2020-06-08 15:07:32 -0700293sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000294 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700295 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700296 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700297 }
298 return parent->getRootLayer();
299}
300
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700301void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700302 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
303 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700304 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700305
306 traverse(LayerVector::StateSet::Current, [&](Layer* layer) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700307 layer->removeFromCurrentState();
308 layer->removeRelativeZ(layersInTree);
chaviw68d4dab2020-06-08 15:07:32 -0700309 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700310}
311
chaviw61626f22018-11-15 16:26:27 -0800312void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700313 if (mRemovedFromDrawingState) {
314 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700315 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700316 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700317 }
chaviw61626f22018-11-15 16:26:27 -0800318
319 for (const auto& child : mCurrentChildren) {
320 child->addToCurrentState();
321 }
322}
323
Mathias Agopian13127d82013-03-05 17:47:11 -0800324// ---------------------------------------------------------------------------
325// set-up
326// ---------------------------------------------------------------------------
327
chaviw13fdc492017-06-27 12:40:18 -0700328bool Layer::getPremultipledAlpha() const {
329 return mPremultipliedAlpha;
330}
331
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700332sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800333 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700334 if (mGetHandleCalled) {
335 ALOGE("Get handle called twice" );
336 return nullptr;
337 }
338 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700339 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000340 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800341}
342
343// ---------------------------------------------------------------------------
344// h/w composer set-up
345// ---------------------------------------------------------------------------
346
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700347static Rect reduce(const Rect& win, const Region& exclude) {
348 if (CC_LIKELY(exclude.isEmpty())) {
349 return win;
350 }
351 if (exclude.isRect()) {
352 return win.reduce(exclude.getBounds());
353 }
354 return Region(win).subtract(exclude).getBounds();
355}
356
Dan Stoza80d61162017-12-20 15:57:52 -0800357static FloatRect reduce(const FloatRect& win, const Region& exclude) {
358 if (CC_LIKELY(exclude.isEmpty())) {
359 return win;
360 }
361 // Convert through Rect (by rounding) for lack of FloatRegion
362 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
363}
364
Vishnu Nair4351ad52019-02-11 14:13:02 -0800365Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800366 if (!reduceTransparentRegion) {
367 return Rect{mScreenBounds};
368 }
369
370 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800371 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800372 // Transform to screen space.
373 bounds = t.transform(bounds);
374 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700375}
376
Vishnu Nair4351ad52019-02-11 14:13:02 -0800377FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000378 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800379 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700380}
381
Vishnu Nairf0c28512019-02-08 12:40:28 -0800382FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
383 // Subtract the transparent region and snap to the bounds.
384 return reduce(mBounds, activeTransparentRegion);
385}
386
Chavi Weingarten076acac2023-01-19 17:20:43 +0000387// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000388void Layer::updateTrustedPresentationState(const DisplayDevice* display,
389 const frontend::LayerSnapshot* snapshot,
390 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000391 if (!hasTrustedPresentationListener()) {
392 return;
393 }
394 const bool lastState = mLastComputedTrustedPresentationState;
395 mLastComputedTrustedPresentationState = false;
396
397 if (!leaveState) {
398 const auto outputLayer = findOutputLayerForDisplay(display);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000399 if (outputLayer != nullptr) {
400 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
401 Region coveredRegion =
402 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
403 mLastComputedTrustedPresentationState =
404 computeTrustedPresentationState(snapshot->geomLayerBounds,
405 snapshot->sourceBounds(), coveredRegion,
406 snapshot->transformedBounds,
407 snapshot->alpha,
408 snapshot->geomLayerTransform,
409 mTrustedPresentationThresholds);
410 } else {
411 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
412 "TrustedPresentationState",
413 getDebugName());
414 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000415 }
416 }
417 const bool newState = mLastComputedTrustedPresentationState;
418 if (lastState && !newState) {
419 // We were in the trusted presentation state, but now we left it,
420 // emit the callback if needed
421 if (mLastReportedTrustedPresentationState) {
422 mLastReportedTrustedPresentationState = false;
423 mTrustedPresentationListener.invoke(false);
424 }
425 // Reset the timer
426 mEnteredTrustedPresentationStateTime = -1;
427 } else if (!lastState && newState) {
428 // We were not in the trusted presentation state, but we entered it, begin the timer
429 // and make sure this gets called at least once more!
430 mEnteredTrustedPresentationStateTime = time_in_ms;
431 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
432 }
433
434 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
435 if (!mLastReportedTrustedPresentationState && newState &&
436 (time_in_ms - mEnteredTrustedPresentationStateTime >
437 mTrustedPresentationThresholds.stabilityRequirementMs)) {
438 mLastReportedTrustedPresentationState = true;
439 mTrustedPresentationListener.invoke(true);
440 }
441}
442
443/**
444 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
445 * of how the parameters and thresholds are interpreted. The general spirit is
446 * to produce an upper bound on the amount of the buffer which was presented.
447 */
448bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
449 const Region& coveredRegion,
450 const FloatRect& screenBounds, float alpha,
451 const ui::Transform& effectiveTransform,
452 const TrustedPresentationThresholds& thresholds) {
453 if (alpha < thresholds.minAlpha) {
454 return false;
455 }
456 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
457 return false;
458 }
459 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
460 return false;
461 }
462
463 const float sx = effectiveTransform.dsdx();
464 const float sy = effectiveTransform.dsdy();
465 float fractionRendered = std::min(sx * sy, 1.0f);
466
467 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
468 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
469 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
470
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000471 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
472 // Compute the size of all the rects since they may be disconnected.
473 float coveredSize = 0;
474 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
475 float size = rect->width() * rect->height();
476 coveredSize += size;
477 }
478
479 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000480
481 if (fractionRendered < thresholds.minFractionRendered) {
482 return false;
483 }
484
485 return true;
486}
487
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700488void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
489 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800490 const State& s(getDrawingState());
491
492 // Calculate effective layer transform
493 mEffectiveTransform = parentTransform * getActiveTransform(s);
494
Garfield Tan2c1782c2022-02-16 15:25:05 -0800495 if (CC_UNLIKELY(!isTransformValid())) {
496 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
497 getDebugName());
498 return;
499 }
500
Vishnu Nair4351ad52019-02-11 14:13:02 -0800501 // Transform parent bounds to layer space
502 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
503
Vishnu Nairc652ff82019-03-15 12:48:54 -0700504 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800505 mSourceBounds = computeSourceBounds(parentBounds);
506
507 // Calculate bounds by croping diplay frame with layer crop and parent bounds
508 FloatRect bounds = mSourceBounds;
509 const Rect layerCrop = getCrop(s);
510 if (!layerCrop.isEmpty()) {
511 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
512 }
513 bounds = bounds.intersect(parentBounds);
514
515 mBounds = bounds;
516 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700517
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700518 // Use the layer's own shadow radius if set. Otherwise get the radius from
519 // parent.
520 if (s.shadowRadius > 0.f) {
521 mEffectiveShadowRadius = s.shadowRadius;
522 } else {
523 mEffectiveShadowRadius = parentShadowRadius;
524 }
525
526 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
527 // don't pass it to its children.
528 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
529
Vishnu Nair4351ad52019-02-11 14:13:02 -0800530 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700531 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800532 }
Vishnu Nairba354102022-08-01 00:14:18 +0000533
534 if (mPotentialCursor) {
535 prepareCursorCompositionState();
536 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800537}
538
Vishnu Nair60356342018-11-13 13:00:45 -0800539Rect Layer::getCroppedBufferSize(const State& s) const {
540 Rect size = getBufferSize(s);
541 Rect crop = getCrop(s);
542 if (!crop.isEmpty() && size.isValid()) {
543 size.intersect(crop, &size);
544 } else if (!crop.isEmpty()) {
545 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700546 }
Vishnu Nair60356342018-11-13 13:00:45 -0800547 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800548}
549
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700550void Layer::setupRoundedCornersCropCoordinates(Rect win,
551 const FloatRect& roundedCornersCrop) const {
552 // Translate win by the rounded corners rect coordinates, to have all values in
553 // layer coordinate space.
554 win.left -= roundedCornersCrop.left;
555 win.right -= roundedCornersCrop.left;
556 win.top -= roundedCornersCrop.top;
557 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700558}
559
Lloyd Piquede196652020-01-22 17:29:58 -0800560void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800561 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800562 const auto alpha = static_cast<float>(getAlpha());
563 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700564 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800565
566 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
567 if (!opaque || alpha != 1.0f) {
568 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
569 : Hwc2::IComposerClient::BlendMode::COVERAGE;
570 }
571
Alec Mourif4af03e2023-02-11 00:25:24 +0000572 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000573 auto* snapshot = editLayerSnapshot();
574 snapshot->outputFilter = getOutputFilter();
575 snapshot->isVisible = isVisible();
576 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
577 snapshot->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800578
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000579 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800580 contentDirty = false;
581
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000582 snapshot->geomLayerBounds = mBounds;
583 snapshot->geomLayerTransform = getTransform();
584 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
585 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000586 snapshot->localTransform = getActiveTransform(drawingState);
587 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000588 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
589 snapshot->alpha = alpha;
590 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
591 snapshot->blurRegions = drawingState.blurRegions;
592 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800593}
594
Lloyd Piquede196652020-01-22 17:29:58 -0800595void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800596 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000597 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700598
Alec Mourif4af03e2023-02-11 00:25:24 +0000599 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000600 snapshot->geomBufferSize = getBufferSize(drawingState);
601 snapshot->geomContentCrop = getBufferCrop();
602 snapshot->geomCrop = getCrop(drawingState);
603 snapshot->geomBufferTransform = getBufferTransform();
604 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
605 snapshot->geomUsesSourceCrop = usesSourceCrop();
606 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800607
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000608 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800609 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
610 for (const auto& [key, mandatory] : supportedMetadata) {
611 const auto& genericLayerMetadataCompatibilityMap =
612 mFlinger->getGenericLayerMetadataKeyMap();
613 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
614 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
615 continue;
616 }
617 const uint32_t id = compatIter->second;
618
619 auto it = drawingState.metadata.mMap.find(id);
620 if (it == std::end(drawingState.metadata.mMap)) {
621 continue;
622 }
623
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000624 snapshot->metadata.emplace(key,
625 compositionengine::GenericLayerMetadataEntry{mandatory,
626 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800627 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800628}
David Sodmanba340492018-08-05 21:51:33 -0700629
Lloyd Piquede196652020-01-22 17:29:58 -0800630void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800631 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000632 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000633 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800634
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000635 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800636
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000637 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
638 snapshot->dataspace = getDataSpace();
639 snapshot->colorTransform = getColorTransform();
640 snapshot->colorTransformIsIdentity = !hasColorTransform();
641 snapshot->surfaceDamage = surfaceDamageRegion;
642 snapshot->hasProtectedContent = isProtected();
643 snapshot->dimmingEnabled = isDimmingEnabled();
John Reck68796592023-01-25 13:47:12 -0500644 snapshot->currentSdrHdrRatio = getCurrentSdrHdrRatio();
645 snapshot->desiredSdrHdrRatio = getDesiredSdrHdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000646 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800647
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700648 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700649
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000650 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800651
652 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400653 // Rounded corners no longer force client composition, since we may use a
654 // hole punch so that the layer will appear to have rounded corners.
655 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000656 snapshot->stretchEffect.hasEffect()) {
657 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800658 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700659 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000660 snapshot->blurRegions = drawingState.blurRegions;
661 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400662
663 // Layer framerate is used in caching decisions.
664 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
665 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000666 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000667
668 if (hasBufferOrSidebandStream()) {
669 preparePerFrameBufferCompositionState();
670 } else {
671 preparePerFrameEffectsCompositionState();
672 }
673}
674
675void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000676 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000677 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000678 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000679 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
680 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000681 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
682 return;
683 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000684 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000685 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800686 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
687 snapshot->compositionType =
688 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000689 } else {
690 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000691 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
692 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000693 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
694 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
695 }
696
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000697 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000698 snapshot->acquireFence = mBufferInfo.mFence;
699 snapshot->frameNumber = mBufferInfo.mFrameNumber;
700 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000701}
702
703void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000704 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000705 auto* snapshot = editLayerSnapshot();
706 snapshot->color = getColor();
707 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000708 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800709}
710
Lloyd Piquede196652020-01-22 17:29:58 -0800711void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800712 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000713 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000714 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800715
716 // Apply the layer's transform, followed by the display's global transform
717 // Here we're guaranteed that the layer's transform preserves rects
718 Rect win = getCroppedBufferSize(drawingState);
719 // Subtract the transparent region and snap to the bounds
720 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
721 Rect frame(getTransform().transform(bounds));
722
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000723 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800724}
725
Lloyd Piquea83776c2019-01-29 18:42:32 -0800726const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700727 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800728}
729
Mathias Agopian13127d82013-03-05 17:47:11 -0800730// ---------------------------------------------------------------------------
731// drawing...
732// ---------------------------------------------------------------------------
733
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500734aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
735 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700736 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800737 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500738 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800739 }
740 if (outputLayer->getState().hwc) {
741 return (*outputLayer->getState().hwc).hwcCompositionType;
742 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500743 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800744 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800745}
746
Mathias Agopian13127d82013-03-05 17:47:11 -0800747// ----------------------------------------------------------------------------
748// local state
749// ----------------------------------------------------------------------------
750
David Sodman41fdfc92017-11-06 16:09:56 -0800751bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800752 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700753 if (s.flags & layer_state_t::eLayerSecure) {
754 return true;
755 }
756
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000757 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700758 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700759}
760
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100761void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
762 std::vector<JankData>& jankData) {
763 if (mPendingJankClassifications.empty() ||
764 !mPendingJankClassifications.front()->getJankType()) {
765 return;
766 }
767
768 bool includeJankData = false;
769 for (const auto& handle : handles) {
770 for (const auto& cb : handle->callbackIds) {
771 if (cb.includeJankData) {
772 includeJankData = true;
773 break;
774 }
775 }
776
777 if (includeJankData) {
778 jankData.reserve(mPendingJankClassifications.size());
779 break;
780 }
781 }
782
783 while (!mPendingJankClassifications.empty() &&
784 mPendingJankClassifications.front()->getJankType()) {
785 if (includeJankData) {
786 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
787 mPendingJankClassifications.front();
788 jankData.emplace_back(
789 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
790 }
791 mPendingJankClassifications.pop_front();
792 }
793}
794
Mathias Agopian13127d82013-03-05 17:47:11 -0800795// ----------------------------------------------------------------------------
796// transaction
797// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800798
Vishnu Naira156f482023-02-22 00:23:38 +0000799uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700800 ATRACE_CALL();
801
Robert Carr0758e5d2021-03-11 22:15:04 -0800802 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700803 mDrawingStateModified = mDrawingState.modified;
804 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700805
Alec Mourib416efd2018-09-06 21:01:59 +0000806 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700807
Robert Carr6a160312021-05-17 12:08:20 -0700808 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800809 // invalidate and recompute the visible regions if needed
810 flags |= Layer::eVisibleRegion;
811 }
812
Robert Carr6a160312021-05-17 12:08:20 -0700813 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800814 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000815 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800816 flags |= eVisibleRegion;
817 this->contentDirty = true;
818
819 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700820 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800821 }
822
Arthur Hung9ed43392022-05-27 06:31:57 +0000823 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
824 mFlinger->mUpdateInputInfo = true;
825 }
826
Vishnu Naira156f482023-02-22 00:23:38 +0000827 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800828
Mathias Agopian13127d82013-03-05 17:47:11 -0800829 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800830}
831
Vishnu Naira156f482023-02-22 00:23:38 +0000832void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000833 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
834 // bufferSurfaceFrameTX will be presented in latchBuffer.
835 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
836 if (surfaceFrame->getPresentState() != PresentState::Presented) {
837 // With applyPendingStates, we could end up having presented surfaceframes from previous
838 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800839 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000840 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
841 }
842 }
Robert Carr6a160312021-05-17 12:08:20 -0700843 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700844}
845
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700846uint32_t Layer::clearTransactionFlags(uint32_t mask) {
847 const auto flags = mTransactionFlags & mask;
848 mTransactionFlags &= ~mask;
849 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800850}
851
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700852void Layer::setTransactionFlags(uint32_t mask) {
853 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800854}
855
Robert Carr1f0a16a2016-10-24 16:27:39 -0700856bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
857 ssize_t idx = mCurrentChildren.indexOf(childLayer);
858 if (idx < 0) {
859 return false;
860 }
861 if (childLayer->setLayer(z)) {
862 mCurrentChildren.removeAt(idx);
863 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800864 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700865 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800866 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700867}
868
Robert Carr503c7042017-09-27 15:06:08 -0700869bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
870 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
871 ssize_t idx = mCurrentChildren.indexOf(childLayer);
872 if (idx < 0) {
873 return false;
874 }
875 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
876 mCurrentChildren.removeAt(idx);
877 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800878 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700879 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800880 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700881}
882
Robert Carrae060832016-11-28 10:51:00 -0800883bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700884 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
885 mDrawingState.sequence++;
886 mDrawingState.z = z;
887 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700888
Robert Carra70e91c2021-06-11 13:59:52 -0700889 mFlinger->mSomeChildrenChanged = true;
890
Robert Carrdb66e622017-04-10 16:55:57 -0700891 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700892 if (mDrawingState.zOrderRelativeOf != nullptr) {
893 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700894 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700895 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700896 }
chaviw606e5cf2019-03-01 10:12:10 -0800897 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700898 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800899 setTransactionFlags(eTransactionNeeded);
900 return true;
901}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700902
Robert Carrdb66e622017-04-10 16:55:57 -0700903void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700904 mDrawingState.zOrderRelatives.remove(relative);
905 mDrawingState.sequence++;
906 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700907 setTransactionFlags(eTransactionNeeded);
908}
909
910void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700911 mDrawingState.zOrderRelatives.add(relative);
912 mDrawingState.modified = true;
913 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700914 setTransactionFlags(eTransactionNeeded);
915}
916
chaviw606e5cf2019-03-01 10:12:10 -0800917void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700918 mDrawingState.zOrderRelativeOf = relativeOf;
919 mDrawingState.sequence++;
920 mDrawingState.modified = true;
921 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700922
chaviw606e5cf2019-03-01 10:12:10 -0800923 setTransactionFlags(eTransactionNeeded);
924}
925
Robert Carr503d2bd2017-12-04 15:49:47 -0800926bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000927 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700928 if (relative == nullptr) {
929 return false;
930 }
931
Robert Carr6a160312021-05-17 12:08:20 -0700932 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
933 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800934 return false;
935 }
936
Robert Carr88b85e12022-03-21 15:47:35 -0700937 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
938 (relative->mDrawingState.zOrderRelativeOf == this)) {
939 ALOGE("Detected relative layer loop between %s and %s",
940 mName.c_str(), relative->mName.c_str());
941 ALOGE("Ignoring new call to set relative layer");
942 return false;
943 }
944
Robert Carra70e91c2021-06-11 13:59:52 -0700945 mFlinger->mSomeChildrenChanged = true;
946
Robert Carr6a160312021-05-17 12:08:20 -0700947 mDrawingState.sequence++;
948 mDrawingState.modified = true;
949 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700950
Robert Carr6a160312021-05-17 12:08:20 -0700951 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700952 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700953 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700954 }
chaviw606e5cf2019-03-01 10:12:10 -0800955 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700956 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700957
958 setTransactionFlags(eTransactionNeeded);
959
960 return true;
961}
962
Winson Chunga30f7c92021-06-29 15:42:56 -0700963bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
964 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
965 mDrawingState.isTrustedOverlay = isTrustedOverlay;
966 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000967 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700968 setTransactionFlags(eTransactionNeeded);
969 return true;
970}
971
972bool Layer::isTrustedOverlay() const {
973 if (getDrawingState().isTrustedOverlay) {
974 return true;
975 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000976 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700977 return (p != nullptr) && p->isTrustedOverlay();
978}
979
Dan Stoza9e56aa02015-11-02 13:00:03 -0800980bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700981 if (mDrawingState.color.a == alpha) return false;
982 mDrawingState.sequence++;
983 mDrawingState.color.a = alpha;
984 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800985 setTransactionFlags(eTransactionNeeded);
986 return true;
987}
chaviw13fdc492017-06-27 12:40:18 -0700988
Valerie Haudd0b7572019-01-29 14:59:27 -0800989bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700990 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700991 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800992 }
Robert Carr6a160312021-05-17 12:08:20 -0700993 mDrawingState.sequence++;
994 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800995 setTransactionFlags(eTransactionNeeded);
996
Robert Carr6a160312021-05-17 12:08:20 -0700997 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -0800998 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -0800999 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001000 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001001 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08001002 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001003 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001004
Valerie Haudd0b7572019-01-29 14:59:27 -08001005 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001006 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001007 mFlinger->mLayersAdded = true;
1008 // set up SF to handle added color layer
1009 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -07001010 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001011 }
1012 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001013 } else if (mDrawingState.bgColorLayer && alpha == 0) {
1014 mDrawingState.bgColorLayer->reparent(nullptr);
1015 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001016 return true;
1017 }
1018
Robert Carr6a160312021-05-17 12:08:20 -07001019 mDrawingState.bgColorLayer->setColor(color);
1020 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1021 mDrawingState.bgColorLayer->setAlpha(alpha);
1022 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001023
chaviw13fdc492017-06-27 12:40:18 -07001024 return true;
1025}
1026
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001027bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001028 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001029
Robert Carr6a160312021-05-17 12:08:20 -07001030 mDrawingState.sequence++;
1031 mDrawingState.cornerRadius = cornerRadius;
1032 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001033 setTransactionFlags(eTransactionNeeded);
1034 return true;
1035}
1036
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001037bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001038 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001039 // If we start or stop drawing blur then the layer's visibility state may change so increment
1040 // the magic sequence number.
1041 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1042 mDrawingState.sequence++;
1043 }
Robert Carr6a160312021-05-17 12:08:20 -07001044 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1045 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001046 setTransactionFlags(eTransactionNeeded);
1047 return true;
1048}
Marissa Wall61c58622018-07-18 10:12:20 -07001049
Mathias Agopian13127d82013-03-05 17:47:11 -08001050bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001051 mDrawingState.sequence++;
1052 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001053 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001054 setTransactionFlags(eTransactionNeeded);
1055 return true;
1056}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001057
Lucas Dupinc3800b82020-10-02 16:24:48 -07001058bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001059 // If we start or stop drawing blur then the layer's visibility state may change so increment
1060 // the magic sequence number.
1061 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1062 mDrawingState.sequence++;
1063 }
Robert Carr6a160312021-05-17 12:08:20 -07001064 mDrawingState.blurRegions = blurRegions;
1065 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001066 setTransactionFlags(eTransactionNeeded);
1067 return true;
1068}
1069
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001070bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001071 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1072 if (mDrawingState.flags == newFlags) return false;
1073 mDrawingState.sequence++;
1074 mDrawingState.flags = newFlags;
1075 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001076 setTransactionFlags(eTransactionNeeded);
1077 return true;
1078}
Robert Carr99e27f02016-06-16 15:18:02 -07001079
chaviw25714502021-02-11 10:01:08 -08001080bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001081 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001082 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001083 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001084
Robert Carr6a160312021-05-17 12:08:20 -07001085 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001086 setTransactionFlags(eTransactionNeeded);
1087 return true;
1088}
Robert Carr8d5227b2017-03-16 15:41:03 -07001089
Evan Roskyef876c92019-01-25 17:46:06 -08001090bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001091 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1092 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001093 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001094 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001095}
1096
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001097bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001098 if (mDrawingState.layerStack == layerStack) return false;
1099 mDrawingState.sequence++;
1100 mDrawingState.layerStack = layerStack;
1101 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001102 setTransactionFlags(eTransactionNeeded);
1103 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001104}
1105
Peiyong Linc502cb72019-03-01 15:00:23 -08001106bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001107 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001108 return false;
1109 }
Robert Carr6a160312021-05-17 12:08:20 -07001110 mDrawingState.sequence++;
1111 mDrawingState.colorSpaceAgnostic = agnostic;
1112 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001113 setTransactionFlags(eTransactionNeeded);
1114 return true;
1115}
1116
Sally Qi81d95e62022-03-21 19:41:33 -07001117bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1118 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1119
1120 mDrawingState.sequence++;
1121 mDrawingState.dimmingEnabled = dimmingEnabled;
1122 mDrawingState.modified = true;
1123 setTransactionFlags(eTransactionNeeded);
1124 return true;
1125}
1126
Ana Krulecc84d09b2019-11-02 23:10:29 +01001127bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001128 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1129 mDrawingState.frameRateSelectionPriority = priority;
1130 mDrawingState.sequence++;
1131 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001132 setTransactionFlags(eTransactionNeeded);
1133 return true;
1134}
1135
1136int32_t Layer::getFrameRateSelectionPriority() const {
1137 // Check if layer has priority set.
1138 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1139 return mDrawingState.frameRateSelectionPriority;
1140 }
1141 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001142 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001143 if (parent != nullptr) {
1144 return parent->getFrameRateSelectionPriority();
1145 }
1146
1147 return Layer::PRIORITY_UNSET;
1148}
1149
Andy Labrada096227e2022-06-15 16:58:11 +00001150bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1151 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1152 mDrawingState.defaultFrameRateCompatibility = compatibility;
1153 mDrawingState.modified = true;
1154 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1155 setTransactionFlags(eTransactionNeeded);
1156 return true;
1157}
1158
1159scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1160 return mDrawingState.defaultFrameRateCompatibility;
1161}
1162
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001163bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1164 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1165};
1166
Vishnu Nair73908d12022-10-24 21:46:42 -07001167ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1168 bool useDrawing = state == LayerVector::StateSet::Drawing;
1169 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1170 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001171 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001172 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001173 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001174}
1175
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001176bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001177 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001178 return false;
1179 }
1180
Robert Carr6a160312021-05-17 12:08:20 -07001181 mDrawingState.sequence++;
1182 mDrawingState.shadowRadius = shadowRadius;
1183 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001184 setTransactionFlags(eTransactionNeeded);
1185 return true;
1186}
1187
Vishnu Nair6213bd92020-05-08 17:42:25 -07001188bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001189 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001190 return false;
1191 }
1192
Robert Carr6a160312021-05-17 12:08:20 -07001193 mDrawingState.sequence++;
1194 mDrawingState.fixedTransformHint = fixedTransformHint;
1195 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001196 setTransactionFlags(eTransactionNeeded);
1197 return true;
1198}
1199
John Reckcdb4ed72021-02-04 13:39:33 -05001200bool Layer::setStretchEffect(const StretchEffect& effect) {
1201 StretchEffect temp = effect;
1202 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001203 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001204 return false;
1205 }
Robert Carr6a160312021-05-17 12:08:20 -07001206 mDrawingState.sequence++;
1207 mDrawingState.stretchEffect = temp;
1208 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001209 setTransactionFlags(eTransactionNeeded);
1210 return true;
1211}
1212
John Reckc00c6692021-02-16 11:37:33 -05001213StretchEffect Layer::getStretchEffect() const {
1214 if (mDrawingState.stretchEffect.hasEffect()) {
1215 return mDrawingState.stretchEffect;
1216 }
1217
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001218 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001219 if (parent != nullptr) {
1220 auto effect = parent->getStretchEffect();
1221 if (effect.hasEffect()) {
1222 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1223 return effect;
1224 }
1225 }
1226 return StretchEffect{};
1227}
1228
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001229bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1230 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001231 return false;
1232 }
1233 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001234 mBorderWidth = width;
1235 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001236 return true;
1237}
1238
1239bool Layer::isBorderEnabled() {
1240 return mBorderEnabled;
1241}
1242
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001243float Layer::getBorderWidth() {
1244 return mBorderWidth;
1245}
1246
1247const half4& Layer::getBorderColor() {
1248 return mBorderColor;
1249}
1250
Ady Abrahama850c182021-08-04 13:04:37 -07001251bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1252 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1253 const auto frameRate = [&] {
1254 if (mDrawingState.frameRate.rate.isValid() ||
1255 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1256 return mDrawingState.frameRate;
1257 }
1258
1259 return parentFrameRate;
1260 }();
1261
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001262 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001263
1264 // The frame rate is propagated to the children
1265 bool childrenHaveFrameRate = false;
1266 for (const sp<Layer>& child : mCurrentChildren) {
1267 childrenHaveFrameRate |=
1268 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1269 }
1270
1271 // If we don't have a valid frame rate, but the children do, we set this
1272 // layer as NoVote to allow the children to control the refresh rate
1273 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1274 childrenHaveFrameRate) {
1275 *transactionNeeded |=
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001276 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001277 }
1278
1279 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1280 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001281 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001282 const auto layerVotedWithDefaultCompatibility =
1283 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1284 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1285 const auto layerVotedWithExactCompatibility =
1286 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1287 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1288 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1289}
1290
Ady Abraham60e42ea2020-03-09 19:17:31 -07001291void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001292 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001293 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001294 while (auto parent = layer->getParent()) {
1295 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001296 }
Ady Abrahama850c182021-08-04 13:04:37 -07001297 return layer;
1298 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001299
Ady Abraham60e42ea2020-03-09 19:17:31 -07001300 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001301 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001302
Ady Abrahama850c182021-08-04 13:04:37 -07001303 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001304 if (transactionNeeded) {
1305 mFlinger->setTransactionFlags(eTraversalNeeded);
1306 }
1307}
1308
Ady Abraham71c437d2020-01-31 15:56:57 -08001309bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001310 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001311 return false;
1312 }
1313
Robert Carr6a160312021-05-17 12:08:20 -07001314 mDrawingState.sequence++;
1315 mDrawingState.frameRate = frameRate;
1316 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001317
1318 updateTreeHasFrameRateVote();
1319
Steven Thomas3172e202020-01-06 19:25:30 -08001320 setTransactionFlags(eTransactionNeeded);
1321 return true;
1322}
1323
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001324void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1325 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001326 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001327
1328 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1329 // there are two transactions with the same token, the first one without a buffer and the
1330 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1331 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001332 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1333 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001334 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001335 mDrawingState.bufferSurfaceFrameTX = it->second;
1336 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1337 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1338 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001339 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001340 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001341 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1342 }
1343}
1344
1345void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1346 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001347 mDrawingState.frameTimelineInfo = info;
1348 mDrawingState.postTime = postTime;
1349 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001350 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001351
Robert Carr6a160312021-05-17 12:08:20 -07001352 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001353 bufferSurfaceFrameTX != nullptr) {
1354 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1355 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1356 // being used for BufferSurfaceFrame, don't create a new one.
1357 return;
1358 }
1359 }
1360 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1361 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1362 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001363 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1364 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001365 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001366 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001367 } else {
1368 if (it->second->getPresentState() == PresentState::Presented) {
1369 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1370 // have been from previous vsync.
1371 it->second = createSurfaceFrameForTransaction(info, postTime);
1372 }
1373 }
1374}
1375
1376void Layer::addSurfaceFrameDroppedForBuffer(
1377 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001378 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001379 surfaceFrame->setPresentState(PresentState::Dropped);
1380 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1381}
1382
1383void Layer::addSurfaceFramePresentedForBuffer(
1384 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1385 nsecs_t currentLatchTime) {
1386 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1387 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1388 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001389 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001390}
1391
1392std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1393 const FrameTimelineInfo& info, nsecs_t postTime) {
1394 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001395 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1396 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001397 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001398 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001399 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001400 // For Transactions, the post time is considered to be both queue and acquire fence time.
1401 surfaceFrame->setActualQueueTime(postTime);
1402 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001403 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1404 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001405 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001406 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001407 onSurfaceFrameCreated(surfaceFrame);
1408 return surfaceFrame;
1409}
1410
1411std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1412 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1413 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001414 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001415 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001416 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001417 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001418 // For buffers, acquire fence time will set during latch.
1419 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001420 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1421 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001422 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001423 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001424 onSurfaceFrameCreated(surfaceFrame);
1425 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001426}
1427
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001428bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001429 if (mDrawingState.frameRateForLayerTree == frameRate) {
1430 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001431 }
1432
Ady Abrahama850c182021-08-04 13:04:37 -07001433 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001434
Ady Abrahama850c182021-08-04 13:04:37 -07001435 // TODO(b/195668952): we probably don't need to dirty visible regions here
1436 // or even store frameRateForLayerTree in mDrawingState
1437 mDrawingState.sequence++;
1438 mDrawingState.modified = true;
1439 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001440
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001441 mFlinger->mScheduler
1442 ->recordLayerHistory(sequence, getLayerProps(), systemTime(),
1443 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1444 return true;
1445}
Ady Abrahama850c182021-08-04 13:04:37 -07001446
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001447bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps) {
1448 if (mDrawingState.frameRateForLayerTree == frameRate) {
1449 return false;
1450 }
1451
1452 mDrawingState.frameRateForLayerTree = frameRate;
1453 mFlinger->mScheduler
1454 ->recordLayerHistory(sequence, layerProps, systemTime(),
1455 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001456 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001457}
1458
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001459Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1460 return getDrawingState().frameRateForLayerTree;
1461}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001462
Robert Carr1f0a16a2016-10-24 16:27:39 -07001463bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001464 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001465 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001466 if (parent != nullptr && parent->isHiddenByPolicy()) {
1467 return true;
1468 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001469 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1470 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1471 if (zOrderRelativeOf != nullptr) {
1472 if (zOrderRelativeOf->isHiddenByPolicy()) {
1473 return true;
1474 }
1475 }
1476 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001477 if (CC_UNLIKELY(!isTransformValid())) {
1478 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1479 return true;
1480 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001481 return s.flags & layer_state_t::eLayerHidden;
1482}
1483
David Sodman41fdfc92017-11-06 16:09:56 -08001484uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001485 // TODO: should we do something special if mSecure is set?
1486 if (mProtectedByApp) {
1487 // need a hardware-protected path to external video sink
1488 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001489 }
Riley Andrews03414a12014-07-01 14:22:59 -07001490 if (mPotentialCursor) {
1491 usage |= GraphicBuffer::USAGE_CURSOR;
1492 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001493 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001494 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001495}
1496
Vishnu Nair71fcf912022-10-18 09:14:20 -07001497void Layer::skipReportingTransformHint() {
1498 mSkipReportingTransformHint = true;
1499}
1500
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001501void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1502 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1503 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001504 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001505
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001506 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001507}
1508
Mathias Agopian13127d82013-03-05 17:47:11 -08001509// ----------------------------------------------------------------------------
1510// debugging
1511// ----------------------------------------------------------------------------
1512
Marissa Wall61c58622018-07-18 10:12:20 -07001513// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001514gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001515 using namespace std::string_literals;
1516
Huihong Luo05539a12022-02-23 10:29:40 -08001517 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001518 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001519 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001520 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001521 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001522 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001523
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001524 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001525 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001526 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001527 info.mX = ds.transform.tx();
1528 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001529 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001530 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001531 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001532 info.mFlags = ds.flags;
1533 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001534 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001535 info.mMatrix[0][0] = ds.transform[0][0];
1536 info.mMatrix[0][1] = ds.transform[0][1];
1537 info.mMatrix[1][0] = ds.transform[1][0];
1538 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001539 {
chaviwd62d3062019-09-04 14:48:02 -07001540 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001541 if (buffer != 0) {
1542 info.mActiveBufferWidth = buffer->getWidth();
1543 info.mActiveBufferHeight = buffer->getHeight();
1544 info.mActiveBufferStride = buffer->getStride();
1545 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001546 } else {
1547 info.mActiveBufferWidth = 0;
1548 info.mActiveBufferHeight = 0;
1549 info.mActiveBufferStride = 0;
1550 info.mActiveBufferFormat = 0;
1551 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001552 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001553 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001554 info.mIsOpaque = isOpaque(ds);
1555 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001556 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001557 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001558}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001559
Yiwei Zhang5434a782018-12-05 18:06:32 -08001560void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001561 result.append(kDumpTableRowLength, '-');
1562 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001563 result.append(" Layer name\n");
1564 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001565 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001566 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001567 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001568 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001569 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001570 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1571 result.append(kDumpTableRowLength, '-');
1572 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001573}
1574
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001575void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1576 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001577 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001578 return;
1579 }
1580
Yiwei Zhang5434a782018-12-05 18:06:32 -08001581 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001582 if (mName.length() > 77) {
1583 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001584 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001585 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001586 shortened.append(mName, mName.length() - 36);
1587 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001588 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001589 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001590 }
1591
Yiwei Zhang5434a782018-12-05 18:06:32 -08001592 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001593
Alec Mourib416efd2018-09-06 21:01:59 +00001594 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001595 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001596
Chia-I Wu1e043612018-03-01 09:45:09 -08001597 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001598 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001599 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001600 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001601 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001602 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001603 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001604 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1605 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001606 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001607 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001608 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001609 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001610 const auto frameRate = getFrameRateForLayerTree();
1611 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1612 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001613 ftl::enum_string(frameRate.type).c_str(),
1614 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001615 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001616 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001617 }
Dan Stozae22aec72016-08-01 13:20:59 -07001618
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001619 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1620 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1621
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001622 result.append(kDumpTableRowLength, '-');
1623 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001624}
Dan Stozae22aec72016-08-01 13:20:59 -07001625
Yiwei Zhang5434a782018-12-05 18:06:32 -08001626void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001627 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001628}
1629
Svetoslavd85084b2014-03-20 10:28:31 -07001630void Layer::clearFrameStats() {
1631 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001632}
1633
Jamie Gennis6547ff42013-07-16 20:12:42 -07001634void Layer::logFrameStats() {
1635 mFrameTracker.logAndResetStats(mName);
1636}
1637
Svetoslavd85084b2014-03-20 10:28:31 -07001638void Layer::getFrameStats(FrameStats* outStats) const {
1639 mFrameTracker.getStats(outStats);
1640}
1641
Vishnu Nair76554eb2022-12-09 03:38:36 +00001642void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1643 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
1644 StringAppendF(&result, "Layer %s%s pid:%d uid:%d\n", getName().c_str(), hasBuffer.c_str(),
Vishnu Naircb8be502022-10-12 19:03:23 +00001645 mOwnerPid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001646}
1647
Brian Anderson5ea5e592016-12-01 16:54:33 -08001648void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001649 const int32_t layerId = getSequence();
1650 mFlinger->mTimeStats->onDestroy(layerId);
1651 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001652}
1653
Vishnu Nair787aa782023-03-17 13:46:46 -07001654size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001655 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001656 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001657 count += 1 + child->getChildrenCount();
1658 }
1659 return count;
1660}
1661
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001662void Layer::setGameModeForTree(GameMode gameMode) {
1663 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001664 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1665 gameMode =
1666 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001667 }
1668 setGameMode(gameMode);
1669 for (const sp<Layer>& child : mCurrentChildren) {
1670 child->setGameModeForTree(gameMode);
1671 }
1672}
1673
Robert Carr1f0a16a2016-10-24 16:27:39 -07001674void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001675 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001676 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001677
Robert Carr1f0a16a2016-10-24 16:27:39 -07001678 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001679 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001680 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001681 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001682}
1683
1684ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001685 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001686 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001687
Robert Carr1323c952019-01-28 18:13:27 -08001688 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001689 const auto removeResult = mCurrentChildren.remove(layer);
1690
1691 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001692 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001693 layer->updateTreeHasFrameRateVote();
1694
1695 return removeResult;
1696}
1697
Robert Carr15eae092018-03-23 13:43:53 -07001698void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001699 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001700 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001701 const float parentShadowRadius =
1702 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001703 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001704 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001705 }
1706}
1707
chaviwf1961f72017-09-18 16:41:07 -07001708bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001709 sp<Layer> newParent;
1710 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001711 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001712 if (newParent == nullptr) {
1713 ALOGE("Unable to promote Layer handle");
1714 return false;
1715 }
1716 if (newParent == this) {
1717 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1718 return false;
1719 }
1720 }
1721
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001722 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001723 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001724 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001725 }
1726
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001727 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001728 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001729 if (!newParent->isRemovedFromCurrentState()) {
1730 addToCurrentState();
1731 } else {
1732 onRemovedFromCurrentState();
1733 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001734 } else {
1735 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001736 }
1737
chaviw06178942017-07-27 10:25:59 -07001738 return true;
1739}
1740
Peiyong Lind3788632018-09-18 16:01:31 -07001741bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001742 static const mat4 identityMatrix = mat4();
1743
Robert Carr6a160312021-05-17 12:08:20 -07001744 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001745 return false;
1746 }
Robert Carr6a160312021-05-17 12:08:20 -07001747 ++mDrawingState.sequence;
1748 mDrawingState.colorTransform = matrix;
1749 mDrawingState.hasColorTransform = matrix != identityMatrix;
1750 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001751 setTransactionFlags(eTransactionNeeded);
1752 return true;
1753}
1754
chaviwf66724d2018-11-28 16:35:21 -08001755mat4 Layer::getColorTransform() const {
1756 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001757 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001758 colorTransform = parent->getColorTransform() * colorTransform;
1759 }
1760 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001761}
1762
1763bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001764 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001765 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001766 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1767 }
1768 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001769}
1770
Chia-I Wu11481472018-05-04 10:43:19 -07001771bool Layer::isLegacyDataSpace() const {
1772 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001773 return !(getDataSpace() &
1774 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1775 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001776}
1777
Robert Carr1f0a16a2016-10-24 16:27:39 -07001778void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001779 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001780}
1781
Robert Carr6a160312021-05-17 12:08:20 -07001782int32_t Layer::getZ(LayerVector::StateSet) const {
1783 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001784}
1785
Robert Carr1c5481e2019-07-01 14:42:27 -07001786bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001787 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001788 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001789 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001790}
1791
David Sodman41fdfc92017-11-06 16:09:56 -08001792__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001793 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001794 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1795 "makeTraversalList received invalid stateSet");
1796 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1797 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001798 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001799
Robert Carr29abff82017-12-04 13:51:20 -08001800 if (state.zOrderRelatives.size() == 0) {
1801 *outSkipRelativeZUsers = true;
1802 return children;
1803 }
1804
chaviwfd462612018-05-31 16:11:27 -07001805 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001806 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001807 sp<Layer> strongRelative = weakRelative.promote();
1808 if (strongRelative != nullptr) {
1809 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001810 }
1811 }
1812
Dan Stoza412903f2017-04-27 13:42:17 -07001813 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001814 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001815 continue;
1816 }
Robert Carrdb66e622017-04-10 16:55:57 -07001817 traverse.add(child);
1818 }
1819
1820 return traverse;
1821}
1822
Robert Carr1f0a16a2016-10-24 16:27:39 -07001823/**
Robert Carrdb66e622017-04-10 16:55:57 -07001824 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001825 */
Dan Stoza412903f2017-04-27 13:42:17 -07001826void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001827 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1828 // produce a new list for traversing, including our relatives, and not including our children
1829 // who are relatives of another surface. In the case that there are no relative Z,
1830 // makeTraversalList returns our children directly to avoid significant overhead.
1831 // However in this case we need to take the responsibility for filtering children which
1832 // are relatives of another surface here.
1833 bool skipRelativeZUsers = false;
1834 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001835
Robert Carr1f0a16a2016-10-24 16:27:39 -07001836 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001837 for (; i < list.size(); i++) {
1838 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001839 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1840 continue;
1841 }
1842
chaviw301b1d82019-11-06 13:15:09 -08001843 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001844 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001845 }
Dan Stoza412903f2017-04-27 13:42:17 -07001846 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001847 }
Robert Carr29abff82017-12-04 13:51:20 -08001848
Dan Stoza412903f2017-04-27 13:42:17 -07001849 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001850 for (; i < list.size(); i++) {
1851 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001852
Robert Carr29abff82017-12-04 13:51:20 -08001853 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1854 continue;
1855 }
Dan Stoza412903f2017-04-27 13:42:17 -07001856 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001857 }
1858}
1859
1860/**
Robert Carrdb66e622017-04-10 16:55:57 -07001861 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001862 */
Dan Stoza412903f2017-04-27 13:42:17 -07001863void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1864 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001865 // See traverseInZOrder for documentation.
1866 bool skipRelativeZUsers = false;
1867 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001868
Robert Carr1f0a16a2016-10-24 16:27:39 -07001869 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001870 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001871 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001872
1873 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1874 continue;
1875 }
1876
chaviw301b1d82019-11-06 13:15:09 -08001877 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001878 break;
1879 }
Dan Stoza412903f2017-04-27 13:42:17 -07001880 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001881 }
Dan Stoza412903f2017-04-27 13:42:17 -07001882 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001883 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001884 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001885
1886 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1887 continue;
1888 }
1889
Dan Stoza412903f2017-04-27 13:42:17 -07001890 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001891 }
1892}
1893
Edgar Arriaga844fa672020-01-16 14:21:42 -08001894void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1895 visitor(this);
1896 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001897 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001898 for (const sp<Layer>& child : children) {
1899 child->traverse(state, visitor);
1900 }
1901}
1902
Vishnu Nair787aa782023-03-17 13:46:46 -07001903void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
1904 for (const sp<Layer>& child : mDrawingChildren) {
1905 visitor(child.get());
1906 }
1907}
1908
chaviw4b129c22018-04-09 16:19:43 -07001909LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1910 const std::vector<Layer*>& layersInTree) {
1911 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1912 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001913 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1914 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001915 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001916
chaviwfd462612018-05-31 16:11:27 -07001917 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001918 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1919 sp<Layer> strongRelative = weakRelative.promote();
1920 // Only add relative layers that are also descendents of the top most parent of the tree.
1921 // If a relative layer is not a descendent, then it should be ignored.
1922 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1923 traverse.add(strongRelative);
1924 }
1925 }
1926
1927 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001928 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001929 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1930 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1931 // the child here since it won't be added later as a relative.
1932 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1933 childState.zOrderRelativeOf.promote().get())) {
1934 continue;
1935 }
1936 traverse.add(child);
1937 }
1938
1939 return traverse;
1940}
1941
1942void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1943 LayerVector::StateSet stateSet,
1944 const LayerVector::Visitor& visitor) {
1945 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001946
1947 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001948 for (; i < list.size(); i++) {
1949 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001950 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001951 break;
1952 }
chaviw4b129c22018-04-09 16:19:43 -07001953 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001954 }
chaviw4b129c22018-04-09 16:19:43 -07001955
chaviwa76b2712017-09-20 12:02:26 -07001956 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001957 for (; i < list.size(); i++) {
1958 const auto& relative = list[i];
1959 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001960 }
1961}
1962
chaviw4b129c22018-04-09 16:19:43 -07001963std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1964 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1965 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1966
1967 std::vector<Layer*> layersInTree = {this};
1968 for (size_t i = 0; i < children.size(); i++) {
1969 const auto& child = children[i];
1970 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1971 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1972 }
1973
1974 return layersInTree;
1975}
1976
1977void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1978 const LayerVector::Visitor& visitor) {
1979 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1980 std::sort(layersInTree.begin(), layersInTree.end());
1981 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1982}
1983
Peiyong Linefefaac2018-08-17 12:27:51 -07001984ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001985 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001986}
1987
Garfield Tan2c1782c2022-02-16 15:25:05 -08001988bool Layer::isTransformValid() const {
1989 float transformDet = getTransform().det();
1990 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1991}
1992
chaviw13fdc492017-06-27 12:40:18 -07001993half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001994 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001995
chaviw13fdc492017-06-27 12:40:18 -07001996 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1997 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07001998}
Robert Carr6452f122017-03-21 10:41:29 -07001999
Vishnu Nair6213bd92020-05-08 17:42:25 -07002000ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002001 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002002 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2003 return fixedTransformHint;
2004 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002005 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002006 if (!p) return fixedTransformHint;
2007 return p->getFixedTransformHint();
2008}
2009
chaviw13fdc492017-06-27 12:40:18 -07002010half4 Layer::getColor() const {
2011 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002012 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002013}
Robert Carr6452f122017-03-21 10:41:29 -07002014
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002015int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002016 if (getDrawingState().backgroundBlurRadius == 0) {
2017 return 0;
2018 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002019
Vishnu Nair29810f72022-07-01 16:38:41 +00002020 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002021 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2022 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002023}
2024
Galia Peychevae0acf382021-04-12 21:22:34 +02002025const std::vector<BlurRegion> Layer::getBlurRegions() const {
2026 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002027 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002028 for (auto& region : regionsCopy) {
2029 region.alpha = region.alpha * layerAlpha;
2030 }
2031 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002032}
2033
Vishnu Naire14c6b32022-08-06 04:20:15 +00002034RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002035 // Get parent settings
2036 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002037 const auto& parent = mDrawingParent.promote();
2038 if (parent != nullptr) {
2039 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002040 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002041 ui::Transform t = getActiveTransform(getDrawingState());
2042 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002043 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002044 parentSettings.radius.x *= t.getScaleX();
2045 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002046 }
2047 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002048
2049 // Get layer settings
2050 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002051 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002052 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002053 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002054
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002055 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002056 // If the parent and the layer have rounded corner settings, use the parent settings if the
2057 // parent crop is entirely inside the layer crop.
2058 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2059 if (parentSettings.cropRect.left > layerCropRect.left &&
2060 parentSettings.cropRect.top > layerCropRect.top &&
2061 parentSettings.cropRect.right < layerCropRect.right &&
2062 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2063 return parentSettings;
2064 } else {
2065 return layerSettings;
2066 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002067 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002068 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002069 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002070 return parentSettings;
2071 }
2072 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002073}
2074
Robert Carr88b85e12022-03-21 15:47:35 -07002075bool Layer::findInHierarchy(const sp<Layer>& l) {
2076 if (l == this) {
2077 return true;
2078 }
2079 for (auto& child : mDrawingChildren) {
2080 if (child->findInHierarchy(l)) {
2081 return true;
2082 }
2083 }
2084 return false;
2085}
2086
Robert Carr1f0a16a2016-10-24 16:27:39 -07002087void Layer::commitChildList() {
2088 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2089 const auto& child = mCurrentChildren[i];
2090 child->commitChildList();
2091 }
2092 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002093 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002094 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2095 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2096 if (zOrderRelativeOf == nullptr) return;
2097 if (findInHierarchy(zOrderRelativeOf)) {
2098 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2099 zOrderRelativeOf->mName.c_str());
2100 ALOGE("Severing rel Z loop, potentially dangerous");
2101 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002102 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002103 }
2104 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002105}
2106
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002107
chaviw3277faf2021-05-19 16:45:23 -05002108void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002109 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002110 mDrawingState.touchableRegionCrop =
2111 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002112 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002113 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002114 setTransactionFlags(eTransactionNeeded);
2115}
2116
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002117LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002118 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002119 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002120 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2121
Vishnu Nair00b90132021-11-05 14:03:40 -07002122 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002123 writeCompositionStateToProto(layerProto);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002124 }
2125
chaviw08f3cb22020-01-13 13:17:21 -08002126 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002127 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002128 }
chaviw6d89e2d2020-01-14 14:42:01 -08002129
2130 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002131}
2132
Vishnu Nairea6ff812023-02-27 17:41:39 +00002133void Layer::writeCompositionStateToProto(LayerProto* layerProto) {
2134 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2135
2136 // Only populate for the primary display.
2137 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
2138 const auto compositionType = getCompositionType(*display);
2139 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
2140 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2141 [&]() { return layerProto->mutable_visible_region(); });
2142 }
2143}
2144
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002145void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002146 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002147 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002148 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002149 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002150 [&]() { return layerInfo->mutable_active_buffer(); });
2151 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2152 layerInfo->mutable_buffer_transform());
2153 }
2154 layerInfo->set_invalidate(contentDirty);
2155 layerInfo->set_is_protected(isProtected());
2156 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2157 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002158 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002159 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002160 layerInfo->set_corner_radius(
2161 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002162 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2163 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2164 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2165 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2166 [&]() { return layerInfo->mutable_position(); });
2167 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002168 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2169 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002170
Vishnu Nair00b90132021-11-05 14:03:40 -07002171 if (hasColorTransform()) {
2172 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002173 }
2174
Vishnu Nair60db8c02020-04-02 11:55:16 -07002175 LayerProtoHelper::writeToProto(mSourceBounds,
2176 [&]() { return layerInfo->mutable_source_bounds(); });
2177 LayerProtoHelper::writeToProto(mScreenBounds,
2178 [&]() { return layerInfo->mutable_screen_bounds(); });
2179 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2180 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2181 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002182}
2183
2184void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002185 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002186 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2187 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002188 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002189
chaviw766c9c52021-02-10 17:36:47 -08002190 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002191
Vishnu Nair00b90132021-11-05 14:03:40 -07002192 layerInfo->set_id(sequence);
2193 layerInfo->set_name(getName().c_str());
2194 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002195
Vishnu Nair00b90132021-11-05 14:03:40 -07002196 for (const auto& child : children) {
2197 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002198 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002199
Vishnu Nair00b90132021-11-05 14:03:40 -07002200 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2201 sp<Layer> strongRelative = weakRelative.promote();
2202 if (strongRelative != nullptr) {
2203 layerInfo->add_relatives(strongRelative->sequence);
2204 }
2205 }
2206
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002207 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002208 [&]() { return layerInfo->mutable_transparent_region(); });
2209
2210 layerInfo->set_layer_stack(getLayerStack().id);
2211 layerInfo->set_z(state.z);
2212
2213 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2214 return layerInfo->mutable_requested_position();
2215 });
2216
Vishnu Nair00b90132021-11-05 14:03:40 -07002217 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2218
2219 layerInfo->set_is_opaque(isOpaque(state));
2220
2221 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2222 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2223 LayerProtoHelper::writeToProto(state.color,
2224 [&]() { return layerInfo->mutable_requested_color(); });
2225 layerInfo->set_flags(state.flags);
2226
2227 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2228 layerInfo->mutable_requested_transform());
2229
2230 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2231 if (parent != nullptr) {
2232 layerInfo->set_parent(parent->sequence);
2233 } else {
2234 layerInfo->set_parent(-1);
2235 }
2236
2237 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2238 if (zOrderRelativeOf != nullptr) {
2239 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2240 } else {
2241 layerInfo->set_z_order_relative_of(-1);
2242 }
2243
2244 layerInfo->set_is_relative_of(state.isRelativeOf);
2245
2246 layerInfo->set_owner_uid(mOwnerUid);
2247
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002248 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002249 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002250 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002251 info = fillInputInfo(
2252 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002253 } else {
2254 info = state.inputInfo;
2255 }
2256
2257 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002258 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002259 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002260
Vishnu Nair00b90132021-11-05 14:03:40 -07002261 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002262 auto protoMap = layerInfo->mutable_metadata();
2263 for (const auto& entry : state.metadata.mMap) {
2264 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2265 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002266 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002267
2268 LayerProtoHelper::writeToProto(state.destinationFrame,
2269 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002270}
2271
Robert Carr2e102c92018-10-23 12:11:15 -07002272bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002273 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002274}
2275
Prabir Pradhan33da9462022-06-14 14:55:57 +00002276// Applies the given transform to the region, while protecting against overflows caused by any
2277// offsets. If applying the offset in the transform to any of the Rects in the region would result
2278// in an overflow, they are not added to the output Region.
2279static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2280 const std::string& debugWindowName) {
2281 // Round the translation using the same rounding strategy used by ui::Transform.
2282 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2283 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2284
2285 ui::Transform transformWithoutOffset = t;
2286 transformWithoutOffset.set(0.f, 0.f);
2287
2288 const Region transformed = transformWithoutOffset.transform(r);
2289
2290 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2291 Region ret;
2292 for (const auto& rect : transformed) {
2293 Rect newRect;
2294 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2295 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2296 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2297 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2298 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2299 debugWindowName.c_str());
2300 continue;
2301 }
2302 ret.orSelf(newRect);
2303 }
2304 return ret;
2305}
2306
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002307void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002308 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2309 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002310 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002311 }
2312
Vishnu Nairfed7c122023-03-18 01:54:43 +00002313 const Rect roundedFrameInDisplay = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002314 info.frameLeft = roundedFrameInDisplay.left;
2315 info.frameTop = roundedFrameInDisplay.top;
2316 info.frameRight = roundedFrameInDisplay.right;
2317 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002318
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002319 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002320 inputToLayer.set(inputBounds.left, inputBounds.top);
2321 const ui::Transform layerToScreen = getInputTransform();
2322 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002323
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002324 // InputDispatcher expects a display-to-input transform.
2325 info.transform = inputToDisplay.inverse();
2326
2327 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002328 info.touchableRegion =
2329 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002330}
2331
chaviw3277faf2021-05-19 16:45:23 -05002332void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002333 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002334 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002335 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002336 }
2337 if (p != nullptr) {
2338 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2339 }
2340}
2341
Vishnu Naira066d902021-09-13 18:40:17 -07002342gui::DropInputMode Layer::getDropInputMode() const {
2343 gui::DropInputMode mode = mDrawingState.dropInputMode;
2344 if (mode == gui::DropInputMode::ALL) {
2345 return mode;
2346 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002347 sp<Layer> parent = mDrawingParent.promote();
2348 if (parent) {
2349 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002350 if (parentMode != gui::DropInputMode::NONE) {
2351 return parentMode;
2352 }
2353 }
2354 return mode;
2355}
2356
2357void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002358 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002359 return;
2360 }
2361
2362 // Check if we need to drop input unconditionally
2363 gui::DropInputMode dropInputMode = getDropInputMode();
2364 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002365 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002366 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2367 return;
2368 }
2369
2370 // Check if we need to check if the window is obscured by parent
2371 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2372 return;
2373 }
2374
2375 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002376 sp<Layer> parent = mDrawingParent.promote();
2377 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002378 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002379 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2380 static_cast<float>(getAlpha()));
2381 }
2382
2383 // Check if the parent has cropped the buffer
2384 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2385 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002386 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002387 return;
2388 }
2389
2390 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2391 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2392 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2393 // match then the layer has not been cropped by its parents.
2394 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2395 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2396
2397 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002398 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002399 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2400 getDebugName());
2401 } else {
2402 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2403 // input if the window is obscured. This check should be done in surfaceflinger but the
2404 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2405 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002406 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002407 }
2408}
2409
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002410WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002411 if (!hasInputInfo()) {
2412 mDrawingState.inputInfo.name = getName();
2413 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2414 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002415 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002416 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002417 }
2418
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002419 const ui::Transform& displayTransform =
2420 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2421
chaviw3277faf2021-05-19 16:45:23 -05002422 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002423 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002424 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002425
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002426 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002427
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002428 if (displayArgs.transform == nullptr) {
2429 // Do not let the window receive touches if it is not associated with a valid display
2430 // transform. We still allow the window to receive keys and prevent ANRs.
2431 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2432 }
2433
Robert Carr5dc426e2020-06-10 14:29:14 -07002434 // For compatibility reasons we let layers which can receive input
2435 // receive input before they have actually submitted a buffer. Because
2436 // of this we use canReceiveInput instead of isVisible to check the
2437 // policy-visibility, ignoring the buffer state. However for layers with
2438 // hasInputInfo()==false we can use the real visibility state.
2439 // We are just using these layers for occlusion detection in
2440 // InputDispatcher, and obviously if they aren't visible they can't occlude
2441 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002442 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2443 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2444
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002445 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002446 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002447 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002448
Vishnu Nair16a938f2021-09-24 07:14:54 -07002449 // If the window will be blacked out on a display because the display does not have the secure
2450 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002451 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002452 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002453 }
2454
Vishnu Nairfed7c122023-03-18 01:54:43 +00002455 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002456 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002457 Rect inputBoundsInDisplaySpace;
2458 if (!cropLayer) {
2459 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2460 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2461 } else {
2462 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2463 inputBoundsInDisplaySpace =
2464 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2465 }
2466 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002467 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002468 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2469 Rect inputBoundsInDisplaySpace =
2470 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2471 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002472 }
2473
Winson Chunga30f7c92021-06-29 15:42:56 -07002474 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2475 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002476 if (isTrustedOverlay()) {
2477 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2478 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002479
chaviwaf87b3e2019-10-01 16:59:28 -07002480 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2481 // touches from going outside the cloned area.
2482 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002483 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002484 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2485 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002486 info.touchableRegion = info.touchableRegion.intersect(rect);
2487 }
2488 }
2489
Robert Carr720e5062018-07-30 17:45:14 -07002490 return info;
2491}
2492
Vishnu Nairfed7c122023-03-18 01:54:43 +00002493Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2494 const ui::Transform& screenToDisplay) {
2495 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2496 // frame and transform used for the layer, which determines the bounds and the coordinate space
2497 // within which the layer will receive input.
2498
2499 // Coordinate space definitions:
2500 // - display: The display device's coordinate space. Correlates to pixels on the display.
2501 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2502 // - layer: The coordinate space of this layer.
2503 // - input: The coordinate space in which this layer will receive input events. This could be
2504 // different than layer space if a surfaceInset is used, which changes the origin
2505 // of the input space.
2506
2507 // Crop the input bounds to ensure it is within the parent's bounds.
2508 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2509 const ui::Transform layerToScreen = getInputTransform();
2510 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2511 return Rect{layerToDisplay.transform(croppedInputBounds)};
2512}
2513
chaviwaf87b3e2019-10-01 16:59:28 -07002514sp<Layer> Layer::getClonedRoot() {
2515 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002516 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002517 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002518 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002519 return nullptr;
2520 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002521 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002522}
2523
Robert Carredd13602020-04-13 17:24:34 -07002524bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002525 return mDrawingState.inputInfo.token != nullptr ||
2526 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002527}
2528
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002529compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002530 const DisplayDevice* display) const {
2531 if (!display) return nullptr;
Vishnu Naird47bcee2023-02-24 18:08:51 +00002532 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2533 return display->getCompositionDisplay()->getOutputLayerForLayer(
2534 getCompositionEngineLayerFE());
2535 }
2536 sp<LayerFE> layerFE;
2537 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2538 for (auto& [p, layer] : mLayerFEs) {
2539 if (p == path) {
2540 layerFE = layer;
2541 }
2542 }
2543
2544 if (!layerFE) return nullptr;
2545 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002546}
2547
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002548Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2549 const auto outputLayer = findOutputLayerForDisplay(display);
2550 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002551}
2552
chaviwb4c6e582019-08-16 14:35:07 -07002553void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002554 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002555 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002556 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2557 mPotentialCursor = clonedFrom->mPotentialCursor;
2558 mProtectedByApp = clonedFrom->mProtectedByApp;
2559 updateCloneBufferInfo();
2560}
2561
2562void Layer::updateCloneBufferInfo() {
2563 if (!isClone() || !isClonedFromAlive()) {
2564 return;
2565 }
2566
2567 sp<Layer> clonedFrom = getClonedFrom();
2568 mBufferInfo = clonedFrom->mBufferInfo;
2569 mSidebandStream = clonedFrom->mSidebandStream;
2570 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2571 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2572 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2573
2574 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2575 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2576 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2577 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2578 // the cloned drawingState again.
2579 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2580 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2581 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2582 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2583
2584 cloneDrawingState(clonedFrom.get());
2585
2586 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2587 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2588 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2589 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002590}
chaviw74b03172019-08-19 11:09:03 -07002591
2592void Layer::updateMirrorInfo() {
2593 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2594 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2595 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2596 // that case, we want to delete the reference to the clone since we want it to get
2597 // destroyed. The root, this layer, will still be around since the client can continue
2598 // to hold a reference, but no cloned layers will be displayed.
2599 mClonedChild = nullptr;
2600 return;
2601 }
2602
2603 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2604 // If the real layer exists and is in current state, add the clone as a child of the root.
2605 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2606 // copied to drawingState for the root layer. So the clonedChild is always removed from
2607 // drawingState and then needs to be added back each traversal.
2608 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2609 addChildToDrawing(mClonedChild);
2610 }
2611
2612 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002613 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002614 mClonedChild->updateClonedRelatives(clonedLayersMap);
2615}
2616
2617void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2618 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2619 // to the clone. If the real layer is no longer alive, continue traversing the children
2620 // since we may be able to pull out other children that are still alive.
2621 if (isClonedFromAlive()) {
2622 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002623 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002624 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002625 }
2626
2627 // The clone layer may have children in drawingState since they may have been created and
2628 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2629 // that already exist, since we can just re-use them.
2630 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2631 // not updated in the regular traversal. They are skipped since the root will lose the
2632 // reference to them when it copies its currentChildren to drawing.
2633 for (sp<Layer>& child : mDrawingChildren) {
2634 child->updateClonedDrawingState(clonedLayersMap);
2635 }
2636}
2637
2638void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2639 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2640 mDrawingChildren.clear();
2641
2642 if (!isClonedFromAlive()) {
2643 return;
2644 }
2645
2646 sp<Layer> clonedFrom = getClonedFrom();
2647 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2648 if (child == mirrorRoot) {
2649 // This is to avoid cyclical mirroring.
2650 continue;
2651 }
2652 sp<Layer> clonedChild = clonedLayersMap[child];
2653 if (clonedChild == nullptr) {
2654 clonedChild = child->createClone();
2655 clonedLayersMap[child] = clonedChild;
2656 }
2657 addChildToDrawing(clonedChild);
2658 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2659 }
2660}
2661
chaviwaf87b3e2019-10-01 16:59:28 -07002662void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2663 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2664 if (cropLayer != nullptr) {
2665 if (clonedLayersMap.count(cropLayer) == 0) {
2666 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2667 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002668 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002669 } else {
2670 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2671 mDrawingState.touchableRegionCrop = clonedCropLayer;
2672 }
2673 }
2674 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2675 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002676 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002677}
2678
2679void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002680 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002681 mDrawingState.zOrderRelatives.clear();
2682
2683 if (!isClonedFromAlive()) {
2684 return;
2685 }
2686
chaviwaf87b3e2019-10-01 16:59:28 -07002687 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002688 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002689 const sp<Layer>& relative = relativeWeak.promote();
2690 if (clonedLayersMap.count(relative) > 0) {
2691 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002692 mDrawingState.zOrderRelatives.add(clonedRelative);
2693 }
2694 }
2695
2696 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2697 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2698 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2699 // still traverse the children, but the layer with the missing relativeOf will not be shown
2700 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002701 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2702 if (clonedLayersMap.count(relativeOf) > 0) {
2703 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002704 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2705 }
2706
chaviwaf87b3e2019-10-01 16:59:28 -07002707 updateClonedInputInfo(clonedLayersMap);
2708
chaviw74b03172019-08-19 11:09:03 -07002709 for (sp<Layer>& child : mDrawingChildren) {
2710 child->updateClonedRelatives(clonedLayersMap);
2711 }
2712}
2713
2714void Layer::addChildToDrawing(const sp<Layer>& layer) {
2715 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002716 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002717}
2718
Steven Thomas62a4cf82020-01-31 12:04:03 -08002719Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2720 switch (compatibility) {
2721 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2722 return FrameRateCompatibility::Default;
2723 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2724 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002725 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2726 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002727 case ANATIVEWINDOW_FRAME_RATE_MIN:
2728 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002729 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2730 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002731 default:
2732 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2733 return FrameRateCompatibility::Default;
2734 }
2735}
2736
Marin Shalamanovc5986772021-03-16 16:09:49 +01002737scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2738 switch (strategy) {
2739 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2740 return Seamlessness::OnlySeamless;
2741 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2742 return Seamlessness::SeamedAndSeamless;
2743 default:
2744 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2745 return Seamlessness::Default;
2746 }
2747}
2748
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002749bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002750 const State& s(mDrawingState);
2751 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2752 return true;
2753 }
2754
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002755 sp<Layer> parent = mDrawingParent.promote();
2756 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002757}
2758
Robert Carr6a0382d2021-07-01 15:57:17 -07002759void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2760 mClonedChild = clonedChild;
2761 mHadClonedChild = true;
2762 mFlinger->mNumClones++;
2763}
2764
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002765bool Layer::setDropInputMode(gui::DropInputMode mode) {
2766 if (mDrawingState.dropInputMode == mode) {
2767 return false;
2768 }
2769 mDrawingState.dropInputMode = mode;
2770 return true;
2771}
2772
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002773void Layer::cloneDrawingState(const Layer* from) {
2774 mDrawingState = from->mDrawingState;
2775 // Skip callback info since they are not applicable for cloned layers.
2776 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002777 // TODO (b/238781169) currently broken for mirror layers because we do not
2778 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002779 mDrawingState.callbackHandles = {};
2780}
2781
Patrick Williamsbb25f802022-08-30 23:02:34 +00002782void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2783 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002784 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002785 if (!listener) {
2786 return;
2787 }
2788 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002789 uint32_t currentMaxAcquiredBufferCount =
2790 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002791 listener->onReleaseBuffer({buffer->getId(), framenumber},
2792 releaseFence ? releaseFence : Fence::NO_FENCE,
2793 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002794}
2795
2796void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2797 // If we are displayed on multiple displays in a single composition cycle then we would
2798 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2799 // For example we can only use it if all the displays are client comp, and we need
2800 // to merge all the client comp fences. We could do this, but for now we just
2801 // disable the optimization when a layer is composed on multiple displays.
2802 if (mClearClientCompositionFenceOnLayerDisplayed) {
2803 mLastClientCompositionFence = nullptr;
2804 } else {
2805 mClearClientCompositionFenceOnLayerDisplayed = true;
2806 }
2807
2808 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2809 // buffer that was presented on this layer. The first transaction that came in this frame that
2810 // replaced the previous buffer on this layer needs this release fence, because the fence will
2811 // let the client know when that previous buffer is removed from the screen.
2812 //
2813 // Every other transaction on this layer does not need a release fence because no other
2814 // Transactions that were set on this layer this frame are going to have their preceding buffer
2815 // removed from the display this frame.
2816 //
2817 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2818 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2819 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2820 // the previous buffer will be released this frame. The third transaction also contains a
2821 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2822 // transaction will now no longer be presented so it is released immediately and the third
2823 // transaction doesn't need a previous release fence.
2824 sp<CallbackHandle> ch;
2825 for (auto& handle : mDrawingState.callbackHandles) {
2826 if (handle->releasePreviousBuffer &&
2827 mDrawingState.releaseBufferEndpoint == handle->listener) {
2828 ch = handle;
2829 break;
2830 }
2831 }
2832
2833 // Prevent tracing the same release multiple times.
2834 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2835 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2836 }
2837
2838 if (ch != nullptr) {
2839 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2840 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2841 ch->name = mName;
2842 }
2843}
2844
2845void Layer::onSurfaceFrameCreated(
2846 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2847 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2848 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2849 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2850 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002851 if (hasBufferOrSidebandStreamInDrawing()) {
2852 // Only log for layers with a buffer, since we expect the jank data to be drained for
2853 // these, while there may be no jank listeners for bufferless layers.
2854 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2855 mName.c_str());
2856 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2857 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2858 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002859 mPendingJankClassifications.pop_front();
2860 }
2861 mPendingJankClassifications.emplace_back(surfaceFrame);
2862}
2863
2864void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2865 for (const auto& handle : mDrawingState.callbackHandles) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -07002866 if (mFlinger->mLayerLifecycleManagerEnabled) {
2867 handle->transformHint = mTransformHint;
2868 } else {
2869 handle->transformHint = mSkipReportingTransformHint
2870 ? std::nullopt
2871 : std::make_optional<uint32_t>(mTransformHintLegacy);
2872 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002873 handle->dequeueReadyTime = dequeueReadyTime;
2874 handle->currentMaxAcquiredBufferCount =
2875 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2876 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2877 handle->previousReleaseCallbackId.framenumber);
2878 }
2879
2880 for (auto& handle : mDrawingState.callbackHandles) {
2881 if (handle->releasePreviousBuffer &&
2882 mDrawingState.releaseBufferEndpoint == handle->listener) {
2883 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2884 break;
2885 }
2886 }
2887
2888 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002889 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002890 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2891 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002892 mDrawingState.callbackHandles = {};
2893}
2894
2895bool Layer::willPresentCurrentTransaction() const {
2896 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2897 return (getSidebandStreamChanged() || getAutoRefresh() ||
2898 (mDrawingState.modified &&
2899 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2900}
2901
2902bool Layer::setTransform(uint32_t transform) {
2903 if (mDrawingState.bufferTransform == transform) return false;
2904 mDrawingState.bufferTransform = transform;
2905 mDrawingState.modified = true;
2906 setTransactionFlags(eTransactionNeeded);
2907 return true;
2908}
2909
2910bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2911 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2912 mDrawingState.sequence++;
2913 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2914 mDrawingState.modified = true;
2915 setTransactionFlags(eTransactionNeeded);
2916 return true;
2917}
2918
2919bool Layer::setBufferCrop(const Rect& bufferCrop) {
2920 if (mDrawingState.bufferCrop == bufferCrop) return false;
2921
2922 mDrawingState.sequence++;
2923 mDrawingState.bufferCrop = bufferCrop;
2924
2925 mDrawingState.modified = true;
2926 setTransactionFlags(eTransactionNeeded);
2927 return true;
2928}
2929
2930bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2931 if (mDrawingState.destinationFrame == destinationFrame) return false;
2932
2933 mDrawingState.sequence++;
2934 mDrawingState.destinationFrame = destinationFrame;
2935
2936 mDrawingState.modified = true;
2937 setTransactionFlags(eTransactionNeeded);
2938 return true;
2939}
2940
2941// Translate destination frame into scale and position. If a destination frame is not set, use the
2942// provided scale and position
2943bool Layer::updateGeometry() {
2944 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2945 mDrawingState.destinationFrame.isEmpty()) {
2946 // If destination frame is not set, use the requested transform set via
2947 // Layer::setPosition and Layer::setMatrix.
2948 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2949 }
2950
2951 Rect destRect = mDrawingState.destinationFrame;
2952 int32_t destW = destRect.width();
2953 int32_t destH = destRect.height();
2954 if (destRect.left < 0) {
2955 destRect.left = 0;
2956 destRect.right = destW;
2957 }
2958 if (destRect.top < 0) {
2959 destRect.top = 0;
2960 destRect.bottom = destH;
2961 }
2962
2963 if (!mDrawingState.buffer) {
2964 ui::Transform t;
2965 t.set(destRect.left, destRect.top);
2966 return assignTransform(&mDrawingState.transform, t);
2967 }
2968
2969 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2970 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2971 // Undo any transformations on the buffer.
2972 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2973 std::swap(bufferWidth, bufferHeight);
2974 }
2975 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
2976 if (mDrawingState.transformToDisplayInverse) {
2977 if (invTransform & ui::Transform::ROT_90) {
2978 std::swap(bufferWidth, bufferHeight);
2979 }
2980 }
2981
2982 float sx = destW / static_cast<float>(bufferWidth);
2983 float sy = destH / static_cast<float>(bufferHeight);
2984 ui::Transform t;
2985 t.set(sx, 0, 0, sy);
2986 t.set(destRect.left, destRect.top);
2987 return assignTransform(&mDrawingState.transform, t);
2988}
2989
2990bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
2991 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
2992 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
2993 return false;
2994 }
2995
2996 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
2997
2998 mDrawingState.sequence++;
2999 mDrawingState.modified = true;
3000 setTransactionFlags(eTransactionNeeded);
3001
3002 return true;
3003}
3004
3005bool Layer::setPosition(float x, float y) {
3006 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3007 return false;
3008 }
3009
3010 mRequestedTransform.set(x, y);
3011
3012 mDrawingState.sequence++;
3013 mDrawingState.modified = true;
3014 setTransactionFlags(eTransactionNeeded);
3015
3016 return true;
3017}
3018
3019bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3020 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3021 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003022 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003023 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003024 if (!buffer) {
3025 return false;
3026 }
3027
3028 const bool frameNumberChanged =
3029 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3030 const uint64_t frameNumber =
3031 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003032 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003033
3034 if (mDrawingState.buffer) {
3035 mReleasePreviousBuffer = true;
3036 if (!mBufferInfo.mBuffer ||
3037 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3038 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3039 // If mDrawingState has a buffer, and we are about to update again
3040 // before swapping to drawing state, then the first buffer will be
3041 // dropped and we should decrement the pending buffer count and
3042 // call any release buffer callbacks if set.
3043 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3044 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003045 mDrawingState.acquireFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003046 decrementPendingBufferCount();
3047 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3048 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3049 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
3050 mDrawingState.bufferSurfaceFrameTX.reset();
3051 }
3052 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3053 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3054 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003055 mLastClientCompositionFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003056 mLastClientCompositionFence = nullptr;
3057 }
Vishnu Nairc09c0232023-03-02 03:22:35 +00003058 } else {
3059 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3060 // we don't want to incorrectly classify a frame if we miss the desired present time.
3061 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003062 }
3063
liulijuneb489f62022-10-17 22:02:14 +08003064 mDrawingState.producerId = bufferData.producerId;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003065 mDrawingState.frameNumber = frameNumber;
3066 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3067 mDrawingState.buffer = std::move(buffer);
3068 mDrawingState.clientCacheId = bufferData.cachedBuffer;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003069 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3070 ? bufferData.acquireFence
3071 : Fence::NO_FENCE;
3072 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3073 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3074 // We latched this buffer unsiganled, so we need to pass the acquire fence
3075 // on the callback instead of just the acquire time, since it's unknown at
3076 // this point.
3077 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3078 } else {
3079 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3080 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003081 mDrawingState.latchedVsyncId = info.vsyncId;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003082 mDrawingState.modified = true;
3083 setTransactionFlags(eTransactionNeeded);
3084
3085 const int32_t layerId = getSequence();
3086 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3087 mOwnerUid, postTime, getGameMode());
3088 mDrawingState.desiredPresentTime = desiredPresentTime;
3089 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3090
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003091 if (mFlinger->mLegacyFrontEndEnabled) {
3092 recordLayerHistoryBufferUpdate(getLayerProps());
3093 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003094
3095 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3096
3097 if (dequeueTime && *dequeueTime != 0) {
3098 const uint64_t bufferId = mDrawingState.buffer->getId();
3099 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3100 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3101 FrameTracer::FrameEvent::DEQUEUE);
3102 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3103 FrameTracer::FrameEvent::QUEUE);
3104 }
3105
3106 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3107 return true;
3108}
3109
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003110void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3111 mDrawingState.desiredPresentTime = desiredPresentTime;
3112 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3113}
3114
3115void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps) {
3116 const nsecs_t presentTime = [&] {
3117 if (!mDrawingState.isAutoTimestamp) return mDrawingState.desiredPresentTime;
3118
3119 const auto prediction = mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3120 mDrawingState.latchedVsyncId);
3121 if (prediction.has_value()) return prediction->presentTime;
3122
3123 return static_cast<nsecs_t>(0);
3124 }();
3125 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3126 scheduler::LayerHistory::LayerUpdateType::Buffer);
3127}
3128
3129void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps) {
3130 const nsecs_t presentTime =
3131 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
3132 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3133 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3134}
3135
Patrick Williamsbb25f802022-08-30 23:02:34 +00003136bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003137 if (mDrawingState.dataspace == dataspace) return false;
3138 mDrawingState.dataspace = dataspace;
3139 mDrawingState.modified = true;
3140 setTransactionFlags(eTransactionNeeded);
3141 return true;
3142}
3143
John Reck68796592023-01-25 13:47:12 -05003144bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
3145 if (mDrawingState.currentSdrHdrRatio == currentBufferRatio &&
3146 mDrawingState.desiredSdrHdrRatio == desiredRatio)
3147 return false;
3148 mDrawingState.currentSdrHdrRatio = currentBufferRatio;
3149 mDrawingState.desiredSdrHdrRatio = desiredRatio;
3150 mDrawingState.modified = true;
3151 setTransactionFlags(eTransactionNeeded);
3152 return true;
3153}
3154
Alec Mourif4af03e2023-02-11 00:25:24 +00003155bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3156 if (mDrawingState.cachingHint == cachingHint) return false;
3157 mDrawingState.cachingHint = cachingHint;
3158 mDrawingState.modified = true;
3159 setTransactionFlags(eTransactionNeeded);
3160 return true;
3161}
3162
Patrick Williamsbb25f802022-08-30 23:02:34 +00003163bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3164 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3165 mDrawingState.hdrMetadata = hdrMetadata;
3166 mDrawingState.modified = true;
3167 setTransactionFlags(eTransactionNeeded);
3168 return true;
3169}
3170
3171bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003172 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003173 mDrawingState.surfaceDamageRegion = surfaceDamage;
3174 mDrawingState.modified = true;
3175 setTransactionFlags(eTransactionNeeded);
3176 return true;
3177}
3178
3179bool Layer::setApi(int32_t api) {
3180 if (mDrawingState.api == api) return false;
3181 mDrawingState.api = api;
3182 mDrawingState.modified = true;
3183 setTransactionFlags(eTransactionNeeded);
3184 return true;
3185}
3186
3187bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3188 if (mDrawingState.sidebandStream == sidebandStream) return false;
3189
3190 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3191 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3192 } else if (sidebandStream != nullptr) {
3193 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3194 }
3195
3196 mDrawingState.sidebandStream = sidebandStream;
3197 mDrawingState.modified = true;
3198 setTransactionFlags(eTransactionNeeded);
3199 if (!mSidebandStreamChanged.exchange(true)) {
3200 // mSidebandStreamChanged was false
3201 mFlinger->onLayerUpdate();
3202 }
3203 return true;
3204}
3205
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003206bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3207 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003208 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3209 if (handles.empty()) {
3210 mReleasePreviousBuffer = false;
3211 return false;
3212 }
3213
Pascal Muetschard81cef292023-02-06 12:18:52 +01003214 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003215 for (const auto& handle : handles) {
3216 // If this transaction set a buffer on this layer, release its previous buffer
3217 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3218
3219 // If this layer will be presented in this frame
3220 if (willPresent) {
3221 // If this transaction set an acquire fence on this layer, set its acquire time
3222 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3223 handle->frameNumber = mDrawingState.frameNumber;
3224
3225 // Store so latched time and release fence can be set
3226 mDrawingState.callbackHandles.push_back(handle);
3227
3228 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003229 // Queue this handle to be notified below.
3230 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003231 }
3232 }
3233
Pascal Muetschard81cef292023-02-06 12:18:52 +01003234 if (!remainingHandles.empty()) {
3235 // Notify the transaction completed threads these handles are done. These are only the
3236 // handles that were not added to the mDrawingState, which will be notified later.
3237 std::vector<JankData> jankData;
3238 transferAvailableJankData(remainingHandles, jankData);
3239 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3240 }
3241
Patrick Williamsbb25f802022-08-30 23:02:34 +00003242 mReleasePreviousBuffer = false;
3243 mCallbackHandleAcquireTimeOrFence = -1;
3244
3245 return willPresent;
3246}
3247
3248Rect Layer::getBufferSize(const State& /*s*/) const {
3249 // for buffer state layers we use the display frame size as the buffer size.
3250
3251 if (mBufferInfo.mBuffer == nullptr) {
3252 return Rect::INVALID_RECT;
3253 }
3254
3255 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3256 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3257
3258 // Undo any transformations on the buffer and return the result.
3259 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3260 std::swap(bufWidth, bufHeight);
3261 }
3262
3263 if (getTransformToDisplayInverse()) {
3264 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3265 if (invTransform & ui::Transform::ROT_90) {
3266 std::swap(bufWidth, bufHeight);
3267 }
3268 }
3269
3270 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3271}
3272
3273FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3274 if (mBufferInfo.mBuffer == nullptr) {
3275 return parentBounds;
3276 }
3277
3278 return getBufferSize(getDrawingState()).toFloatRect();
3279}
3280
3281bool Layer::fenceHasSignaled() const {
3282 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3283 return true;
3284 }
3285
3286 const bool fenceSignaled =
3287 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3288 if (!fenceSignaled) {
3289 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3290 TimeStats::LatchSkipReason::LateAcquire);
3291 }
3292
3293 return fenceSignaled;
3294}
3295
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003296void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003297 for (const auto& handle : mDrawingState.callbackHandles) {
3298 handle->refreshStartTime = refreshStartTime;
3299 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003300}
3301
3302void Layer::setAutoRefresh(bool autoRefresh) {
3303 mDrawingState.autoRefresh = autoRefresh;
3304}
3305
3306bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3307 // 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 +00003308 auto* snapshot = editLayerSnapshot();
3309 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003310
3311 if (mSidebandStreamChanged.exchange(false)) {
3312 const State& s(getDrawingState());
3313 // mSidebandStreamChanged was true
3314 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003315 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003316 if (mSidebandStream != nullptr) {
3317 setTransactionFlags(eTransactionNeeded);
3318 mFlinger->setTransactionFlags(eTraversalNeeded);
3319 }
3320 recomputeVisibleRegions = true;
3321
3322 return true;
3323 }
3324 return false;
3325}
3326
3327bool Layer::hasFrameUpdate() const {
3328 const State& c(getDrawingState());
3329 return (mDrawingStateModified || mDrawingState.modified) &&
3330 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3331}
3332
Vishnu Naird47bcee2023-02-24 18:08:51 +00003333void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003334 const State& s(getDrawingState());
3335
3336 if (!s.buffer) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003337 if (bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003338 for (auto& handle : mDrawingState.callbackHandles) {
3339 handle->latchTime = latchTime;
3340 }
3341 }
3342 return;
3343 }
3344
3345 for (auto& handle : mDrawingState.callbackHandles) {
3346 if (handle->frameNumber == mDrawingState.frameNumber) {
3347 handle->latchTime = latchTime;
3348 }
3349 }
3350
3351 const int32_t layerId = getSequence();
3352 const uint64_t bufferId = mDrawingState.buffer->getId();
3353 const uint64_t frameNumber = mDrawingState.frameNumber;
3354 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3355 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3356 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3357
3358 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3359 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3360 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3361 FrameTracer::FrameEvent::LATCH);
3362
3363 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3364 if (bufferSurfaceFrame != nullptr &&
3365 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3366 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3367 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3368 // are processing the next state.
3369 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3370 mDrawingState.acquireFenceTime->getSignalTime(),
3371 latchTime);
3372 mDrawingState.bufferSurfaceFrameTX.reset();
3373 }
3374
3375 std::deque<sp<CallbackHandle>> remainingHandles;
3376 mFlinger->getTransactionCallbackInvoker()
3377 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3378 mDrawingState.callbackHandles = remainingHandles;
3379
3380 mDrawingStateModified = false;
3381}
3382
3383void Layer::gatherBufferInfo() {
3384 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3385 decrementPendingBufferCount();
3386 }
3387
3388 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3389 mBufferInfo.mBuffer = mDrawingState.buffer;
3390 mBufferInfo.mFence = mDrawingState.acquireFence;
3391 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3392 mBufferInfo.mPixelFormat =
3393 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3394 mBufferInfo.mFrameLatencyNeeded = true;
3395 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3396 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3397 mBufferInfo.mFence = mDrawingState.acquireFence;
3398 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3399 auto lastDataspace = mBufferInfo.mDataspace;
3400 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003401 if (mBufferInfo.mBuffer != nullptr) {
3402 auto& mapper = GraphicBufferMapper::get();
3403 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
3404 // and don't need to possibly remaps buffers.
3405 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
3406 status_t err = OK;
3407 {
3408 ATRACE_NAME("getDataspace");
3409 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
3410 }
3411 if (err != OK || dataspace != mBufferInfo.mDataspace) {
3412 {
3413 ATRACE_NAME("setDataspace");
3414 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
3415 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
3416 }
3417
3418 // Some GPU drivers may cache gralloc metadata which means before we composite we need
3419 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
3420 // compatible with old vendors, with a ticking clock.
3421 static const int32_t kVendorVersion =
3422 base::GetIntProperty("ro.vndk.version", __ANDROID_API_FUTURE__);
3423 if (const auto format =
3424 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
3425 mBufferInfo.mBuffer->getPixelFormat());
3426 err == OK && kVendorVersion < __ANDROID_API_U__ &&
3427 (format ==
3428 aidl::android::hardware::graphics::common::PixelFormat::
3429 IMPLEMENTATION_DEFINED ||
3430 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
3431 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
3432 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
3433 mBufferInfo.mBuffer->remapBuffer();
3434 }
3435 }
3436 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003437 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003438 mFlinger->mHdrLayerInfoChanged = true;
3439 }
3440 if (mBufferInfo.mDesiredSdrHdrRatio != mDrawingState.desiredSdrHdrRatio) {
3441 mBufferInfo.mDesiredSdrHdrRatio = mDrawingState.desiredSdrHdrRatio;
3442 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003443 }
3444 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3445 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3446 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3447 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3448 mBufferInfo.mApi = mDrawingState.api;
3449 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003450}
3451
3452Rect Layer::computeBufferCrop(const State& s) {
3453 if (s.buffer && !s.bufferCrop.isEmpty()) {
3454 Rect bufferCrop;
3455 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3456 return bufferCrop;
3457 } else if (s.buffer) {
3458 return s.buffer->getBounds();
3459 } else {
3460 return s.bufferCrop;
3461 }
3462}
3463
3464sp<Layer> Layer::createClone() {
3465 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3466 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003467 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003468 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3469 return layer;
3470}
3471
Patrick Williamsbb25f802022-08-30 23:02:34 +00003472void Layer::decrementPendingBufferCount() {
3473 int32_t pendingBuffers = --mPendingBufferTransactions;
3474 tracePendingBufferCount(pendingBuffers);
3475}
3476
3477void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3478 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3479}
3480
3481/*
3482 * We don't want to send the layer's transform to input, but rather the
3483 * parent's transform. This is because Layer's transform is
3484 * information about how the buffer is placed on screen. The parent's
3485 * transform makes more sense to send since it's information about how the
3486 * layer is placed on screen. This transform is used by input to determine
3487 * how to go from screen space back to window space.
3488 */
3489ui::Transform Layer::getInputTransform() const {
3490 if (!hasBufferOrSidebandStream()) {
3491 return getTransform();
3492 }
3493 sp<Layer> parent = mDrawingParent.promote();
3494 if (parent == nullptr) {
3495 return ui::Transform();
3496 }
3497
3498 return parent->getTransform();
3499}
3500
3501/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003502 * Returns the bounds used to fill the input frame and the touchable region.
3503 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003504 * Similar to getInputTransform, we need to update the bounds to include the transform.
3505 * This is because bounds don't include the buffer transform, where the input assumes
3506 * that's already included.
3507 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003508std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3509 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3510 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3511 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3512 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3513 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003514 }
3515
Vishnu Nairfed7c122023-03-18 01:54:43 +00003516 bool inputBoundsValid = croppedBufferSize.isValid();
3517 if (!inputBoundsValid) {
3518 /**
3519 * Input bounds are based on the layer crop or buffer size. But if we are using
3520 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3521 * we can use the parent bounds as the input bounds if the layer does not have buffer
3522 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3523 * use the parent bounds. A layer without a buffer can get input. So when a window is
3524 * initially added, its touchable region can fill its parent layer bounds and that can
3525 * have negative consequences.
3526 */
3527 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003528 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003529
3530 // Clamp surface inset to the input bounds.
3531 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3532 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3533 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3534
3535 // Apply the insets to the input bounds.
3536 inputBounds.left += xSurfaceInset;
3537 inputBounds.top += ySurfaceInset;
3538 inputBounds.right -= xSurfaceInset;
3539 inputBounds.bottom -= ySurfaceInset;
3540
3541 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003542}
3543
3544bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3545 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3546
3547 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3548 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3549 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3550 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3551 layer_state_t::eReparent;
3552
3553 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3554 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3555 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3556 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3557 layer_state_t::eInputInfoChanged;
3558
3559 if ((s.what & requiredFlags) != requiredFlags) {
3560 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3561 (s.what | requiredFlags) & ~s.what);
3562 return false;
3563 }
3564
3565 if (s.what & deniedFlags) {
3566 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3567 return false;
3568 }
3569
3570 if (s.what & allowedFlags) {
3571 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3572 }
3573
3574 if (s.what & layer_state_t::ePositionChanged) {
3575 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3576 ALOGV("%s: false [ePositionChanged changed]", __func__);
3577 return false;
3578 }
3579 }
3580
3581 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003582 if (mDrawingState.color.a != s.color.a) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003583 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3584 return false;
3585 }
3586 }
3587
3588 if (s.what & layer_state_t::eColorTransformChanged) {
3589 if (mDrawingState.colorTransform != s.colorTransform) {
3590 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3591 return false;
3592 }
3593 }
3594
3595 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003596 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003597 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3598 return false;
3599 }
3600 }
3601
3602 if (s.what & layer_state_t::eMatrixChanged) {
3603 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3604 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3605 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3606 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3607 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3608 return false;
3609 }
3610 }
3611
3612 if (s.what & layer_state_t::eCornerRadiusChanged) {
3613 if (mDrawingState.cornerRadius != s.cornerRadius) {
3614 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3615 return false;
3616 }
3617 }
3618
3619 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3620 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3621 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3622 return false;
3623 }
3624 }
3625
Vishnu Nairbbceb462022-10-10 04:52:13 +00003626 if (s.what & layer_state_t::eBufferTransformChanged) {
3627 if (mDrawingState.bufferTransform != s.bufferTransform) {
3628 ALOGV("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003629 return false;
3630 }
3631 }
3632
3633 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3634 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3635 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3636 return false;
3637 }
3638 }
3639
3640 if (s.what & layer_state_t::eCropChanged) {
3641 if (mDrawingState.crop != s.crop) {
3642 ALOGV("%s: false [eCropChanged changed]", __func__);
3643 return false;
3644 }
3645 }
3646
3647 if (s.what & layer_state_t::eDataspaceChanged) {
3648 if (mDrawingState.dataspace != s.dataspace) {
3649 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3650 return false;
3651 }
3652 }
3653
3654 if (s.what & layer_state_t::eHdrMetadataChanged) {
3655 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3656 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3657 return false;
3658 }
3659 }
3660
3661 if (s.what & layer_state_t::eSidebandStreamChanged) {
3662 if (mDrawingState.sidebandStream != s.sidebandStream) {
3663 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3664 return false;
3665 }
3666 }
3667
3668 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3669 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3670 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3671 return false;
3672 }
3673 }
3674
3675 if (s.what & layer_state_t::eShadowRadiusChanged) {
3676 if (mDrawingState.shadowRadius != s.shadowRadius) {
3677 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3678 return false;
3679 }
3680 }
3681
3682 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3683 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3684 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3685 return false;
3686 }
3687 }
3688
3689 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3690 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3691 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3692 return false;
3693 }
3694 }
3695
3696 if (s.what & layer_state_t::eStretchChanged) {
3697 StretchEffect temp = s.stretchEffect;
3698 temp.sanitize();
3699 if (mDrawingState.stretchEffect != temp) {
3700 ALOGV("%s: false [eStretchChanged changed]", __func__);
3701 return false;
3702 }
3703 }
3704
3705 if (s.what & layer_state_t::eBufferCropChanged) {
3706 if (mDrawingState.bufferCrop != s.bufferCrop) {
3707 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3708 return false;
3709 }
3710 }
3711
3712 if (s.what & layer_state_t::eDestinationFrameChanged) {
3713 if (mDrawingState.destinationFrame != s.destinationFrame) {
3714 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3715 return false;
3716 }
3717 }
3718
3719 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3720 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3721 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3722 return false;
3723 }
3724 }
3725
John Reck68796592023-01-25 13:47:12 -05003726 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
3727 if (mDrawingState.currentSdrHdrRatio != s.currentSdrHdrRatio ||
3728 mDrawingState.desiredSdrHdrRatio != s.desiredSdrHdrRatio) {
3729 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3730 return false;
3731 }
3732 }
3733
Patrick Williamsbb25f802022-08-30 23:02:34 +00003734 ALOGV("%s: true", __func__);
3735 return true;
3736}
3737
3738bool Layer::isHdrY410() const {
3739 // pixel format is HDR Y410 masquerading as RGBA_1010102
3740 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3741 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3742 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3743}
3744
Vishnu Naire14c6b32022-08-06 04:20:15 +00003745sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003746 // 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 +00003747 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003748}
3749
Vishnu Naire14c6b32022-08-06 04:20:15 +00003750const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003751 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003752}
3753
Vishnu Naire14c6b32022-08-06 04:20:15 +00003754LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003755 return mSnapshot.get();
3756}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003757
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003758std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3759 return std::move(mSnapshot);
3760}
3761
3762void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3763 mSnapshot = std::move(snapshot);
3764}
3765
Patrick Williamsbb25f802022-08-30 23:02:34 +00003766const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003767 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003768}
3769
Patrick Williams7584c6a2022-10-29 02:10:58 +00003770sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003771 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003772 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3773 return result;
3774}
3775
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003776sp<LayerFE> Layer::getCompositionEngineLayerFE(
3777 const frontend::LayerHierarchy::TraversalPath& path) {
3778 for (auto& [p, layerFE] : mLayerFEs) {
3779 if (p == path) {
3780 return layerFE;
3781 }
3782 }
3783 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3784 mLayerFEs.emplace_back(path, layerFE);
3785 return layerFE;
3786}
3787
Patrick Williamsbb25f802022-08-30 23:02:34 +00003788void Layer::useSurfaceDamage() {
3789 if (mFlinger->mForceFullDamage) {
3790 surfaceDamageRegion = Region::INVALID_REGION;
3791 } else {
3792 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3793 }
3794}
3795
3796void Layer::useEmptyDamage() {
3797 surfaceDamageRegion.clear();
3798}
3799
3800bool Layer::isOpaque(const Layer::State& s) const {
3801 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3802 // layer's opaque flag.
3803 if (!hasSomethingToDraw()) {
3804 return false;
3805 }
3806
3807 // if the layer has the opaque flag, then we're always opaque
3808 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3809 return true;
3810 }
3811
3812 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003813 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003814 return true;
3815 }
3816
3817 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3818 return fillsColor() && getAlpha() == 1.0_hf;
3819}
3820
3821bool Layer::canReceiveInput() const {
3822 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3823}
3824
3825bool Layer::isVisible() const {
3826 if (!hasSomethingToDraw()) {
3827 return false;
3828 }
3829
3830 if (isHiddenByPolicy()) {
3831 return false;
3832 }
3833
3834 return getAlpha() > 0.0f || hasBlur();
3835}
3836
3837void Layer::onPostComposition(const DisplayDevice* display,
3838 const std::shared_ptr<FenceTime>& glDoneFence,
3839 const std::shared_ptr<FenceTime>& presentFence,
3840 const CompositorTiming& compositorTiming) {
3841 // mFrameLatencyNeeded is true when a new frame was latched for the
3842 // composition.
3843 if (!mBufferInfo.mFrameLatencyNeeded) return;
3844
3845 for (const auto& handle : mDrawingState.callbackHandles) {
3846 handle->gpuCompositionDoneFence = glDoneFence;
3847 handle->compositorTiming = compositorTiming;
3848 }
3849
3850 // Update mFrameTracker.
3851 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3852 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3853
3854 const int32_t layerId = getSequence();
3855 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3856
3857 const auto outputLayer = findOutputLayerForDisplay(display);
3858 if (outputLayer && outputLayer->requiresClientComposition()) {
3859 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3860 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3861 clientCompositionTimestamp,
3862 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3863 // Update the SurfaceFrames in the drawing state
3864 if (mDrawingState.bufferSurfaceFrameTX) {
3865 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3866 }
3867 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3868 surfaceFrame->setGpuComposition();
3869 }
3870 }
3871
3872 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3873 if (frameReadyFence->isValid()) {
3874 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3875 } else {
3876 // There was no fence for this frame, so assume that it was ready
3877 // to be presented at the desired present time.
3878 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3879 }
3880
3881 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08003882 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003883 const std::optional<Fps> renderRate =
3884 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3885
3886 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3887 const auto gameMode = getGameMode();
3888
3889 if (presentFence->isValid()) {
3890 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3891 refreshRate, renderRate, vote, gameMode);
3892 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3893 presentFence,
3894 FrameTracer::FrameEvent::PRESENT_FENCE);
3895 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3896 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3897 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003898 // The HWC doesn't support present fences, so use the present timestamp instead.
3899 const nsecs_t presentTimestamp =
3900 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3901
3902 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3903 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3904 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3905
Patrick Williamsbb25f802022-08-30 23:02:34 +00003906 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3907 refreshRate, renderRate, vote, gameMode);
3908 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3909 mCurrentFrameNumber, actualPresentTime,
3910 FrameTracer::FrameEvent::PRESENT_FENCE);
3911 mFrameTracker.setActualPresentTime(actualPresentTime);
3912 }
3913 }
3914
3915 mFrameTracker.advanceFrame();
3916 mBufferInfo.mFrameLatencyNeeded = false;
3917}
3918
3919bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003920 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
3921 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
3922}
3923
3924bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003925 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3926 getDrawingState().frameNumber);
3927
3928 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3929
3930 if (refreshRequired) {
3931 return refreshRequired;
3932 }
3933
3934 // If the head buffer's acquire fence hasn't signaled yet, return and
3935 // try again later
3936 if (!fenceHasSignaled()) {
3937 ATRACE_NAME("!fenceHasSignaled()");
3938 mFlinger->onLayerUpdate();
3939 return false;
3940 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00003941 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003942 if (mDrawingState.buffer == nullptr) {
3943 return false;
3944 }
3945
3946 // Capture the old state of the layer for comparisons later
3947 BufferInfo oldBufferInfo = mBufferInfo;
3948 const bool oldOpacity = isOpaque(mDrawingState);
3949 mPreviousFrameNumber = mCurrentFrameNumber;
3950 mCurrentFrameNumber = mDrawingState.frameNumber;
3951 gatherBufferInfo();
3952
3953 if (oldBufferInfo.mBuffer == nullptr) {
3954 // the first time we receive a buffer, we need to trigger a
3955 // geometry invalidation.
3956 recomputeVisibleRegions = true;
3957 }
3958
3959 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3960 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3961 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3962 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3963 recomputeVisibleRegions = true;
3964 }
3965
3966 if (oldBufferInfo.mBuffer != nullptr) {
3967 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3968 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3969 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3970 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3971 recomputeVisibleRegions = true;
3972 }
3973 }
3974
3975 if (oldOpacity != isOpaque(mDrawingState)) {
3976 recomputeVisibleRegions = true;
3977 }
3978
3979 return true;
3980}
3981
3982bool Layer::hasReadyFrame() const {
3983 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
3984}
3985
3986bool Layer::isProtected() const {
3987 return (mBufferInfo.mBuffer != nullptr) &&
3988 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
3989}
3990
Patrick Williamsbb25f802022-08-30 23:02:34 +00003991void Layer::latchAndReleaseBuffer() {
3992 if (hasReadyFrame()) {
3993 bool ignored = false;
3994 latchBuffer(ignored, systemTime());
3995 }
3996 releasePendingBuffer(systemTime());
3997}
3998
3999PixelFormat Layer::getPixelFormat() const {
4000 return mBufferInfo.mPixelFormat;
4001}
4002
4003bool Layer::getTransformToDisplayInverse() const {
4004 return mBufferInfo.mTransformToDisplayInverse;
4005}
4006
4007Rect Layer::getBufferCrop() const {
4008 // this is the crop rectangle that applies to the buffer
4009 // itself (as opposed to the window)
4010 if (!mBufferInfo.mCrop.isEmpty()) {
4011 // if the buffer crop is defined, we use that
4012 return mBufferInfo.mCrop;
4013 } else if (mBufferInfo.mBuffer != nullptr) {
4014 // otherwise we use the whole buffer
4015 return mBufferInfo.mBuffer->getBounds();
4016 } else {
4017 // if we don't have a buffer yet, we use an empty/invalid crop
4018 return Rect();
4019 }
4020}
4021
4022uint32_t Layer::getBufferTransform() const {
4023 return mBufferInfo.mTransform;
4024}
4025
4026ui::Dataspace Layer::getDataSpace() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004027 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4028}
4029
4030ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4031 ui::Dataspace updatedDataspace = dataspace;
4032 // translate legacy dataspaces to modern dataspaces
4033 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00004034 // Treat unknown dataspaces as V0_sRGB
4035 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00004036 case ui::Dataspace::SRGB:
4037 updatedDataspace = ui::Dataspace::V0_SRGB;
4038 break;
4039 case ui::Dataspace::SRGB_LINEAR:
4040 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4041 break;
4042 case ui::Dataspace::JFIF:
4043 updatedDataspace = ui::Dataspace::V0_JFIF;
4044 break;
4045 case ui::Dataspace::BT601_625:
4046 updatedDataspace = ui::Dataspace::V0_BT601_625;
4047 break;
4048 case ui::Dataspace::BT601_525:
4049 updatedDataspace = ui::Dataspace::V0_BT601_525;
4050 break;
4051 case ui::Dataspace::BT709:
4052 updatedDataspace = ui::Dataspace::V0_BT709;
4053 break;
4054 default:
4055 break;
4056 }
4057
4058 return updatedDataspace;
4059}
4060
4061sp<GraphicBuffer> Layer::getBuffer() const {
4062 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4063}
4064
Vishnu Nairb76d99a2023-03-19 18:22:31 -07004065void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4066 mTransformHintLegacy = getFixedTransformHint();
4067 if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4068 mTransformHintLegacy = displayTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004069 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004070 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004071}
4072
4073const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4074 return mBufferInfo.mBuffer;
4075}
4076
4077bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004078 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004079 return false;
4080 }
4081
4082 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004083 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004084 mDrawingState.modified = true;
4085 setTransactionFlags(eTransactionNeeded);
4086 return true;
4087}
4088
4089bool Layer::fillsColor() const {
4090 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4091 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4092}
4093
4094bool Layer::hasBlur() const {
4095 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4096}
4097
Vishnu Nairba354102022-08-01 00:14:18 +00004098void Layer::updateSnapshot(bool updateGeometry) {
4099 if (!getCompositionEngineLayerFE()) {
4100 return;
4101 }
4102
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004103 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004104 if (updateGeometry) {
4105 prepareBasicGeometryCompositionState();
4106 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004107 snapshot->roundedCorner = getRoundedCornerState();
4108 snapshot->stretchEffect = getStretchEffect();
4109 snapshot->transformedBounds = mScreenBounds;
4110 if (mEffectiveShadowRadius > 0.f) {
4111 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4112
4113 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4114 // it if transparent regions are present. This may not be necessary since shadows are
4115 // typically cast by layers without transparent regions.
4116 snapshot->shadowSettings.boundaries = mBounds;
4117
4118 const float casterAlpha = snapshot->alpha;
4119 const bool casterIsOpaque =
4120 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4121
4122 // If the casting layer is translucent, we need to fill in the shadow underneath the
4123 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4124 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4125 snapshot->shadowSettings.ambientColor *= casterAlpha;
4126 snapshot->shadowSettings.spotColor *= casterAlpha;
4127 }
4128 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004129 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004130 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004131 snapshot->layerOpaqueFlagSet =
4132 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004133 snapshot->isHdrY410 = isHdrY410();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004134 sp<Layer> p = mDrawingParent.promote();
4135 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004136 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004137 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004138 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004139 }
4140 snapshot->bufferSize = getBufferSize(mDrawingState);
4141 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004142 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004143 preparePerFrameCompositionState();
4144}
4145
Vishnu Naire14c6b32022-08-06 04:20:15 +00004146void Layer::updateChildrenSnapshots(bool updateGeometry) {
4147 for (const sp<Layer>& child : mDrawingChildren) {
4148 child->updateSnapshot(updateGeometry);
4149 child->updateChildrenSnapshots(updateGeometry);
4150 }
4151}
4152
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004153void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4154 mSnapshot->layerMetadata = parentMetadata;
4155 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4156 for (const sp<Layer>& child : mDrawingChildren) {
4157 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4158 }
4159}
4160
4161void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4162 std::unordered_set<Layer*>& visited) {
4163 if (visited.find(this) != visited.end()) {
4164 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4165 return;
4166 }
4167 visited.insert(this);
4168
4169 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4170
4171 if (mDrawingState.zOrderRelatives.empty()) {
4172 return;
4173 }
4174 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4175 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4176 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4177 sp<Layer> relative = weakRelative.promote();
4178 if (!relative) {
4179 continue;
4180 }
4181 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4182 }
4183}
4184
Chavi Weingarten328a8312023-01-26 21:17:52 +00004185bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004186 TrustedPresentationListener const& listener) {
4187 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4188 mTrustedPresentationListener = listener;
4189 mTrustedPresentationThresholds = thresholds;
4190 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4191 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4192 mFlinger->mNumTrustedPresentationListeners++;
4193 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4194 mFlinger->mNumTrustedPresentationListeners--;
4195 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004196
4197 // Reset trusted presentation states to ensure we start the time again.
4198 mEnteredTrustedPresentationStateTime = -1;
4199 mLastReportedTrustedPresentationState = false;
4200 mLastComputedTrustedPresentationState = false;
4201
4202 // If there's a new trusted presentation listener, the code needs to go through the composite
4203 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4204 // we're already in the requested state.
4205 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004206}
4207
Vishnu Naira156f482023-02-22 00:23:38 +00004208void Layer::updateLastLatchTime(nsecs_t latchTime) {
4209 mLastLatchTime = latchTime;
4210}
4211
Mathias Agopian13127d82013-03-05 17:47:11 -08004212// ---------------------------------------------------------------------------
4213
Marin Shalamanov46084422020-10-13 12:33:42 +02004214std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004215 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4216 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004217}
4218
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004219} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004220
4221#if defined(__gl_h_)
4222#error "don't include gl/gl.h in this file"
4223#endif
4224
4225#if defined(__gl2_h_)
4226#error "don't include gl2/gl2.h in this file"
4227#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004228
4229// TODO(b/129481165): remove the #pragma below and fix conversion issues
4230#pragma clang diagnostic pop // ignored "-Wconversion"