blob: 3b4145847530347e02307b311ff1cd6c213da7f2 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Dan Stoza9e56aa02015-11-02 13:00:03 -080021//#define LOG_NDEBUG 0
22#undef LOG_TAG
23#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080024#define ATRACE_TAG ATRACE_TAG_GRAPHICS
25
Alec Mourie60041e2019-06-14 18:59:51 -070026#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080027
[1;3C2b9fc252021-02-04 16:16:50 -080028#include <android-base/properties.h>
Yiwei Zhang5434a782018-12-05 18:06:32 -080029#include <android-base/stringprintf.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080030#include <android/native_window.h>
Vishnu Nair0f085c62019-08-30 08:49:12 -070031#include <binder/IPCThreadState.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000032#include <compositionengine/CompositionEngine.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080033#include <compositionengine/Display.h>
Lloyd Piquea83776c2019-01-29 18:42:32 -080034#include <compositionengine/LayerFECompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080035#include <compositionengine/OutputLayer.h>
36#include <compositionengine/impl/OutputLayerCompositionState.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070037#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070038#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070039#include <cutils/properties.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070040#include <ftl/enum.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080041#include <ftl/fake_guard.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080042#include <gui/BufferItem.h>
43#include <gui/LayerDebugInfo.h>
44#include <gui/Surface.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000045#include <gui/TraceUtils.h>
Alec Mourie60041e2019-06-14 18:59:51 -070046#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070047#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070049#include <stdint.h>
50#include <stdlib.h>
51#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000052#include <system/graphics-base-v1.0.h>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070053#include <ui/DataspaceUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080054#include <ui/DebugUtils.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000055#include <ui/FloatRect.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080056#include <ui/GraphicBuffer.h>
57#include <ui/PixelFormat.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000058#include <ui/Rect.h>
59#include <ui/Transform.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060#include <utils/Errors.h>
61#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080062#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080064#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065
Alec Mourie60041e2019-06-14 18:59:51 -070066#include <algorithm>
67#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070068#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070069#include <sstream>
70
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070071#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080072#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070073#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070074#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +000075#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000076#include "FrontEnd/LayerHandle.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080077#include "LayerProtoHelper.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080079#include "TimeStats/TimeStats.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070080#include "TunnelModeEnabledReporter.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070081
David Sodman41fdfc92017-11-06 16:09:56 -080082#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000083#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085namespace android {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010086namespace {
87constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000088
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000089const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000090
Patrick Williamsbb25f802022-08-30 23:02:34 +000091bool assignTransform(ui::Transform* dst, ui::Transform& from) {
92 if (*dst == from) {
93 return false;
94 }
95 *dst = from;
96 return true;
97}
98
99TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
100 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
101 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
102 const auto frameRateCompatibility = [frameRate] {
103 switch (frameRate.type) {
104 case Layer::FrameRateCompatibility::Default:
105 return FrameRateCompatibility::Default;
106 case Layer::FrameRateCompatibility::ExactOrMultiple:
107 return FrameRateCompatibility::ExactOrMultiple;
108 default:
109 return FrameRateCompatibility::Undefined;
110 }
111 }();
112
113 const auto seamlessness = [frameRate] {
114 switch (frameRate.seamlessness) {
115 case scheduler::Seamlessness::OnlySeamless:
116 return Seamlessness::ShouldBeSeamless;
117 case scheduler::Seamlessness::SeamedAndSeamless:
118 return Seamlessness::NotRequired;
119 default:
120 return Seamlessness::Undefined;
121 }
122 }();
123
124 return TimeStats::SetFrameRateVote{.frameRate = frameRate.rate.getValue(),
125 .frameRateCompatibility = frameRateCompatibility,
126 .seamlessness = seamlessness};
127}
128
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100129} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800130
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700131using namespace ftl::flag_operators;
132
Yiwei Zhang5434a782018-12-05 18:06:32 -0800133using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000134using frontend::LayerSnapshot;
135using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800136using gui::GameMode;
137using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500138using gui::WindowInfo;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800139
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700140using PresentState = frametimeline::SurfaceFrame::PresentState;
141
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700142Layer::Layer(const LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000143 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700144 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000145 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700146 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800147 mWindowType(static_cast<WindowInfo::Type>(
148 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000149 mLayerCreationFlags(args.flags),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000150 mBorderEnabled(false),
151 mTextureName(args.textureName),
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000152 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000153 ALOGV("Creating Layer %s", getDebugName());
154
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700155 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700156 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
157 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
158 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700159 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
160 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700161 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700162 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700163 mDrawingState.z = 0;
164 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700165 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700166 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700167 mDrawingState.transform.set(0, 0);
168 mDrawingState.frameNumber = 0;
169 mDrawingState.bufferTransform = 0;
170 mDrawingState.transformToDisplayInverse = false;
171 mDrawingState.crop.makeInvalid();
172 mDrawingState.acquireFence = sp<Fence>::make(-1);
173 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
174 mDrawingState.dataspace = ui::Dataspace::UNKNOWN;
Vishnu Nairbc4ee5c2022-08-16 03:19:37 +0000175 mDrawingState.dataspaceRequested = false;
Robert Carr6a160312021-05-17 12:08:20 -0700176 mDrawingState.hdrMetadata.validTypes = 0;
177 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
178 mDrawingState.cornerRadius = 0.0f;
179 mDrawingState.backgroundBlurRadius = 0;
180 mDrawingState.api = -1;
181 mDrawingState.hasColorTransform = false;
182 mDrawingState.colorSpaceAgnostic = false;
183 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
184 mDrawingState.metadata = args.metadata;
185 mDrawingState.shadowRadius = 0.f;
186 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
187 mDrawingState.frameTimelineInfo = {};
188 mDrawingState.postTime = -1;
189 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000190 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700191 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700192 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000193 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700194
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700195 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
196 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700197 mDrawingState.color.r = -1.0_hf;
198 mDrawingState.color.g = -1.0_hf;
199 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700200 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700201
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500202 mFrameTracker.setDisplayRefreshPeriod(
203 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700204
Vishnu Naircb8be502022-10-12 19:03:23 +0000205 mOwnerUid = args.ownerUid;
206 mOwnerPid = args.ownerPid;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000207
208 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
209 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
210 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
211 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000212
213 mSnapshot->sequence = sequence;
214 mSnapshot->name = getDebugName();
215 mSnapshot->textureName = mTextureName;
216 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000217 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800218}
219
220void Layer::onFirstRef() {
221 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700222}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700223
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700224Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000225 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
226 "Layer destructor called off the main thread.");
227
Patrick Williamsbb25f802022-08-30 23:02:34 +0000228 // The original layer and the clone layer share the same texture and buffer. Therefore, only
229 // one of the layers, in this case the original layer, needs to handle the deletion. The
230 // original layer and the clone should be removed at the same time so there shouldn't be any
231 // issue with the clone layer trying to use the texture.
232 if (mBufferInfo.mBuffer != nullptr) {
233 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
234 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800235 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000236 }
237 if (!isClone()) {
238 // The original layer and the clone layer share the same texture. Therefore, only one of
239 // the layers, in this case the original layer, needs to handle the deletion. The original
240 // layer and the clone should be removed at the same time so there shouldn't be any issue
241 // with the clone layer trying to use the deleted texture.
242 mFlinger->deleteTextureAsync(mTextureName);
243 }
244 const int32_t layerId = getSequence();
245 mFlinger->mTimeStats->onDestroy(layerId);
246 mFlinger->mFrameTracer->onDestroy(layerId);
247
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000248 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700249 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700250
251 if (mDrawingState.sidebandStream != nullptr) {
252 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
253 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700254 if (mHadClonedChild) {
255 mFlinger->mNumClones--;
256 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000257 if (hasTrustedPresentationListener()) {
258 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000259 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000260 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700261}
262
Mathias Agopian13127d82013-03-05 17:47:11 -0800263// ---------------------------------------------------------------------------
264// callbacks
265// ---------------------------------------------------------------------------
266
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700267void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700268 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700269 return;
270 }
Robert Carr2e102c92018-10-23 12:11:15 -0700271
Robert Carr6a160312021-05-17 12:08:20 -0700272 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700273 if (strongRelative == nullptr) {
274 setZOrderRelativeOf(nullptr);
275 return;
276 }
277
278 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700279 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700280 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800281 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700282 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700283}
284
285void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700286 if (!mRemovedFromDrawingState) {
287 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700288 mFlinger->mScheduler->deregisterLayer(this);
289 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000290 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000291
Ady Abrahamd11bade2022-08-01 16:18:03 -0700292 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700293}
Chia-I Wu38512252017-05-17 14:36:16 -0700294
chaviw68d4dab2020-06-08 15:07:32 -0700295sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000296 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700297 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700298 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700299 }
300 return parent->getRootLayer();
301}
302
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700303void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700304 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
305 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700306 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700307
308 traverse(LayerVector::StateSet::Current, [&](Layer* layer) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700309 layer->removeFromCurrentState();
310 layer->removeRelativeZ(layersInTree);
chaviw68d4dab2020-06-08 15:07:32 -0700311 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700312}
313
chaviw61626f22018-11-15 16:26:27 -0800314void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700315 if (mRemovedFromDrawingState) {
316 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700317 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700318 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700319 }
chaviw61626f22018-11-15 16:26:27 -0800320
321 for (const auto& child : mCurrentChildren) {
322 child->addToCurrentState();
323 }
324}
325
Mathias Agopian13127d82013-03-05 17:47:11 -0800326// ---------------------------------------------------------------------------
327// set-up
328// ---------------------------------------------------------------------------
329
chaviw13fdc492017-06-27 12:40:18 -0700330bool Layer::getPremultipledAlpha() const {
331 return mPremultipliedAlpha;
332}
333
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700334sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800335 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700336 if (mGetHandleCalled) {
337 ALOGE("Get handle called twice" );
338 return nullptr;
339 }
340 mGetHandleCalled = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000341 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800342}
343
344// ---------------------------------------------------------------------------
345// h/w composer set-up
346// ---------------------------------------------------------------------------
347
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700348static Rect reduce(const Rect& win, const Region& exclude) {
349 if (CC_LIKELY(exclude.isEmpty())) {
350 return win;
351 }
352 if (exclude.isRect()) {
353 return win.reduce(exclude.getBounds());
354 }
355 return Region(win).subtract(exclude).getBounds();
356}
357
Dan Stoza80d61162017-12-20 15:57:52 -0800358static FloatRect reduce(const FloatRect& win, const Region& exclude) {
359 if (CC_LIKELY(exclude.isEmpty())) {
360 return win;
361 }
362 // Convert through Rect (by rounding) for lack of FloatRegion
363 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
364}
365
Vishnu Nair4351ad52019-02-11 14:13:02 -0800366Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800367 if (!reduceTransparentRegion) {
368 return Rect{mScreenBounds};
369 }
370
371 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800372 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800373 // Transform to screen space.
374 bounds = t.transform(bounds);
375 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700376}
377
Vishnu Nair4351ad52019-02-11 14:13:02 -0800378FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000379 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800380 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700381}
382
Vishnu Nairf0c28512019-02-08 12:40:28 -0800383FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
384 // Subtract the transparent region and snap to the bounds.
385 return reduce(mBounds, activeTransparentRegion);
386}
387
Chavi Weingarten076acac2023-01-19 17:20:43 +0000388// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000389void Layer::updateTrustedPresentationState(const DisplayDevice* display,
390 const frontend::LayerSnapshot* snapshot,
391 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000392 if (!hasTrustedPresentationListener()) {
393 return;
394 }
395 const bool lastState = mLastComputedTrustedPresentationState;
396 mLastComputedTrustedPresentationState = false;
397
398 if (!leaveState) {
399 const auto outputLayer = findOutputLayerForDisplay(display);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000400 if (outputLayer != nullptr) {
401 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
402 Region coveredRegion =
403 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
404 mLastComputedTrustedPresentationState =
405 computeTrustedPresentationState(snapshot->geomLayerBounds,
406 snapshot->sourceBounds(), coveredRegion,
407 snapshot->transformedBounds,
408 snapshot->alpha,
409 snapshot->geomLayerTransform,
410 mTrustedPresentationThresholds);
411 } else {
412 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
413 "TrustedPresentationState",
414 getDebugName());
415 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000416 }
417 }
418 const bool newState = mLastComputedTrustedPresentationState;
419 if (lastState && !newState) {
420 // We were in the trusted presentation state, but now we left it,
421 // emit the callback if needed
422 if (mLastReportedTrustedPresentationState) {
423 mLastReportedTrustedPresentationState = false;
424 mTrustedPresentationListener.invoke(false);
425 }
426 // Reset the timer
427 mEnteredTrustedPresentationStateTime = -1;
428 } else if (!lastState && newState) {
429 // We were not in the trusted presentation state, but we entered it, begin the timer
430 // and make sure this gets called at least once more!
431 mEnteredTrustedPresentationStateTime = time_in_ms;
432 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
433 }
434
435 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
436 if (!mLastReportedTrustedPresentationState && newState &&
437 (time_in_ms - mEnteredTrustedPresentationStateTime >
438 mTrustedPresentationThresholds.stabilityRequirementMs)) {
439 mLastReportedTrustedPresentationState = true;
440 mTrustedPresentationListener.invoke(true);
441 }
442}
443
444/**
445 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
446 * of how the parameters and thresholds are interpreted. The general spirit is
447 * to produce an upper bound on the amount of the buffer which was presented.
448 */
449bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
450 const Region& coveredRegion,
451 const FloatRect& screenBounds, float alpha,
452 const ui::Transform& effectiveTransform,
453 const TrustedPresentationThresholds& thresholds) {
454 if (alpha < thresholds.minAlpha) {
455 return false;
456 }
457 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
458 return false;
459 }
460 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
461 return false;
462 }
463
464 const float sx = effectiveTransform.dsdx();
465 const float sy = effectiveTransform.dsdy();
466 float fractionRendered = std::min(sx * sy, 1.0f);
467
468 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
469 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
470 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
471
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000472 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
473 // Compute the size of all the rects since they may be disconnected.
474 float coveredSize = 0;
475 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
476 float size = rect->width() * rect->height();
477 coveredSize += size;
478 }
479
480 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000481
482 if (fractionRendered < thresholds.minFractionRendered) {
483 return false;
484 }
485
486 return true;
487}
488
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700489void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
490 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800491 const State& s(getDrawingState());
492
493 // Calculate effective layer transform
494 mEffectiveTransform = parentTransform * getActiveTransform(s);
495
Garfield Tan2c1782c2022-02-16 15:25:05 -0800496 if (CC_UNLIKELY(!isTransformValid())) {
497 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
498 getDebugName());
499 return;
500 }
501
Vishnu Nair4351ad52019-02-11 14:13:02 -0800502 // Transform parent bounds to layer space
503 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
504
Vishnu Nairc652ff82019-03-15 12:48:54 -0700505 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800506 mSourceBounds = computeSourceBounds(parentBounds);
507
508 // Calculate bounds by croping diplay frame with layer crop and parent bounds
509 FloatRect bounds = mSourceBounds;
510 const Rect layerCrop = getCrop(s);
511 if (!layerCrop.isEmpty()) {
512 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
513 }
514 bounds = bounds.intersect(parentBounds);
515
516 mBounds = bounds;
517 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700518
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700519 // Use the layer's own shadow radius if set. Otherwise get the radius from
520 // parent.
521 if (s.shadowRadius > 0.f) {
522 mEffectiveShadowRadius = s.shadowRadius;
523 } else {
524 mEffectiveShadowRadius = parentShadowRadius;
525 }
526
527 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
528 // don't pass it to its children.
529 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
530
Vishnu Nair4351ad52019-02-11 14:13:02 -0800531 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700532 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800533 }
Vishnu Nairba354102022-08-01 00:14:18 +0000534
535 if (mPotentialCursor) {
536 prepareCursorCompositionState();
537 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800538}
539
Vishnu Nair60356342018-11-13 13:00:45 -0800540Rect Layer::getCroppedBufferSize(const State& s) const {
541 Rect size = getBufferSize(s);
542 Rect crop = getCrop(s);
543 if (!crop.isEmpty() && size.isValid()) {
544 size.intersect(crop, &size);
545 } else if (!crop.isEmpty()) {
546 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700547 }
Vishnu Nair60356342018-11-13 13:00:45 -0800548 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800549}
550
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700551void Layer::setupRoundedCornersCropCoordinates(Rect win,
552 const FloatRect& roundedCornersCrop) const {
553 // Translate win by the rounded corners rect coordinates, to have all values in
554 // layer coordinate space.
555 win.left -= roundedCornersCrop.left;
556 win.right -= roundedCornersCrop.left;
557 win.top -= roundedCornersCrop.top;
558 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700559}
560
Lloyd Piquede196652020-01-22 17:29:58 -0800561void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800562 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800563 const auto alpha = static_cast<float>(getAlpha());
564 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700565 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800566
567 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
568 if (!opaque || alpha != 1.0f) {
569 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
570 : Hwc2::IComposerClient::BlendMode::COVERAGE;
571 }
572
Alec Mourif4af03e2023-02-11 00:25:24 +0000573 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000574 auto* snapshot = editLayerSnapshot();
575 snapshot->outputFilter = getOutputFilter();
576 snapshot->isVisible = isVisible();
577 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
578 snapshot->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800579
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000580 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800581 contentDirty = false;
582
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000583 snapshot->geomLayerBounds = mBounds;
584 snapshot->geomLayerTransform = getTransform();
585 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
586 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000587 snapshot->localTransform = getActiveTransform(drawingState);
588 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000589 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
590 snapshot->alpha = alpha;
591 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
592 snapshot->blurRegions = drawingState.blurRegions;
593 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800594}
595
Lloyd Piquede196652020-01-22 17:29:58 -0800596void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800597 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000598 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700599
Alec Mourif4af03e2023-02-11 00:25:24 +0000600 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000601 snapshot->geomBufferSize = getBufferSize(drawingState);
602 snapshot->geomContentCrop = getBufferCrop();
603 snapshot->geomCrop = getCrop(drawingState);
604 snapshot->geomBufferTransform = getBufferTransform();
605 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
606 snapshot->geomUsesSourceCrop = usesSourceCrop();
607 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800608
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000609 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800610 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
611 for (const auto& [key, mandatory] : supportedMetadata) {
612 const auto& genericLayerMetadataCompatibilityMap =
613 mFlinger->getGenericLayerMetadataKeyMap();
614 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
615 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
616 continue;
617 }
618 const uint32_t id = compatIter->second;
619
620 auto it = drawingState.metadata.mMap.find(id);
621 if (it == std::end(drawingState.metadata.mMap)) {
622 continue;
623 }
624
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000625 snapshot->metadata.emplace(key,
626 compositionengine::GenericLayerMetadataEntry{mandatory,
627 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800628 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800629}
David Sodmanba340492018-08-05 21:51:33 -0700630
Lloyd Piquede196652020-01-22 17:29:58 -0800631void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800632 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000633 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000634 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800635
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000636 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800637
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000638 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
639 snapshot->dataspace = getDataSpace();
640 snapshot->colorTransform = getColorTransform();
641 snapshot->colorTransformIsIdentity = !hasColorTransform();
642 snapshot->surfaceDamage = surfaceDamageRegion;
643 snapshot->hasProtectedContent = isProtected();
644 snapshot->dimmingEnabled = isDimmingEnabled();
John Reck68796592023-01-25 13:47:12 -0500645 snapshot->currentSdrHdrRatio = getCurrentSdrHdrRatio();
646 snapshot->desiredSdrHdrRatio = getDesiredSdrHdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000647 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800648
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700649 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700650
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000651 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800652
653 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400654 // Rounded corners no longer force client composition, since we may use a
655 // hole punch so that the layer will appear to have rounded corners.
656 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000657 snapshot->stretchEffect.hasEffect()) {
658 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800659 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700660 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000661 snapshot->blurRegions = drawingState.blurRegions;
662 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400663
664 // Layer framerate is used in caching decisions.
665 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
666 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000667 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000668
669 if (hasBufferOrSidebandStream()) {
670 preparePerFrameBufferCompositionState();
671 } else {
672 preparePerFrameEffectsCompositionState();
673 }
674}
675
676void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000677 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000678 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000679 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000680 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
681 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000682 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
683 return;
684 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000685 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000686 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800687 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
688 snapshot->compositionType =
689 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000690 } else {
691 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000692 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
693 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000694 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
695 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
696 }
697
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000698 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000699 snapshot->acquireFence = mBufferInfo.mFence;
700 snapshot->frameNumber = mBufferInfo.mFrameNumber;
701 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000702}
703
704void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000705 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000706 auto* snapshot = editLayerSnapshot();
707 snapshot->color = getColor();
708 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000709 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800710}
711
Lloyd Piquede196652020-01-22 17:29:58 -0800712void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800713 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000714 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000715 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800716
717 // Apply the layer's transform, followed by the display's global transform
718 // Here we're guaranteed that the layer's transform preserves rects
719 Rect win = getCroppedBufferSize(drawingState);
720 // Subtract the transparent region and snap to the bounds
721 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
722 Rect frame(getTransform().transform(bounds));
723
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000724 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800725}
726
Lloyd Piquea83776c2019-01-29 18:42:32 -0800727const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700728 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800729}
730
Mathias Agopian13127d82013-03-05 17:47:11 -0800731// ---------------------------------------------------------------------------
732// drawing...
733// ---------------------------------------------------------------------------
734
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500735aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
736 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700737 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800738 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500739 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800740 }
741 if (outputLayer->getState().hwc) {
742 return (*outputLayer->getState().hwc).hwcCompositionType;
743 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500744 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800745 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800746}
747
Mathias Agopian13127d82013-03-05 17:47:11 -0800748// ----------------------------------------------------------------------------
749// local state
750// ----------------------------------------------------------------------------
751
David Sodman41fdfc92017-11-06 16:09:56 -0800752bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800753 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700754 if (s.flags & layer_state_t::eLayerSecure) {
755 return true;
756 }
757
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000758 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700759 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700760}
761
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100762void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
763 std::vector<JankData>& jankData) {
764 if (mPendingJankClassifications.empty() ||
765 !mPendingJankClassifications.front()->getJankType()) {
766 return;
767 }
768
769 bool includeJankData = false;
770 for (const auto& handle : handles) {
771 for (const auto& cb : handle->callbackIds) {
772 if (cb.includeJankData) {
773 includeJankData = true;
774 break;
775 }
776 }
777
778 if (includeJankData) {
779 jankData.reserve(mPendingJankClassifications.size());
780 break;
781 }
782 }
783
784 while (!mPendingJankClassifications.empty() &&
785 mPendingJankClassifications.front()->getJankType()) {
786 if (includeJankData) {
787 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
788 mPendingJankClassifications.front();
789 jankData.emplace_back(
790 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
791 }
792 mPendingJankClassifications.pop_front();
793 }
794}
795
Mathias Agopian13127d82013-03-05 17:47:11 -0800796// ----------------------------------------------------------------------------
797// transaction
798// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800799
Vishnu Naira156f482023-02-22 00:23:38 +0000800uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700801 ATRACE_CALL();
802
Robert Carr0758e5d2021-03-11 22:15:04 -0800803 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700804 mDrawingStateModified = mDrawingState.modified;
805 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700806
Alec Mourib416efd2018-09-06 21:01:59 +0000807 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700808
Robert Carr6a160312021-05-17 12:08:20 -0700809 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800810 // invalidate and recompute the visible regions if needed
811 flags |= Layer::eVisibleRegion;
812 }
813
Robert Carr6a160312021-05-17 12:08:20 -0700814 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800815 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000816 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800817 flags |= eVisibleRegion;
818 this->contentDirty = true;
819
820 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700821 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800822 }
823
Arthur Hung9ed43392022-05-27 06:31:57 +0000824 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
825 mFlinger->mUpdateInputInfo = true;
826 }
827
Vishnu Naira156f482023-02-22 00:23:38 +0000828 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800829
Mathias Agopian13127d82013-03-05 17:47:11 -0800830 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800831}
832
Vishnu Naira156f482023-02-22 00:23:38 +0000833void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000834 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
835 // bufferSurfaceFrameTX will be presented in latchBuffer.
836 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
837 if (surfaceFrame->getPresentState() != PresentState::Presented) {
838 // With applyPendingStates, we could end up having presented surfaceframes from previous
839 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800840 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000841 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
842 }
843 }
Robert Carr6a160312021-05-17 12:08:20 -0700844 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700845}
846
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700847uint32_t Layer::clearTransactionFlags(uint32_t mask) {
848 const auto flags = mTransactionFlags & mask;
849 mTransactionFlags &= ~mask;
850 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800851}
852
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700853void Layer::setTransactionFlags(uint32_t mask) {
854 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800855}
856
Robert Carr1f0a16a2016-10-24 16:27:39 -0700857bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
858 ssize_t idx = mCurrentChildren.indexOf(childLayer);
859 if (idx < 0) {
860 return false;
861 }
862 if (childLayer->setLayer(z)) {
863 mCurrentChildren.removeAt(idx);
864 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800865 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700866 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800867 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700868}
869
Robert Carr503c7042017-09-27 15:06:08 -0700870bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
871 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
872 ssize_t idx = mCurrentChildren.indexOf(childLayer);
873 if (idx < 0) {
874 return false;
875 }
876 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
877 mCurrentChildren.removeAt(idx);
878 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800879 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700880 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800881 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700882}
883
Robert Carrae060832016-11-28 10:51:00 -0800884bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700885 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
886 mDrawingState.sequence++;
887 mDrawingState.z = z;
888 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700889
Robert Carra70e91c2021-06-11 13:59:52 -0700890 mFlinger->mSomeChildrenChanged = true;
891
Robert Carrdb66e622017-04-10 16:55:57 -0700892 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700893 if (mDrawingState.zOrderRelativeOf != nullptr) {
894 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700895 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700896 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700897 }
chaviw606e5cf2019-03-01 10:12:10 -0800898 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700899 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800900 setTransactionFlags(eTransactionNeeded);
901 return true;
902}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700903
Robert Carrdb66e622017-04-10 16:55:57 -0700904void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700905 mDrawingState.zOrderRelatives.remove(relative);
906 mDrawingState.sequence++;
907 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700908 setTransactionFlags(eTransactionNeeded);
909}
910
911void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700912 mDrawingState.zOrderRelatives.add(relative);
913 mDrawingState.modified = true;
914 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700915 setTransactionFlags(eTransactionNeeded);
916}
917
chaviw606e5cf2019-03-01 10:12:10 -0800918void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700919 mDrawingState.zOrderRelativeOf = relativeOf;
920 mDrawingState.sequence++;
921 mDrawingState.modified = true;
922 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700923
chaviw606e5cf2019-03-01 10:12:10 -0800924 setTransactionFlags(eTransactionNeeded);
925}
926
Robert Carr503d2bd2017-12-04 15:49:47 -0800927bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000928 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700929 if (relative == nullptr) {
930 return false;
931 }
932
Robert Carr6a160312021-05-17 12:08:20 -0700933 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
934 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800935 return false;
936 }
937
Robert Carr88b85e12022-03-21 15:47:35 -0700938 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
939 (relative->mDrawingState.zOrderRelativeOf == this)) {
940 ALOGE("Detected relative layer loop between %s and %s",
941 mName.c_str(), relative->mName.c_str());
942 ALOGE("Ignoring new call to set relative layer");
943 return false;
944 }
945
Robert Carra70e91c2021-06-11 13:59:52 -0700946 mFlinger->mSomeChildrenChanged = true;
947
Robert Carr6a160312021-05-17 12:08:20 -0700948 mDrawingState.sequence++;
949 mDrawingState.modified = true;
950 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700951
Robert Carr6a160312021-05-17 12:08:20 -0700952 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700953 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700954 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700955 }
chaviw606e5cf2019-03-01 10:12:10 -0800956 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700957 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700958
959 setTransactionFlags(eTransactionNeeded);
960
961 return true;
962}
963
Winson Chunga30f7c92021-06-29 15:42:56 -0700964bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
965 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
966 mDrawingState.isTrustedOverlay = isTrustedOverlay;
967 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000968 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700969 setTransactionFlags(eTransactionNeeded);
970 return true;
971}
972
973bool Layer::isTrustedOverlay() const {
974 if (getDrawingState().isTrustedOverlay) {
975 return true;
976 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000977 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700978 return (p != nullptr) && p->isTrustedOverlay();
979}
980
Dan Stoza9e56aa02015-11-02 13:00:03 -0800981bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700982 if (mDrawingState.color.a == alpha) return false;
983 mDrawingState.sequence++;
984 mDrawingState.color.a = alpha;
985 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800986 setTransactionFlags(eTransactionNeeded);
987 return true;
988}
chaviw13fdc492017-06-27 12:40:18 -0700989
Valerie Haudd0b7572019-01-29 14:59:27 -0800990bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700991 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700992 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800993 }
Robert Carr6a160312021-05-17 12:08:20 -0700994 mDrawingState.sequence++;
995 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800996 setTransactionFlags(eTransactionNeeded);
997
Robert Carr6a160312021-05-17 12:08:20 -0700998 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -0800999 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001000 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001001 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001002 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08001003 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001004 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001005
Valerie Haudd0b7572019-01-29 14:59:27 -08001006 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001007 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001008 mFlinger->mLayersAdded = true;
1009 // set up SF to handle added color layer
1010 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -07001011 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001012 }
1013 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001014 } else if (mDrawingState.bgColorLayer && alpha == 0) {
1015 mDrawingState.bgColorLayer->reparent(nullptr);
1016 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001017 return true;
1018 }
1019
Robert Carr6a160312021-05-17 12:08:20 -07001020 mDrawingState.bgColorLayer->setColor(color);
1021 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1022 mDrawingState.bgColorLayer->setAlpha(alpha);
1023 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001024
chaviw13fdc492017-06-27 12:40:18 -07001025 return true;
1026}
1027
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001028bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001029 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001030
Robert Carr6a160312021-05-17 12:08:20 -07001031 mDrawingState.sequence++;
1032 mDrawingState.cornerRadius = cornerRadius;
1033 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001034 setTransactionFlags(eTransactionNeeded);
1035 return true;
1036}
1037
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001038bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001039 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001040 // If we start or stop drawing blur then the layer's visibility state may change so increment
1041 // the magic sequence number.
1042 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1043 mDrawingState.sequence++;
1044 }
Robert Carr6a160312021-05-17 12:08:20 -07001045 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1046 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001047 setTransactionFlags(eTransactionNeeded);
1048 return true;
1049}
Marissa Wall61c58622018-07-18 10:12:20 -07001050
Mathias Agopian13127d82013-03-05 17:47:11 -08001051bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001052 mDrawingState.sequence++;
1053 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001054 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001055 setTransactionFlags(eTransactionNeeded);
1056 return true;
1057}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001058
Lucas Dupinc3800b82020-10-02 16:24:48 -07001059bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001060 // If we start or stop drawing blur then the layer's visibility state may change so increment
1061 // the magic sequence number.
1062 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1063 mDrawingState.sequence++;
1064 }
Robert Carr6a160312021-05-17 12:08:20 -07001065 mDrawingState.blurRegions = blurRegions;
1066 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001067 setTransactionFlags(eTransactionNeeded);
1068 return true;
1069}
1070
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001071bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001072 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1073 if (mDrawingState.flags == newFlags) return false;
1074 mDrawingState.sequence++;
1075 mDrawingState.flags = newFlags;
1076 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001077 setTransactionFlags(eTransactionNeeded);
1078 return true;
1079}
Robert Carr99e27f02016-06-16 15:18:02 -07001080
chaviw25714502021-02-11 10:01:08 -08001081bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001082 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001083 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001084 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001085
Robert Carr6a160312021-05-17 12:08:20 -07001086 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001087 setTransactionFlags(eTransactionNeeded);
1088 return true;
1089}
Robert Carr8d5227b2017-03-16 15:41:03 -07001090
Evan Roskyef876c92019-01-25 17:46:06 -08001091bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001092 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1093 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001094 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001095 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001096}
1097
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001098bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001099 if (mDrawingState.layerStack == layerStack) return false;
1100 mDrawingState.sequence++;
1101 mDrawingState.layerStack = layerStack;
1102 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001103 setTransactionFlags(eTransactionNeeded);
1104 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001105}
1106
Peiyong Linc502cb72019-03-01 15:00:23 -08001107bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001108 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001109 return false;
1110 }
Robert Carr6a160312021-05-17 12:08:20 -07001111 mDrawingState.sequence++;
1112 mDrawingState.colorSpaceAgnostic = agnostic;
1113 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001114 setTransactionFlags(eTransactionNeeded);
1115 return true;
1116}
1117
Sally Qi81d95e62022-03-21 19:41:33 -07001118bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1119 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1120
1121 mDrawingState.sequence++;
1122 mDrawingState.dimmingEnabled = dimmingEnabled;
1123 mDrawingState.modified = true;
1124 setTransactionFlags(eTransactionNeeded);
1125 return true;
1126}
1127
Ana Krulecc84d09b2019-11-02 23:10:29 +01001128bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001129 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1130 mDrawingState.frameRateSelectionPriority = priority;
1131 mDrawingState.sequence++;
1132 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001133 setTransactionFlags(eTransactionNeeded);
1134 return true;
1135}
1136
1137int32_t Layer::getFrameRateSelectionPriority() const {
1138 // Check if layer has priority set.
1139 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1140 return mDrawingState.frameRateSelectionPriority;
1141 }
1142 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001143 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001144 if (parent != nullptr) {
1145 return parent->getFrameRateSelectionPriority();
1146 }
1147
1148 return Layer::PRIORITY_UNSET;
1149}
1150
Andy Labrada096227e2022-06-15 16:58:11 +00001151bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1152 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1153 mDrawingState.defaultFrameRateCompatibility = compatibility;
1154 mDrawingState.modified = true;
1155 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1156 setTransactionFlags(eTransactionNeeded);
1157 return true;
1158}
1159
1160scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1161 return mDrawingState.defaultFrameRateCompatibility;
1162}
1163
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001164bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1165 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1166};
1167
Vishnu Nair73908d12022-10-24 21:46:42 -07001168ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1169 bool useDrawing = state == LayerVector::StateSet::Drawing;
1170 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1171 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001172 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001173 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001174 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001175}
1176
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001177bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001178 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001179 return false;
1180 }
1181
Robert Carr6a160312021-05-17 12:08:20 -07001182 mDrawingState.sequence++;
1183 mDrawingState.shadowRadius = shadowRadius;
1184 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001185 setTransactionFlags(eTransactionNeeded);
1186 return true;
1187}
1188
Vishnu Nair6213bd92020-05-08 17:42:25 -07001189bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001190 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001191 return false;
1192 }
1193
Robert Carr6a160312021-05-17 12:08:20 -07001194 mDrawingState.sequence++;
1195 mDrawingState.fixedTransformHint = fixedTransformHint;
1196 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001197 setTransactionFlags(eTransactionNeeded);
1198 return true;
1199}
1200
John Reckcdb4ed72021-02-04 13:39:33 -05001201bool Layer::setStretchEffect(const StretchEffect& effect) {
1202 StretchEffect temp = effect;
1203 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001204 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001205 return false;
1206 }
Robert Carr6a160312021-05-17 12:08:20 -07001207 mDrawingState.sequence++;
1208 mDrawingState.stretchEffect = temp;
1209 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001210 setTransactionFlags(eTransactionNeeded);
1211 return true;
1212}
1213
John Reckc00c6692021-02-16 11:37:33 -05001214StretchEffect Layer::getStretchEffect() const {
1215 if (mDrawingState.stretchEffect.hasEffect()) {
1216 return mDrawingState.stretchEffect;
1217 }
1218
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001219 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001220 if (parent != nullptr) {
1221 auto effect = parent->getStretchEffect();
1222 if (effect.hasEffect()) {
1223 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1224 return effect;
1225 }
1226 }
1227 return StretchEffect{};
1228}
1229
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001230bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1231 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001232 return false;
1233 }
1234 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001235 mBorderWidth = width;
1236 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001237 return true;
1238}
1239
1240bool Layer::isBorderEnabled() {
1241 return mBorderEnabled;
1242}
1243
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001244float Layer::getBorderWidth() {
1245 return mBorderWidth;
1246}
1247
1248const half4& Layer::getBorderColor() {
1249 return mBorderColor;
1250}
1251
Ady Abrahama850c182021-08-04 13:04:37 -07001252bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1253 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1254 const auto frameRate = [&] {
1255 if (mDrawingState.frameRate.rate.isValid() ||
1256 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1257 return mDrawingState.frameRate;
1258 }
1259
1260 return parentFrameRate;
1261 }();
1262
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001263 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001264
1265 // The frame rate is propagated to the children
1266 bool childrenHaveFrameRate = false;
1267 for (const sp<Layer>& child : mCurrentChildren) {
1268 childrenHaveFrameRate |=
1269 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1270 }
1271
1272 // If we don't have a valid frame rate, but the children do, we set this
1273 // layer as NoVote to allow the children to control the refresh rate
1274 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1275 childrenHaveFrameRate) {
1276 *transactionNeeded |=
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001277 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001278 }
1279
1280 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1281 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001282 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001283 const auto layerVotedWithDefaultCompatibility =
1284 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1285 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1286 const auto layerVotedWithExactCompatibility =
1287 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1288 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1289 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1290}
1291
Ady Abraham60e42ea2020-03-09 19:17:31 -07001292void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001293 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001294 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001295 while (auto parent = layer->getParent()) {
1296 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001297 }
Ady Abrahama850c182021-08-04 13:04:37 -07001298 return layer;
1299 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001300
Ady Abraham60e42ea2020-03-09 19:17:31 -07001301 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001302 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001303
Ady Abrahama850c182021-08-04 13:04:37 -07001304 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001305 if (transactionNeeded) {
1306 mFlinger->setTransactionFlags(eTraversalNeeded);
1307 }
1308}
1309
Ady Abraham71c437d2020-01-31 15:56:57 -08001310bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001311 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001312 return false;
1313 }
1314
Robert Carr6a160312021-05-17 12:08:20 -07001315 mDrawingState.sequence++;
1316 mDrawingState.frameRate = frameRate;
1317 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001318
1319 updateTreeHasFrameRateVote();
1320
Steven Thomas3172e202020-01-06 19:25:30 -08001321 setTransactionFlags(eTransactionNeeded);
1322 return true;
1323}
1324
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001325void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1326 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001327 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001328
1329 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1330 // there are two transactions with the same token, the first one without a buffer and the
1331 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1332 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001333 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1334 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001335 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001336 mDrawingState.bufferSurfaceFrameTX = it->second;
1337 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1338 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1339 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001340 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001341 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001342 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1343 }
1344}
1345
1346void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1347 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001348 mDrawingState.frameTimelineInfo = info;
1349 mDrawingState.postTime = postTime;
1350 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001351 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001352
Robert Carr6a160312021-05-17 12:08:20 -07001353 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001354 bufferSurfaceFrameTX != nullptr) {
1355 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1356 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1357 // being used for BufferSurfaceFrame, don't create a new one.
1358 return;
1359 }
1360 }
1361 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1362 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1363 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001364 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1365 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001366 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001367 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001368 } else {
1369 if (it->second->getPresentState() == PresentState::Presented) {
1370 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1371 // have been from previous vsync.
1372 it->second = createSurfaceFrameForTransaction(info, postTime);
1373 }
1374 }
1375}
1376
1377void Layer::addSurfaceFrameDroppedForBuffer(
1378 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001379 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001380 surfaceFrame->setPresentState(PresentState::Dropped);
1381 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1382}
1383
1384void Layer::addSurfaceFramePresentedForBuffer(
1385 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1386 nsecs_t currentLatchTime) {
1387 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1388 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1389 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001390 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001391}
1392
1393std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1394 const FrameTimelineInfo& info, nsecs_t postTime) {
1395 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001396 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1397 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001398 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001399 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001400 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001401 // For Transactions, the post time is considered to be both queue and acquire fence time.
1402 surfaceFrame->setActualQueueTime(postTime);
1403 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001404 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1405 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001406 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001407 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001408 onSurfaceFrameCreated(surfaceFrame);
1409 return surfaceFrame;
1410}
1411
1412std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1413 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1414 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001415 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001416 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001417 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001418 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001419 // For buffers, acquire fence time will set during latch.
1420 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001421 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1422 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001423 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001424 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001425 onSurfaceFrameCreated(surfaceFrame);
1426 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001427}
1428
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001429bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001430 if (mDrawingState.frameRateForLayerTree == frameRate) {
1431 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001432 }
1433
Ady Abrahama850c182021-08-04 13:04:37 -07001434 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001435
Ady Abrahama850c182021-08-04 13:04:37 -07001436 // TODO(b/195668952): we probably don't need to dirty visible regions here
1437 // or even store frameRateForLayerTree in mDrawingState
1438 mDrawingState.sequence++;
1439 mDrawingState.modified = true;
1440 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001441
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001442 mFlinger->mScheduler
1443 ->recordLayerHistory(sequence, getLayerProps(), systemTime(),
1444 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1445 return true;
1446}
Ady Abrahama850c182021-08-04 13:04:37 -07001447
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001448bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps) {
1449 if (mDrawingState.frameRateForLayerTree == frameRate) {
1450 return false;
1451 }
1452
1453 mDrawingState.frameRateForLayerTree = frameRate;
1454 mFlinger->mScheduler
1455 ->recordLayerHistory(sequence, layerProps, systemTime(),
1456 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001457 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001458}
1459
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001460Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1461 return getDrawingState().frameRateForLayerTree;
1462}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001463
Robert Carr1f0a16a2016-10-24 16:27:39 -07001464bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001465 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001466 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001467 if (parent != nullptr && parent->isHiddenByPolicy()) {
1468 return true;
1469 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001470 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1471 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1472 if (zOrderRelativeOf != nullptr) {
1473 if (zOrderRelativeOf->isHiddenByPolicy()) {
1474 return true;
1475 }
1476 }
1477 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001478 if (CC_UNLIKELY(!isTransformValid())) {
1479 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1480 return true;
1481 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001482 return s.flags & layer_state_t::eLayerHidden;
1483}
1484
David Sodman41fdfc92017-11-06 16:09:56 -08001485uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001486 // TODO: should we do something special if mSecure is set?
1487 if (mProtectedByApp) {
1488 // need a hardware-protected path to external video sink
1489 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001490 }
Riley Andrews03414a12014-07-01 14:22:59 -07001491 if (mPotentialCursor) {
1492 usage |= GraphicBuffer::USAGE_CURSOR;
1493 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001494 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001495 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001496}
1497
Vishnu Nair71fcf912022-10-18 09:14:20 -07001498void Layer::skipReportingTransformHint() {
1499 mSkipReportingTransformHint = true;
1500}
1501
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001502void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1503 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1504 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001505 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001506
Vishnu Nair6213bd92020-05-08 17:42:25 -07001507 setTransformHint(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001508}
1509
Mathias Agopian13127d82013-03-05 17:47:11 -08001510// ----------------------------------------------------------------------------
1511// debugging
1512// ----------------------------------------------------------------------------
1513
Marissa Wall61c58622018-07-18 10:12:20 -07001514// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001515gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001516 using namespace std::string_literals;
1517
Huihong Luo05539a12022-02-23 10:29:40 -08001518 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001519 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001520 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001521 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001522 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001523 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001524
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001525 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001526 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001527 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001528 info.mX = ds.transform.tx();
1529 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001530 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001531 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001532 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001533 info.mFlags = ds.flags;
1534 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001535 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001536 info.mMatrix[0][0] = ds.transform[0][0];
1537 info.mMatrix[0][1] = ds.transform[0][1];
1538 info.mMatrix[1][0] = ds.transform[1][0];
1539 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001540 {
chaviwd62d3062019-09-04 14:48:02 -07001541 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001542 if (buffer != 0) {
1543 info.mActiveBufferWidth = buffer->getWidth();
1544 info.mActiveBufferHeight = buffer->getHeight();
1545 info.mActiveBufferStride = buffer->getStride();
1546 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001547 } else {
1548 info.mActiveBufferWidth = 0;
1549 info.mActiveBufferHeight = 0;
1550 info.mActiveBufferStride = 0;
1551 info.mActiveBufferFormat = 0;
1552 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001553 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001554 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001555 info.mIsOpaque = isOpaque(ds);
1556 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001557 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001558 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001559}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001560
Yiwei Zhang5434a782018-12-05 18:06:32 -08001561void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001562 result.append(kDumpTableRowLength, '-');
1563 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001564 result.append(" Layer name\n");
1565 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001566 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001567 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001568 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001569 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001570 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001571 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1572 result.append(kDumpTableRowLength, '-');
1573 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001574}
1575
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001576void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1577 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001578 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001579 return;
1580 }
1581
Yiwei Zhang5434a782018-12-05 18:06:32 -08001582 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001583 if (mName.length() > 77) {
1584 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001585 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001586 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001587 shortened.append(mName, mName.length() - 36);
1588 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001589 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001590 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001591 }
1592
Yiwei Zhang5434a782018-12-05 18:06:32 -08001593 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001594
Alec Mourib416efd2018-09-06 21:01:59 +00001595 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001596 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001597
Chia-I Wu1e043612018-03-01 09:45:09 -08001598 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001599 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001600 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001601 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001602 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001603 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001604 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001605 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1606 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001607 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001608 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001609 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001610 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001611 const auto frameRate = getFrameRateForLayerTree();
1612 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1613 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001614 ftl::enum_string(frameRate.type).c_str(),
1615 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001616 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001617 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001618 }
Dan Stozae22aec72016-08-01 13:20:59 -07001619
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001620 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1621 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1622
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001623 result.append(kDumpTableRowLength, '-');
1624 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001625}
Dan Stozae22aec72016-08-01 13:20:59 -07001626
Yiwei Zhang5434a782018-12-05 18:06:32 -08001627void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001628 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001629}
1630
Svetoslavd85084b2014-03-20 10:28:31 -07001631void Layer::clearFrameStats() {
1632 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001633}
1634
Jamie Gennis6547ff42013-07-16 20:12:42 -07001635void Layer::logFrameStats() {
1636 mFrameTracker.logAndResetStats(mName);
1637}
1638
Svetoslavd85084b2014-03-20 10:28:31 -07001639void Layer::getFrameStats(FrameStats* outStats) const {
1640 mFrameTracker.getStats(outStats);
1641}
1642
Vishnu Nair76554eb2022-12-09 03:38:36 +00001643void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1644 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
1645 StringAppendF(&result, "Layer %s%s pid:%d uid:%d\n", getName().c_str(), hasBuffer.c_str(),
Vishnu Naircb8be502022-10-12 19:03:23 +00001646 mOwnerPid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001647}
1648
Brian Anderson5ea5e592016-12-01 16:54:33 -08001649void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001650 const int32_t layerId = getSequence();
1651 mFlinger->mTimeStats->onDestroy(layerId);
1652 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001653}
1654
Chia-I Wu98f1c102017-05-30 14:54:08 -07001655size_t Layer::getChildrenCount() const {
1656 size_t count = 0;
1657 for (const sp<Layer>& child : mCurrentChildren) {
1658 count += 1 + child->getChildrenCount();
1659 }
1660 return count;
1661}
1662
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001663void Layer::setGameModeForTree(GameMode gameMode) {
1664 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001665 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1666 gameMode =
1667 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001668 }
1669 setGameMode(gameMode);
1670 for (const sp<Layer>& child : mCurrentChildren) {
1671 child->setGameModeForTree(gameMode);
1672 }
1673}
1674
Robert Carr1f0a16a2016-10-24 16:27:39 -07001675void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001676 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001677 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001678
Robert Carr1f0a16a2016-10-24 16:27:39 -07001679 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001680 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001681 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001682 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001683}
1684
1685ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001686 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001687 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001688
Robert Carr1323c952019-01-28 18:13:27 -08001689 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001690 const auto removeResult = mCurrentChildren.remove(layer);
1691
1692 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001693 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001694 layer->updateTreeHasFrameRateVote();
1695
1696 return removeResult;
1697}
1698
Robert Carr15eae092018-03-23 13:43:53 -07001699void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001700 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001701 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001702 const float parentShadowRadius =
1703 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001704 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001705 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001706 }
1707}
1708
chaviwf1961f72017-09-18 16:41:07 -07001709bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001710 sp<Layer> newParent;
1711 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001712 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001713 if (newParent == nullptr) {
1714 ALOGE("Unable to promote Layer handle");
1715 return false;
1716 }
1717 if (newParent == this) {
1718 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1719 return false;
1720 }
1721 }
1722
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001723 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001724 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001725 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001726 }
1727
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001728 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001729 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001730 if (!newParent->isRemovedFromCurrentState()) {
1731 addToCurrentState();
1732 } else {
1733 onRemovedFromCurrentState();
1734 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001735 } else {
1736 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001737 }
1738
chaviw06178942017-07-27 10:25:59 -07001739 return true;
1740}
1741
Peiyong Lind3788632018-09-18 16:01:31 -07001742bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001743 static const mat4 identityMatrix = mat4();
1744
Robert Carr6a160312021-05-17 12:08:20 -07001745 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001746 return false;
1747 }
Robert Carr6a160312021-05-17 12:08:20 -07001748 ++mDrawingState.sequence;
1749 mDrawingState.colorTransform = matrix;
1750 mDrawingState.hasColorTransform = matrix != identityMatrix;
1751 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001752 setTransactionFlags(eTransactionNeeded);
1753 return true;
1754}
1755
chaviwf66724d2018-11-28 16:35:21 -08001756mat4 Layer::getColorTransform() const {
1757 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001758 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001759 colorTransform = parent->getColorTransform() * colorTransform;
1760 }
1761 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001762}
1763
1764bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001765 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001766 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001767 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1768 }
1769 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001770}
1771
Chia-I Wu11481472018-05-04 10:43:19 -07001772bool Layer::isLegacyDataSpace() const {
1773 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001774 return !(getDataSpace() &
1775 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1776 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001777}
1778
Robert Carr1f0a16a2016-10-24 16:27:39 -07001779void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001780 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001781}
1782
Robert Carr6a160312021-05-17 12:08:20 -07001783int32_t Layer::getZ(LayerVector::StateSet) const {
1784 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001785}
1786
Robert Carr1c5481e2019-07-01 14:42:27 -07001787bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001788 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001789 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001790 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001791}
1792
David Sodman41fdfc92017-11-06 16:09:56 -08001793__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001794 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001795 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1796 "makeTraversalList received invalid stateSet");
1797 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1798 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001799 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001800
Robert Carr29abff82017-12-04 13:51:20 -08001801 if (state.zOrderRelatives.size() == 0) {
1802 *outSkipRelativeZUsers = true;
1803 return children;
1804 }
1805
chaviwfd462612018-05-31 16:11:27 -07001806 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001807 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001808 sp<Layer> strongRelative = weakRelative.promote();
1809 if (strongRelative != nullptr) {
1810 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001811 }
1812 }
1813
Dan Stoza412903f2017-04-27 13:42:17 -07001814 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001815 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001816 continue;
1817 }
Robert Carrdb66e622017-04-10 16:55:57 -07001818 traverse.add(child);
1819 }
1820
1821 return traverse;
1822}
1823
Robert Carr1f0a16a2016-10-24 16:27:39 -07001824/**
Robert Carrdb66e622017-04-10 16:55:57 -07001825 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001826 */
Dan Stoza412903f2017-04-27 13:42:17 -07001827void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001828 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1829 // produce a new list for traversing, including our relatives, and not including our children
1830 // who are relatives of another surface. In the case that there are no relative Z,
1831 // makeTraversalList returns our children directly to avoid significant overhead.
1832 // However in this case we need to take the responsibility for filtering children which
1833 // are relatives of another surface here.
1834 bool skipRelativeZUsers = false;
1835 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001836
Robert Carr1f0a16a2016-10-24 16:27:39 -07001837 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001838 for (; i < list.size(); i++) {
1839 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001840 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1841 continue;
1842 }
1843
chaviw301b1d82019-11-06 13:15:09 -08001844 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001845 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001846 }
Dan Stoza412903f2017-04-27 13:42:17 -07001847 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001848 }
Robert Carr29abff82017-12-04 13:51:20 -08001849
Dan Stoza412903f2017-04-27 13:42:17 -07001850 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001851 for (; i < list.size(); i++) {
1852 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001853
Robert Carr29abff82017-12-04 13:51:20 -08001854 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1855 continue;
1856 }
Dan Stoza412903f2017-04-27 13:42:17 -07001857 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001858 }
1859}
1860
1861/**
Robert Carrdb66e622017-04-10 16:55:57 -07001862 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001863 */
Dan Stoza412903f2017-04-27 13:42:17 -07001864void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1865 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001866 // See traverseInZOrder for documentation.
1867 bool skipRelativeZUsers = false;
1868 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001869
Robert Carr1f0a16a2016-10-24 16:27:39 -07001870 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001871 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001872 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001873
1874 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1875 continue;
1876 }
1877
chaviw301b1d82019-11-06 13:15:09 -08001878 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001879 break;
1880 }
Dan Stoza412903f2017-04-27 13:42:17 -07001881 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001882 }
Dan Stoza412903f2017-04-27 13:42:17 -07001883 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001884 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001885 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001886
1887 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1888 continue;
1889 }
1890
Dan Stoza412903f2017-04-27 13:42:17 -07001891 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001892 }
1893}
1894
Edgar Arriaga844fa672020-01-16 14:21:42 -08001895void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1896 visitor(this);
1897 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001898 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001899 for (const sp<Layer>& child : children) {
1900 child->traverse(state, visitor);
1901 }
1902}
1903
chaviw4b129c22018-04-09 16:19:43 -07001904LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1905 const std::vector<Layer*>& layersInTree) {
1906 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1907 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001908 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1909 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001910 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001911
chaviwfd462612018-05-31 16:11:27 -07001912 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001913 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1914 sp<Layer> strongRelative = weakRelative.promote();
1915 // Only add relative layers that are also descendents of the top most parent of the tree.
1916 // If a relative layer is not a descendent, then it should be ignored.
1917 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1918 traverse.add(strongRelative);
1919 }
1920 }
1921
1922 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001923 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001924 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1925 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1926 // the child here since it won't be added later as a relative.
1927 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1928 childState.zOrderRelativeOf.promote().get())) {
1929 continue;
1930 }
1931 traverse.add(child);
1932 }
1933
1934 return traverse;
1935}
1936
1937void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1938 LayerVector::StateSet stateSet,
1939 const LayerVector::Visitor& visitor) {
1940 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001941
1942 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001943 for (; i < list.size(); i++) {
1944 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001945 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001946 break;
1947 }
chaviw4b129c22018-04-09 16:19:43 -07001948 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001949 }
chaviw4b129c22018-04-09 16:19:43 -07001950
chaviwa76b2712017-09-20 12:02:26 -07001951 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001952 for (; i < list.size(); i++) {
1953 const auto& relative = list[i];
1954 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001955 }
1956}
1957
chaviw4b129c22018-04-09 16:19:43 -07001958std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1959 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1960 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1961
1962 std::vector<Layer*> layersInTree = {this};
1963 for (size_t i = 0; i < children.size(); i++) {
1964 const auto& child = children[i];
1965 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1966 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1967 }
1968
1969 return layersInTree;
1970}
1971
1972void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1973 const LayerVector::Visitor& visitor) {
1974 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1975 std::sort(layersInTree.begin(), layersInTree.end());
1976 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1977}
1978
Peiyong Linefefaac2018-08-17 12:27:51 -07001979ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001980 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001981}
1982
Garfield Tan2c1782c2022-02-16 15:25:05 -08001983bool Layer::isTransformValid() const {
1984 float transformDet = getTransform().det();
1985 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1986}
1987
chaviw13fdc492017-06-27 12:40:18 -07001988half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001989 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001990
chaviw13fdc492017-06-27 12:40:18 -07001991 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1992 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07001993}
Robert Carr6452f122017-03-21 10:41:29 -07001994
Vishnu Nair6213bd92020-05-08 17:42:25 -07001995ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07001996 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001997 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
1998 return fixedTransformHint;
1999 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002000 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002001 if (!p) return fixedTransformHint;
2002 return p->getFixedTransformHint();
2003}
2004
chaviw13fdc492017-06-27 12:40:18 -07002005half4 Layer::getColor() const {
2006 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002007 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002008}
Robert Carr6452f122017-03-21 10:41:29 -07002009
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002010int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002011 if (getDrawingState().backgroundBlurRadius == 0) {
2012 return 0;
2013 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002014
Vishnu Nair29810f72022-07-01 16:38:41 +00002015 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002016 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2017 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002018}
2019
Galia Peychevae0acf382021-04-12 21:22:34 +02002020const std::vector<BlurRegion> Layer::getBlurRegions() const {
2021 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002022 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002023 for (auto& region : regionsCopy) {
2024 region.alpha = region.alpha * layerAlpha;
2025 }
2026 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002027}
2028
Vishnu Naire14c6b32022-08-06 04:20:15 +00002029RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002030 // Get parent settings
2031 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002032 const auto& parent = mDrawingParent.promote();
2033 if (parent != nullptr) {
2034 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002035 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002036 ui::Transform t = getActiveTransform(getDrawingState());
2037 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002038 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002039 parentSettings.radius.x *= t.getScaleX();
2040 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002041 }
2042 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002043
2044 // Get layer settings
2045 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002046 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002047 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002048 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002049
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002050 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002051 // If the parent and the layer have rounded corner settings, use the parent settings if the
2052 // parent crop is entirely inside the layer crop.
2053 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2054 if (parentSettings.cropRect.left > layerCropRect.left &&
2055 parentSettings.cropRect.top > layerCropRect.top &&
2056 parentSettings.cropRect.right < layerCropRect.right &&
2057 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2058 return parentSettings;
2059 } else {
2060 return layerSettings;
2061 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002062 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002063 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002064 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002065 return parentSettings;
2066 }
2067 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002068}
2069
Robert Carr88b85e12022-03-21 15:47:35 -07002070bool Layer::findInHierarchy(const sp<Layer>& l) {
2071 if (l == this) {
2072 return true;
2073 }
2074 for (auto& child : mDrawingChildren) {
2075 if (child->findInHierarchy(l)) {
2076 return true;
2077 }
2078 }
2079 return false;
2080}
2081
Robert Carr1f0a16a2016-10-24 16:27:39 -07002082void Layer::commitChildList() {
2083 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2084 const auto& child = mCurrentChildren[i];
2085 child->commitChildList();
2086 }
2087 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002088 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002089 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2090 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2091 if (zOrderRelativeOf == nullptr) return;
2092 if (findInHierarchy(zOrderRelativeOf)) {
2093 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2094 zOrderRelativeOf->mName.c_str());
2095 ALOGE("Severing rel Z loop, potentially dangerous");
2096 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002097 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002098 }
2099 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002100}
2101
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002102
chaviw3277faf2021-05-19 16:45:23 -05002103void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002104 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002105 mDrawingState.touchableRegionCrop =
2106 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002107 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002108 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002109 setTransactionFlags(eTransactionNeeded);
2110}
2111
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002112LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002113 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002114 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002115 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2116
Vishnu Nair00b90132021-11-05 14:03:40 -07002117 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002118 writeCompositionStateToProto(layerProto);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002119 }
2120
chaviw08f3cb22020-01-13 13:17:21 -08002121 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002122 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002123 }
chaviw6d89e2d2020-01-14 14:42:01 -08002124
2125 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002126}
2127
Vishnu Nairea6ff812023-02-27 17:41:39 +00002128void Layer::writeCompositionStateToProto(LayerProto* layerProto) {
2129 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2130
2131 // Only populate for the primary display.
2132 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
2133 const auto compositionType = getCompositionType(*display);
2134 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
2135 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2136 [&]() { return layerProto->mutable_visible_region(); });
2137 }
2138}
2139
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002140void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002141 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002142 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002143 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002144 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002145 [&]() { return layerInfo->mutable_active_buffer(); });
2146 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2147 layerInfo->mutable_buffer_transform());
2148 }
2149 layerInfo->set_invalidate(contentDirty);
2150 layerInfo->set_is_protected(isProtected());
2151 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2152 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002153 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002154 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002155 layerInfo->set_corner_radius(
2156 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002157 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2158 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2159 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2160 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2161 [&]() { return layerInfo->mutable_position(); });
2162 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002163 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2164 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002165
Vishnu Nair00b90132021-11-05 14:03:40 -07002166 if (hasColorTransform()) {
2167 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002168 }
2169
Vishnu Nair60db8c02020-04-02 11:55:16 -07002170 LayerProtoHelper::writeToProto(mSourceBounds,
2171 [&]() { return layerInfo->mutable_source_bounds(); });
2172 LayerProtoHelper::writeToProto(mScreenBounds,
2173 [&]() { return layerInfo->mutable_screen_bounds(); });
2174 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2175 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2176 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002177}
2178
2179void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002180 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002181 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2182 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002183 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002184
chaviw766c9c52021-02-10 17:36:47 -08002185 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002186
Vishnu Nair00b90132021-11-05 14:03:40 -07002187 layerInfo->set_id(sequence);
2188 layerInfo->set_name(getName().c_str());
2189 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002190
Vishnu Nair00b90132021-11-05 14:03:40 -07002191 for (const auto& child : children) {
2192 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002193 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002194
Vishnu Nair00b90132021-11-05 14:03:40 -07002195 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2196 sp<Layer> strongRelative = weakRelative.promote();
2197 if (strongRelative != nullptr) {
2198 layerInfo->add_relatives(strongRelative->sequence);
2199 }
2200 }
2201
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002202 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002203 [&]() { return layerInfo->mutable_transparent_region(); });
2204
2205 layerInfo->set_layer_stack(getLayerStack().id);
2206 layerInfo->set_z(state.z);
2207
2208 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2209 return layerInfo->mutable_requested_position();
2210 });
2211
Vishnu Nair00b90132021-11-05 14:03:40 -07002212 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2213
2214 layerInfo->set_is_opaque(isOpaque(state));
2215
2216 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2217 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2218 LayerProtoHelper::writeToProto(state.color,
2219 [&]() { return layerInfo->mutable_requested_color(); });
2220 layerInfo->set_flags(state.flags);
2221
2222 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2223 layerInfo->mutable_requested_transform());
2224
2225 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2226 if (parent != nullptr) {
2227 layerInfo->set_parent(parent->sequence);
2228 } else {
2229 layerInfo->set_parent(-1);
2230 }
2231
2232 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2233 if (zOrderRelativeOf != nullptr) {
2234 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2235 } else {
2236 layerInfo->set_z_order_relative_of(-1);
2237 }
2238
2239 layerInfo->set_is_relative_of(state.isRelativeOf);
2240
2241 layerInfo->set_owner_uid(mOwnerUid);
2242
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002243 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002244 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002245 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002246 info = fillInputInfo(
2247 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002248 } else {
2249 info = state.inputInfo;
2250 }
2251
2252 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002253 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002254 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002255
Vishnu Nair00b90132021-11-05 14:03:40 -07002256 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002257 auto protoMap = layerInfo->mutable_metadata();
2258 for (const auto& entry : state.metadata.mMap) {
2259 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2260 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002261 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002262
2263 LayerProtoHelper::writeToProto(state.destinationFrame,
2264 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002265}
2266
Robert Carr2e102c92018-10-23 12:11:15 -07002267bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002268 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002269}
2270
Prabir Pradhan33da9462022-06-14 14:55:57 +00002271// Applies the given transform to the region, while protecting against overflows caused by any
2272// offsets. If applying the offset in the transform to any of the Rects in the region would result
2273// in an overflow, they are not added to the output Region.
2274static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2275 const std::string& debugWindowName) {
2276 // Round the translation using the same rounding strategy used by ui::Transform.
2277 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2278 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2279
2280 ui::Transform transformWithoutOffset = t;
2281 transformWithoutOffset.set(0.f, 0.f);
2282
2283 const Region transformed = transformWithoutOffset.transform(r);
2284
2285 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2286 Region ret;
2287 for (const auto& rect : transformed) {
2288 Rect newRect;
2289 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2290 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2291 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2292 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2293 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2294 debugWindowName.c_str());
2295 continue;
2296 }
2297 ret.orSelf(newRect);
2298 }
2299 return ret;
2300}
2301
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002302void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002303 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2304 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002305 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002306 }
2307
Vishnu Nairfed7c122023-03-18 01:54:43 +00002308 const Rect roundedFrameInDisplay = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002309 info.frameLeft = roundedFrameInDisplay.left;
2310 info.frameTop = roundedFrameInDisplay.top;
2311 info.frameRight = roundedFrameInDisplay.right;
2312 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002313
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002314 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002315 inputToLayer.set(inputBounds.left, inputBounds.top);
2316 const ui::Transform layerToScreen = getInputTransform();
2317 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002318
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002319 // InputDispatcher expects a display-to-input transform.
2320 info.transform = inputToDisplay.inverse();
2321
2322 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002323 info.touchableRegion =
2324 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002325}
2326
chaviw3277faf2021-05-19 16:45:23 -05002327void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002328 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002329 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002330 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002331 }
2332 if (p != nullptr) {
2333 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2334 }
2335}
2336
Vishnu Naira066d902021-09-13 18:40:17 -07002337gui::DropInputMode Layer::getDropInputMode() const {
2338 gui::DropInputMode mode = mDrawingState.dropInputMode;
2339 if (mode == gui::DropInputMode::ALL) {
2340 return mode;
2341 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002342 sp<Layer> parent = mDrawingParent.promote();
2343 if (parent) {
2344 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002345 if (parentMode != gui::DropInputMode::NONE) {
2346 return parentMode;
2347 }
2348 }
2349 return mode;
2350}
2351
2352void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002353 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002354 return;
2355 }
2356
2357 // Check if we need to drop input unconditionally
2358 gui::DropInputMode dropInputMode = getDropInputMode();
2359 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002360 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002361 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2362 return;
2363 }
2364
2365 // Check if we need to check if the window is obscured by parent
2366 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2367 return;
2368 }
2369
2370 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002371 sp<Layer> parent = mDrawingParent.promote();
2372 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002373 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002374 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2375 static_cast<float>(getAlpha()));
2376 }
2377
2378 // Check if the parent has cropped the buffer
2379 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2380 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002381 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002382 return;
2383 }
2384
2385 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2386 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2387 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2388 // match then the layer has not been cropped by its parents.
2389 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2390 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2391
2392 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002393 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002394 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2395 getDebugName());
2396 } else {
2397 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2398 // input if the window is obscured. This check should be done in surfaceflinger but the
2399 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2400 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002401 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002402 }
2403}
2404
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002405WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002406 if (!hasInputInfo()) {
2407 mDrawingState.inputInfo.name = getName();
2408 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2409 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002410 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002411 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002412 }
2413
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002414 const ui::Transform& displayTransform =
2415 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2416
chaviw3277faf2021-05-19 16:45:23 -05002417 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002418 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002419 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002420
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002421 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002422
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002423 if (displayArgs.transform == nullptr) {
2424 // Do not let the window receive touches if it is not associated with a valid display
2425 // transform. We still allow the window to receive keys and prevent ANRs.
2426 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2427 }
2428
Robert Carr5dc426e2020-06-10 14:29:14 -07002429 // For compatibility reasons we let layers which can receive input
2430 // receive input before they have actually submitted a buffer. Because
2431 // of this we use canReceiveInput instead of isVisible to check the
2432 // policy-visibility, ignoring the buffer state. However for layers with
2433 // hasInputInfo()==false we can use the real visibility state.
2434 // We are just using these layers for occlusion detection in
2435 // InputDispatcher, and obviously if they aren't visible they can't occlude
2436 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002437 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2438 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2439
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002440 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002441 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002442 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002443
Vishnu Nair16a938f2021-09-24 07:14:54 -07002444 // If the window will be blacked out on a display because the display does not have the secure
2445 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002446 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002447 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002448 }
2449
Vishnu Nairfed7c122023-03-18 01:54:43 +00002450 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002451 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002452 Rect inputBoundsInDisplaySpace;
2453 if (!cropLayer) {
2454 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2455 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2456 } else {
2457 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2458 inputBoundsInDisplaySpace =
2459 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2460 }
2461 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002462 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002463 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2464 Rect inputBoundsInDisplaySpace =
2465 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2466 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002467 }
2468
Winson Chunga30f7c92021-06-29 15:42:56 -07002469 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2470 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002471 if (isTrustedOverlay()) {
2472 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2473 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002474
chaviwaf87b3e2019-10-01 16:59:28 -07002475 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2476 // touches from going outside the cloned area.
2477 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002478 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002479 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2480 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002481 info.touchableRegion = info.touchableRegion.intersect(rect);
2482 }
2483 }
2484
Robert Carr720e5062018-07-30 17:45:14 -07002485 return info;
2486}
2487
Vishnu Nairfed7c122023-03-18 01:54:43 +00002488Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2489 const ui::Transform& screenToDisplay) {
2490 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2491 // frame and transform used for the layer, which determines the bounds and the coordinate space
2492 // within which the layer will receive input.
2493
2494 // Coordinate space definitions:
2495 // - display: The display device's coordinate space. Correlates to pixels on the display.
2496 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2497 // - layer: The coordinate space of this layer.
2498 // - input: The coordinate space in which this layer will receive input events. This could be
2499 // different than layer space if a surfaceInset is used, which changes the origin
2500 // of the input space.
2501
2502 // Crop the input bounds to ensure it is within the parent's bounds.
2503 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2504 const ui::Transform layerToScreen = getInputTransform();
2505 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2506 return Rect{layerToDisplay.transform(croppedInputBounds)};
2507}
2508
chaviwaf87b3e2019-10-01 16:59:28 -07002509sp<Layer> Layer::getClonedRoot() {
2510 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002511 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002512 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002513 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002514 return nullptr;
2515 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002516 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002517}
2518
Robert Carredd13602020-04-13 17:24:34 -07002519bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002520 return mDrawingState.inputInfo.token != nullptr ||
2521 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002522}
2523
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002524compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002525 const DisplayDevice* display) const {
2526 if (!display) return nullptr;
Vishnu Naird47bcee2023-02-24 18:08:51 +00002527 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2528 return display->getCompositionDisplay()->getOutputLayerForLayer(
2529 getCompositionEngineLayerFE());
2530 }
2531 sp<LayerFE> layerFE;
2532 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2533 for (auto& [p, layer] : mLayerFEs) {
2534 if (p == path) {
2535 layerFE = layer;
2536 }
2537 }
2538
2539 if (!layerFE) return nullptr;
2540 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002541}
2542
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002543Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2544 const auto outputLayer = findOutputLayerForDisplay(display);
2545 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002546}
2547
chaviwb4c6e582019-08-16 14:35:07 -07002548void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002549 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002550 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002551 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2552 mPotentialCursor = clonedFrom->mPotentialCursor;
2553 mProtectedByApp = clonedFrom->mProtectedByApp;
2554 updateCloneBufferInfo();
2555}
2556
2557void Layer::updateCloneBufferInfo() {
2558 if (!isClone() || !isClonedFromAlive()) {
2559 return;
2560 }
2561
2562 sp<Layer> clonedFrom = getClonedFrom();
2563 mBufferInfo = clonedFrom->mBufferInfo;
2564 mSidebandStream = clonedFrom->mSidebandStream;
2565 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2566 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2567 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2568
2569 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2570 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2571 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2572 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2573 // the cloned drawingState again.
2574 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2575 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2576 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2577 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2578
2579 cloneDrawingState(clonedFrom.get());
2580
2581 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2582 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2583 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2584 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002585}
chaviw74b03172019-08-19 11:09:03 -07002586
2587void Layer::updateMirrorInfo() {
2588 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2589 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2590 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2591 // that case, we want to delete the reference to the clone since we want it to get
2592 // destroyed. The root, this layer, will still be around since the client can continue
2593 // to hold a reference, but no cloned layers will be displayed.
2594 mClonedChild = nullptr;
2595 return;
2596 }
2597
2598 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2599 // If the real layer exists and is in current state, add the clone as a child of the root.
2600 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2601 // copied to drawingState for the root layer. So the clonedChild is always removed from
2602 // drawingState and then needs to be added back each traversal.
2603 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2604 addChildToDrawing(mClonedChild);
2605 }
2606
2607 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002608 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002609 mClonedChild->updateClonedRelatives(clonedLayersMap);
2610}
2611
2612void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2613 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2614 // to the clone. If the real layer is no longer alive, continue traversing the children
2615 // since we may be able to pull out other children that are still alive.
2616 if (isClonedFromAlive()) {
2617 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002618 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002619 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002620 }
2621
2622 // The clone layer may have children in drawingState since they may have been created and
2623 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2624 // that already exist, since we can just re-use them.
2625 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2626 // not updated in the regular traversal. They are skipped since the root will lose the
2627 // reference to them when it copies its currentChildren to drawing.
2628 for (sp<Layer>& child : mDrawingChildren) {
2629 child->updateClonedDrawingState(clonedLayersMap);
2630 }
2631}
2632
2633void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2634 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2635 mDrawingChildren.clear();
2636
2637 if (!isClonedFromAlive()) {
2638 return;
2639 }
2640
2641 sp<Layer> clonedFrom = getClonedFrom();
2642 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2643 if (child == mirrorRoot) {
2644 // This is to avoid cyclical mirroring.
2645 continue;
2646 }
2647 sp<Layer> clonedChild = clonedLayersMap[child];
2648 if (clonedChild == nullptr) {
2649 clonedChild = child->createClone();
2650 clonedLayersMap[child] = clonedChild;
2651 }
2652 addChildToDrawing(clonedChild);
2653 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2654 }
2655}
2656
chaviwaf87b3e2019-10-01 16:59:28 -07002657void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2658 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2659 if (cropLayer != nullptr) {
2660 if (clonedLayersMap.count(cropLayer) == 0) {
2661 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2662 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002663 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002664 } else {
2665 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2666 mDrawingState.touchableRegionCrop = clonedCropLayer;
2667 }
2668 }
2669 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2670 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002671 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002672}
2673
2674void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002675 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002676 mDrawingState.zOrderRelatives.clear();
2677
2678 if (!isClonedFromAlive()) {
2679 return;
2680 }
2681
chaviwaf87b3e2019-10-01 16:59:28 -07002682 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002683 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002684 const sp<Layer>& relative = relativeWeak.promote();
2685 if (clonedLayersMap.count(relative) > 0) {
2686 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002687 mDrawingState.zOrderRelatives.add(clonedRelative);
2688 }
2689 }
2690
2691 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2692 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2693 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2694 // still traverse the children, but the layer with the missing relativeOf will not be shown
2695 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002696 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2697 if (clonedLayersMap.count(relativeOf) > 0) {
2698 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002699 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2700 }
2701
chaviwaf87b3e2019-10-01 16:59:28 -07002702 updateClonedInputInfo(clonedLayersMap);
2703
chaviw74b03172019-08-19 11:09:03 -07002704 for (sp<Layer>& child : mDrawingChildren) {
2705 child->updateClonedRelatives(clonedLayersMap);
2706 }
2707}
2708
2709void Layer::addChildToDrawing(const sp<Layer>& layer) {
2710 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002711 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002712}
2713
Steven Thomas62a4cf82020-01-31 12:04:03 -08002714Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2715 switch (compatibility) {
2716 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2717 return FrameRateCompatibility::Default;
2718 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2719 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002720 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2721 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002722 case ANATIVEWINDOW_FRAME_RATE_MIN:
2723 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002724 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2725 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002726 default:
2727 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2728 return FrameRateCompatibility::Default;
2729 }
2730}
2731
Marin Shalamanovc5986772021-03-16 16:09:49 +01002732scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2733 switch (strategy) {
2734 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2735 return Seamlessness::OnlySeamless;
2736 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2737 return Seamlessness::SeamedAndSeamless;
2738 default:
2739 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2740 return Seamlessness::Default;
2741 }
2742}
2743
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002744bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002745 const State& s(mDrawingState);
2746 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2747 return true;
2748 }
2749
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002750 sp<Layer> parent = mDrawingParent.promote();
2751 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002752}
2753
Robert Carr6a0382d2021-07-01 15:57:17 -07002754void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2755 mClonedChild = clonedChild;
2756 mHadClonedChild = true;
2757 mFlinger->mNumClones++;
2758}
2759
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002760bool Layer::setDropInputMode(gui::DropInputMode mode) {
2761 if (mDrawingState.dropInputMode == mode) {
2762 return false;
2763 }
2764 mDrawingState.dropInputMode = mode;
2765 return true;
2766}
2767
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002768void Layer::cloneDrawingState(const Layer* from) {
2769 mDrawingState = from->mDrawingState;
2770 // Skip callback info since they are not applicable for cloned layers.
2771 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002772 // TODO (b/238781169) currently broken for mirror layers because we do not
2773 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002774 mDrawingState.callbackHandles = {};
2775}
2776
Patrick Williamsbb25f802022-08-30 23:02:34 +00002777void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2778 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002779 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002780 if (!listener) {
2781 return;
2782 }
2783 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002784 uint32_t currentMaxAcquiredBufferCount =
2785 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002786 listener->onReleaseBuffer({buffer->getId(), framenumber},
2787 releaseFence ? releaseFence : Fence::NO_FENCE,
2788 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002789}
2790
2791void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2792 // If we are displayed on multiple displays in a single composition cycle then we would
2793 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2794 // For example we can only use it if all the displays are client comp, and we need
2795 // to merge all the client comp fences. We could do this, but for now we just
2796 // disable the optimization when a layer is composed on multiple displays.
2797 if (mClearClientCompositionFenceOnLayerDisplayed) {
2798 mLastClientCompositionFence = nullptr;
2799 } else {
2800 mClearClientCompositionFenceOnLayerDisplayed = true;
2801 }
2802
2803 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2804 // buffer that was presented on this layer. The first transaction that came in this frame that
2805 // replaced the previous buffer on this layer needs this release fence, because the fence will
2806 // let the client know when that previous buffer is removed from the screen.
2807 //
2808 // Every other transaction on this layer does not need a release fence because no other
2809 // Transactions that were set on this layer this frame are going to have their preceding buffer
2810 // removed from the display this frame.
2811 //
2812 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2813 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2814 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2815 // the previous buffer will be released this frame. The third transaction also contains a
2816 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2817 // transaction will now no longer be presented so it is released immediately and the third
2818 // transaction doesn't need a previous release fence.
2819 sp<CallbackHandle> ch;
2820 for (auto& handle : mDrawingState.callbackHandles) {
2821 if (handle->releasePreviousBuffer &&
2822 mDrawingState.releaseBufferEndpoint == handle->listener) {
2823 ch = handle;
2824 break;
2825 }
2826 }
2827
2828 // Prevent tracing the same release multiple times.
2829 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2830 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2831 }
2832
2833 if (ch != nullptr) {
2834 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2835 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2836 ch->name = mName;
2837 }
2838}
2839
2840void Layer::onSurfaceFrameCreated(
2841 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2842 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2843 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2844 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2845 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002846 if (hasBufferOrSidebandStreamInDrawing()) {
2847 // Only log for layers with a buffer, since we expect the jank data to be drained for
2848 // these, while there may be no jank listeners for bufferless layers.
2849 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2850 mName.c_str());
2851 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2852 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2853 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002854 mPendingJankClassifications.pop_front();
2855 }
2856 mPendingJankClassifications.emplace_back(surfaceFrame);
2857}
2858
2859void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2860 for (const auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair71fcf912022-10-18 09:14:20 -07002861 handle->transformHint = mSkipReportingTransformHint
2862 ? std::nullopt
2863 : std::make_optional<uint32_t>(mTransformHint);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002864 handle->dequeueReadyTime = dequeueReadyTime;
2865 handle->currentMaxAcquiredBufferCount =
2866 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2867 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2868 handle->previousReleaseCallbackId.framenumber);
2869 }
2870
2871 for (auto& handle : mDrawingState.callbackHandles) {
2872 if (handle->releasePreviousBuffer &&
2873 mDrawingState.releaseBufferEndpoint == handle->listener) {
2874 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2875 break;
2876 }
2877 }
2878
2879 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002880 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002881 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2882 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002883 mDrawingState.callbackHandles = {};
2884}
2885
2886bool Layer::willPresentCurrentTransaction() const {
2887 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2888 return (getSidebandStreamChanged() || getAutoRefresh() ||
2889 (mDrawingState.modified &&
2890 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2891}
2892
2893bool Layer::setTransform(uint32_t transform) {
2894 if (mDrawingState.bufferTransform == transform) return false;
2895 mDrawingState.bufferTransform = transform;
2896 mDrawingState.modified = true;
2897 setTransactionFlags(eTransactionNeeded);
2898 return true;
2899}
2900
2901bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2902 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2903 mDrawingState.sequence++;
2904 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2905 mDrawingState.modified = true;
2906 setTransactionFlags(eTransactionNeeded);
2907 return true;
2908}
2909
2910bool Layer::setBufferCrop(const Rect& bufferCrop) {
2911 if (mDrawingState.bufferCrop == bufferCrop) return false;
2912
2913 mDrawingState.sequence++;
2914 mDrawingState.bufferCrop = bufferCrop;
2915
2916 mDrawingState.modified = true;
2917 setTransactionFlags(eTransactionNeeded);
2918 return true;
2919}
2920
2921bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2922 if (mDrawingState.destinationFrame == destinationFrame) return false;
2923
2924 mDrawingState.sequence++;
2925 mDrawingState.destinationFrame = destinationFrame;
2926
2927 mDrawingState.modified = true;
2928 setTransactionFlags(eTransactionNeeded);
2929 return true;
2930}
2931
2932// Translate destination frame into scale and position. If a destination frame is not set, use the
2933// provided scale and position
2934bool Layer::updateGeometry() {
2935 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2936 mDrawingState.destinationFrame.isEmpty()) {
2937 // If destination frame is not set, use the requested transform set via
2938 // Layer::setPosition and Layer::setMatrix.
2939 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2940 }
2941
2942 Rect destRect = mDrawingState.destinationFrame;
2943 int32_t destW = destRect.width();
2944 int32_t destH = destRect.height();
2945 if (destRect.left < 0) {
2946 destRect.left = 0;
2947 destRect.right = destW;
2948 }
2949 if (destRect.top < 0) {
2950 destRect.top = 0;
2951 destRect.bottom = destH;
2952 }
2953
2954 if (!mDrawingState.buffer) {
2955 ui::Transform t;
2956 t.set(destRect.left, destRect.top);
2957 return assignTransform(&mDrawingState.transform, t);
2958 }
2959
2960 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2961 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2962 // Undo any transformations on the buffer.
2963 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2964 std::swap(bufferWidth, bufferHeight);
2965 }
2966 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
2967 if (mDrawingState.transformToDisplayInverse) {
2968 if (invTransform & ui::Transform::ROT_90) {
2969 std::swap(bufferWidth, bufferHeight);
2970 }
2971 }
2972
2973 float sx = destW / static_cast<float>(bufferWidth);
2974 float sy = destH / static_cast<float>(bufferHeight);
2975 ui::Transform t;
2976 t.set(sx, 0, 0, sy);
2977 t.set(destRect.left, destRect.top);
2978 return assignTransform(&mDrawingState.transform, t);
2979}
2980
2981bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
2982 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
2983 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
2984 return false;
2985 }
2986
2987 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
2988
2989 mDrawingState.sequence++;
2990 mDrawingState.modified = true;
2991 setTransactionFlags(eTransactionNeeded);
2992
2993 return true;
2994}
2995
2996bool Layer::setPosition(float x, float y) {
2997 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
2998 return false;
2999 }
3000
3001 mRequestedTransform.set(x, y);
3002
3003 mDrawingState.sequence++;
3004 mDrawingState.modified = true;
3005 setTransactionFlags(eTransactionNeeded);
3006
3007 return true;
3008}
3009
3010bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3011 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3012 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003013 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003014 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003015 if (!buffer) {
3016 return false;
3017 }
3018
3019 const bool frameNumberChanged =
3020 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3021 const uint64_t frameNumber =
3022 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003023 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003024
3025 if (mDrawingState.buffer) {
3026 mReleasePreviousBuffer = true;
3027 if (!mBufferInfo.mBuffer ||
3028 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3029 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3030 // If mDrawingState has a buffer, and we are about to update again
3031 // before swapping to drawing state, then the first buffer will be
3032 // dropped and we should decrement the pending buffer count and
3033 // call any release buffer callbacks if set.
3034 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3035 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003036 mDrawingState.acquireFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003037 decrementPendingBufferCount();
3038 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3039 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3040 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
3041 mDrawingState.bufferSurfaceFrameTX.reset();
3042 }
3043 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3044 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3045 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003046 mLastClientCompositionFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003047 mLastClientCompositionFence = nullptr;
3048 }
Vishnu Nairc09c0232023-03-02 03:22:35 +00003049 } else {
3050 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3051 // we don't want to incorrectly classify a frame if we miss the desired present time.
3052 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003053 }
3054
liulijuneb489f62022-10-17 22:02:14 +08003055 mDrawingState.producerId = bufferData.producerId;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003056 mDrawingState.frameNumber = frameNumber;
3057 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3058 mDrawingState.buffer = std::move(buffer);
3059 mDrawingState.clientCacheId = bufferData.cachedBuffer;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003060 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3061 ? bufferData.acquireFence
3062 : Fence::NO_FENCE;
3063 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3064 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3065 // We latched this buffer unsiganled, so we need to pass the acquire fence
3066 // on the callback instead of just the acquire time, since it's unknown at
3067 // this point.
3068 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3069 } else {
3070 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3071 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003072 mDrawingState.latchedVsyncId = info.vsyncId;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003073 mDrawingState.modified = true;
3074 setTransactionFlags(eTransactionNeeded);
3075
3076 const int32_t layerId = getSequence();
3077 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3078 mOwnerUid, postTime, getGameMode());
3079 mDrawingState.desiredPresentTime = desiredPresentTime;
3080 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3081
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003082 if (mFlinger->mLegacyFrontEndEnabled) {
3083 recordLayerHistoryBufferUpdate(getLayerProps());
3084 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003085
3086 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3087
3088 if (dequeueTime && *dequeueTime != 0) {
3089 const uint64_t bufferId = mDrawingState.buffer->getId();
3090 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3091 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3092 FrameTracer::FrameEvent::DEQUEUE);
3093 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3094 FrameTracer::FrameEvent::QUEUE);
3095 }
3096
3097 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3098 return true;
3099}
3100
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003101void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3102 mDrawingState.desiredPresentTime = desiredPresentTime;
3103 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3104}
3105
3106void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps) {
3107 const nsecs_t presentTime = [&] {
3108 if (!mDrawingState.isAutoTimestamp) return mDrawingState.desiredPresentTime;
3109
3110 const auto prediction = mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3111 mDrawingState.latchedVsyncId);
3112 if (prediction.has_value()) return prediction->presentTime;
3113
3114 return static_cast<nsecs_t>(0);
3115 }();
3116 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3117 scheduler::LayerHistory::LayerUpdateType::Buffer);
3118}
3119
3120void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps) {
3121 const nsecs_t presentTime =
3122 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
3123 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3124 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3125}
3126
Patrick Williamsbb25f802022-08-30 23:02:34 +00003127bool Layer::setDataspace(ui::Dataspace dataspace) {
3128 mDrawingState.dataspaceRequested = true;
3129 if (mDrawingState.dataspace == dataspace) return false;
3130 mDrawingState.dataspace = dataspace;
3131 mDrawingState.modified = true;
3132 setTransactionFlags(eTransactionNeeded);
3133 return true;
3134}
3135
John Reck68796592023-01-25 13:47:12 -05003136bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
3137 if (mDrawingState.currentSdrHdrRatio == currentBufferRatio &&
3138 mDrawingState.desiredSdrHdrRatio == desiredRatio)
3139 return false;
3140 mDrawingState.currentSdrHdrRatio = currentBufferRatio;
3141 mDrawingState.desiredSdrHdrRatio = desiredRatio;
3142 mDrawingState.modified = true;
3143 setTransactionFlags(eTransactionNeeded);
3144 return true;
3145}
3146
Alec Mourif4af03e2023-02-11 00:25:24 +00003147bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3148 if (mDrawingState.cachingHint == cachingHint) return false;
3149 mDrawingState.cachingHint = cachingHint;
3150 mDrawingState.modified = true;
3151 setTransactionFlags(eTransactionNeeded);
3152 return true;
3153}
3154
Patrick Williamsbb25f802022-08-30 23:02:34 +00003155bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3156 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3157 mDrawingState.hdrMetadata = hdrMetadata;
3158 mDrawingState.modified = true;
3159 setTransactionFlags(eTransactionNeeded);
3160 return true;
3161}
3162
3163bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
3164 mDrawingState.surfaceDamageRegion = surfaceDamage;
3165 mDrawingState.modified = true;
3166 setTransactionFlags(eTransactionNeeded);
3167 return true;
3168}
3169
3170bool Layer::setApi(int32_t api) {
3171 if (mDrawingState.api == api) return false;
3172 mDrawingState.api = api;
3173 mDrawingState.modified = true;
3174 setTransactionFlags(eTransactionNeeded);
3175 return true;
3176}
3177
3178bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3179 if (mDrawingState.sidebandStream == sidebandStream) return false;
3180
3181 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3182 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3183 } else if (sidebandStream != nullptr) {
3184 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3185 }
3186
3187 mDrawingState.sidebandStream = sidebandStream;
3188 mDrawingState.modified = true;
3189 setTransactionFlags(eTransactionNeeded);
3190 if (!mSidebandStreamChanged.exchange(true)) {
3191 // mSidebandStreamChanged was false
3192 mFlinger->onLayerUpdate();
3193 }
3194 return true;
3195}
3196
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003197bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3198 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003199 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3200 if (handles.empty()) {
3201 mReleasePreviousBuffer = false;
3202 return false;
3203 }
3204
Pascal Muetschard81cef292023-02-06 12:18:52 +01003205 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003206 for (const auto& handle : handles) {
3207 // If this transaction set a buffer on this layer, release its previous buffer
3208 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3209
3210 // If this layer will be presented in this frame
3211 if (willPresent) {
3212 // If this transaction set an acquire fence on this layer, set its acquire time
3213 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3214 handle->frameNumber = mDrawingState.frameNumber;
3215
3216 // Store so latched time and release fence can be set
3217 mDrawingState.callbackHandles.push_back(handle);
3218
3219 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003220 // Queue this handle to be notified below.
3221 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003222 }
3223 }
3224
Pascal Muetschard81cef292023-02-06 12:18:52 +01003225 if (!remainingHandles.empty()) {
3226 // Notify the transaction completed threads these handles are done. These are only the
3227 // handles that were not added to the mDrawingState, which will be notified later.
3228 std::vector<JankData> jankData;
3229 transferAvailableJankData(remainingHandles, jankData);
3230 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3231 }
3232
Patrick Williamsbb25f802022-08-30 23:02:34 +00003233 mReleasePreviousBuffer = false;
3234 mCallbackHandleAcquireTimeOrFence = -1;
3235
3236 return willPresent;
3237}
3238
3239Rect Layer::getBufferSize(const State& /*s*/) const {
3240 // for buffer state layers we use the display frame size as the buffer size.
3241
3242 if (mBufferInfo.mBuffer == nullptr) {
3243 return Rect::INVALID_RECT;
3244 }
3245
3246 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3247 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3248
3249 // Undo any transformations on the buffer and return the result.
3250 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3251 std::swap(bufWidth, bufHeight);
3252 }
3253
3254 if (getTransformToDisplayInverse()) {
3255 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3256 if (invTransform & ui::Transform::ROT_90) {
3257 std::swap(bufWidth, bufHeight);
3258 }
3259 }
3260
3261 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3262}
3263
3264FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3265 if (mBufferInfo.mBuffer == nullptr) {
3266 return parentBounds;
3267 }
3268
3269 return getBufferSize(getDrawingState()).toFloatRect();
3270}
3271
3272bool Layer::fenceHasSignaled() const {
3273 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3274 return true;
3275 }
3276
3277 const bool fenceSignaled =
3278 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3279 if (!fenceSignaled) {
3280 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3281 TimeStats::LatchSkipReason::LateAcquire);
3282 }
3283
3284 return fenceSignaled;
3285}
3286
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003287void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003288 for (const auto& handle : mDrawingState.callbackHandles) {
3289 handle->refreshStartTime = refreshStartTime;
3290 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003291}
3292
3293void Layer::setAutoRefresh(bool autoRefresh) {
3294 mDrawingState.autoRefresh = autoRefresh;
3295}
3296
3297bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3298 // 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 +00003299 auto* snapshot = editLayerSnapshot();
3300 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003301
3302 if (mSidebandStreamChanged.exchange(false)) {
3303 const State& s(getDrawingState());
3304 // mSidebandStreamChanged was true
3305 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003306 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003307 if (mSidebandStream != nullptr) {
3308 setTransactionFlags(eTransactionNeeded);
3309 mFlinger->setTransactionFlags(eTraversalNeeded);
3310 }
3311 recomputeVisibleRegions = true;
3312
3313 return true;
3314 }
3315 return false;
3316}
3317
3318bool Layer::hasFrameUpdate() const {
3319 const State& c(getDrawingState());
3320 return (mDrawingStateModified || mDrawingState.modified) &&
3321 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3322}
3323
Vishnu Naird47bcee2023-02-24 18:08:51 +00003324void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003325 const State& s(getDrawingState());
3326
3327 if (!s.buffer) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003328 if (bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003329 for (auto& handle : mDrawingState.callbackHandles) {
3330 handle->latchTime = latchTime;
3331 }
3332 }
3333 return;
3334 }
3335
3336 for (auto& handle : mDrawingState.callbackHandles) {
3337 if (handle->frameNumber == mDrawingState.frameNumber) {
3338 handle->latchTime = latchTime;
3339 }
3340 }
3341
3342 const int32_t layerId = getSequence();
3343 const uint64_t bufferId = mDrawingState.buffer->getId();
3344 const uint64_t frameNumber = mDrawingState.frameNumber;
3345 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3346 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3347 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3348
3349 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3350 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3351 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3352 FrameTracer::FrameEvent::LATCH);
3353
3354 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3355 if (bufferSurfaceFrame != nullptr &&
3356 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3357 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3358 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3359 // are processing the next state.
3360 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3361 mDrawingState.acquireFenceTime->getSignalTime(),
3362 latchTime);
3363 mDrawingState.bufferSurfaceFrameTX.reset();
3364 }
3365
3366 std::deque<sp<CallbackHandle>> remainingHandles;
3367 mFlinger->getTransactionCallbackInvoker()
3368 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3369 mDrawingState.callbackHandles = remainingHandles;
3370
3371 mDrawingStateModified = false;
3372}
3373
3374void Layer::gatherBufferInfo() {
3375 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3376 decrementPendingBufferCount();
3377 }
3378
3379 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3380 mBufferInfo.mBuffer = mDrawingState.buffer;
3381 mBufferInfo.mFence = mDrawingState.acquireFence;
3382 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3383 mBufferInfo.mPixelFormat =
3384 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3385 mBufferInfo.mFrameLatencyNeeded = true;
3386 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3387 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3388 mBufferInfo.mFence = mDrawingState.acquireFence;
3389 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3390 auto lastDataspace = mBufferInfo.mDataspace;
3391 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3392 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003393 mFlinger->mHdrLayerInfoChanged = true;
3394 }
3395 if (mBufferInfo.mDesiredSdrHdrRatio != mDrawingState.desiredSdrHdrRatio) {
3396 mBufferInfo.mDesiredSdrHdrRatio = mDrawingState.desiredSdrHdrRatio;
3397 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003398 }
3399 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3400 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3401 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3402 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3403 mBufferInfo.mApi = mDrawingState.api;
3404 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003405}
3406
3407Rect Layer::computeBufferCrop(const State& s) {
3408 if (s.buffer && !s.bufferCrop.isEmpty()) {
3409 Rect bufferCrop;
3410 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3411 return bufferCrop;
3412 } else if (s.buffer) {
3413 return s.buffer->getBounds();
3414 } else {
3415 return s.bufferCrop;
3416 }
3417}
3418
3419sp<Layer> Layer::createClone() {
3420 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3421 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003422 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003423 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3424 return layer;
3425}
3426
Patrick Williamsbb25f802022-08-30 23:02:34 +00003427void Layer::decrementPendingBufferCount() {
3428 int32_t pendingBuffers = --mPendingBufferTransactions;
3429 tracePendingBufferCount(pendingBuffers);
3430}
3431
3432void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3433 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3434}
3435
3436/*
3437 * We don't want to send the layer's transform to input, but rather the
3438 * parent's transform. This is because Layer's transform is
3439 * information about how the buffer is placed on screen. The parent's
3440 * transform makes more sense to send since it's information about how the
3441 * layer is placed on screen. This transform is used by input to determine
3442 * how to go from screen space back to window space.
3443 */
3444ui::Transform Layer::getInputTransform() const {
3445 if (!hasBufferOrSidebandStream()) {
3446 return getTransform();
3447 }
3448 sp<Layer> parent = mDrawingParent.promote();
3449 if (parent == nullptr) {
3450 return ui::Transform();
3451 }
3452
3453 return parent->getTransform();
3454}
3455
3456/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003457 * Returns the bounds used to fill the input frame and the touchable region.
3458 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003459 * Similar to getInputTransform, we need to update the bounds to include the transform.
3460 * This is because bounds don't include the buffer transform, where the input assumes
3461 * that's already included.
3462 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003463std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3464 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3465 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3466 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3467 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3468 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003469 }
3470
Vishnu Nairfed7c122023-03-18 01:54:43 +00003471 bool inputBoundsValid = croppedBufferSize.isValid();
3472 if (!inputBoundsValid) {
3473 /**
3474 * Input bounds are based on the layer crop or buffer size. But if we are using
3475 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3476 * we can use the parent bounds as the input bounds if the layer does not have buffer
3477 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3478 * use the parent bounds. A layer without a buffer can get input. So when a window is
3479 * initially added, its touchable region can fill its parent layer bounds and that can
3480 * have negative consequences.
3481 */
3482 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003483 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003484
3485 // Clamp surface inset to the input bounds.
3486 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3487 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3488 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3489
3490 // Apply the insets to the input bounds.
3491 inputBounds.left += xSurfaceInset;
3492 inputBounds.top += ySurfaceInset;
3493 inputBounds.right -= xSurfaceInset;
3494 inputBounds.bottom -= ySurfaceInset;
3495
3496 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003497}
3498
3499bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3500 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3501
3502 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3503 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3504 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3505 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3506 layer_state_t::eReparent;
3507
3508 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3509 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3510 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3511 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3512 layer_state_t::eInputInfoChanged;
3513
3514 if ((s.what & requiredFlags) != requiredFlags) {
3515 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3516 (s.what | requiredFlags) & ~s.what);
3517 return false;
3518 }
3519
3520 if (s.what & deniedFlags) {
3521 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3522 return false;
3523 }
3524
3525 if (s.what & allowedFlags) {
3526 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3527 }
3528
3529 if (s.what & layer_state_t::ePositionChanged) {
3530 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3531 ALOGV("%s: false [ePositionChanged changed]", __func__);
3532 return false;
3533 }
3534 }
3535
3536 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003537 if (mDrawingState.color.a != s.color.a) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003538 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3539 return false;
3540 }
3541 }
3542
3543 if (s.what & layer_state_t::eColorTransformChanged) {
3544 if (mDrawingState.colorTransform != s.colorTransform) {
3545 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3546 return false;
3547 }
3548 }
3549
3550 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003551 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003552 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3553 return false;
3554 }
3555 }
3556
3557 if (s.what & layer_state_t::eMatrixChanged) {
3558 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3559 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3560 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3561 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3562 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3563 return false;
3564 }
3565 }
3566
3567 if (s.what & layer_state_t::eCornerRadiusChanged) {
3568 if (mDrawingState.cornerRadius != s.cornerRadius) {
3569 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3570 return false;
3571 }
3572 }
3573
3574 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3575 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3576 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3577 return false;
3578 }
3579 }
3580
Vishnu Nairbbceb462022-10-10 04:52:13 +00003581 if (s.what & layer_state_t::eBufferTransformChanged) {
3582 if (mDrawingState.bufferTransform != s.bufferTransform) {
3583 ALOGV("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003584 return false;
3585 }
3586 }
3587
3588 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3589 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3590 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3591 return false;
3592 }
3593 }
3594
3595 if (s.what & layer_state_t::eCropChanged) {
3596 if (mDrawingState.crop != s.crop) {
3597 ALOGV("%s: false [eCropChanged changed]", __func__);
3598 return false;
3599 }
3600 }
3601
3602 if (s.what & layer_state_t::eDataspaceChanged) {
3603 if (mDrawingState.dataspace != s.dataspace) {
3604 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3605 return false;
3606 }
3607 }
3608
3609 if (s.what & layer_state_t::eHdrMetadataChanged) {
3610 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3611 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3612 return false;
3613 }
3614 }
3615
3616 if (s.what & layer_state_t::eSidebandStreamChanged) {
3617 if (mDrawingState.sidebandStream != s.sidebandStream) {
3618 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3619 return false;
3620 }
3621 }
3622
3623 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3624 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3625 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3626 return false;
3627 }
3628 }
3629
3630 if (s.what & layer_state_t::eShadowRadiusChanged) {
3631 if (mDrawingState.shadowRadius != s.shadowRadius) {
3632 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3633 return false;
3634 }
3635 }
3636
3637 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3638 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3639 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3640 return false;
3641 }
3642 }
3643
3644 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3645 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3646 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3647 return false;
3648 }
3649 }
3650
3651 if (s.what & layer_state_t::eStretchChanged) {
3652 StretchEffect temp = s.stretchEffect;
3653 temp.sanitize();
3654 if (mDrawingState.stretchEffect != temp) {
3655 ALOGV("%s: false [eStretchChanged changed]", __func__);
3656 return false;
3657 }
3658 }
3659
3660 if (s.what & layer_state_t::eBufferCropChanged) {
3661 if (mDrawingState.bufferCrop != s.bufferCrop) {
3662 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3663 return false;
3664 }
3665 }
3666
3667 if (s.what & layer_state_t::eDestinationFrameChanged) {
3668 if (mDrawingState.destinationFrame != s.destinationFrame) {
3669 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3670 return false;
3671 }
3672 }
3673
3674 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3675 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3676 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3677 return false;
3678 }
3679 }
3680
John Reck68796592023-01-25 13:47:12 -05003681 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
3682 if (mDrawingState.currentSdrHdrRatio != s.currentSdrHdrRatio ||
3683 mDrawingState.desiredSdrHdrRatio != s.desiredSdrHdrRatio) {
3684 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3685 return false;
3686 }
3687 }
3688
Patrick Williamsbb25f802022-08-30 23:02:34 +00003689 ALOGV("%s: true", __func__);
3690 return true;
3691}
3692
3693bool Layer::isHdrY410() const {
3694 // pixel format is HDR Y410 masquerading as RGBA_1010102
3695 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3696 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3697 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3698}
3699
Vishnu Naire14c6b32022-08-06 04:20:15 +00003700sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003701 // 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 +00003702 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003703}
3704
Vishnu Naire14c6b32022-08-06 04:20:15 +00003705const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003706 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003707}
3708
Vishnu Naire14c6b32022-08-06 04:20:15 +00003709LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003710 return mSnapshot.get();
3711}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003712
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003713std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3714 return std::move(mSnapshot);
3715}
3716
3717void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3718 mSnapshot = std::move(snapshot);
3719}
3720
Patrick Williamsbb25f802022-08-30 23:02:34 +00003721const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003722 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003723}
3724
Patrick Williams7584c6a2022-10-29 02:10:58 +00003725sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003726 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003727 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3728 return result;
3729}
3730
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003731sp<LayerFE> Layer::getCompositionEngineLayerFE(
3732 const frontend::LayerHierarchy::TraversalPath& path) {
3733 for (auto& [p, layerFE] : mLayerFEs) {
3734 if (p == path) {
3735 return layerFE;
3736 }
3737 }
3738 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3739 mLayerFEs.emplace_back(path, layerFE);
3740 return layerFE;
3741}
3742
Patrick Williamsbb25f802022-08-30 23:02:34 +00003743void Layer::useSurfaceDamage() {
3744 if (mFlinger->mForceFullDamage) {
3745 surfaceDamageRegion = Region::INVALID_REGION;
3746 } else {
3747 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3748 }
3749}
3750
3751void Layer::useEmptyDamage() {
3752 surfaceDamageRegion.clear();
3753}
3754
3755bool Layer::isOpaque(const Layer::State& s) const {
3756 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3757 // layer's opaque flag.
3758 if (!hasSomethingToDraw()) {
3759 return false;
3760 }
3761
3762 // if the layer has the opaque flag, then we're always opaque
3763 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3764 return true;
3765 }
3766
3767 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003768 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003769 return true;
3770 }
3771
3772 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3773 return fillsColor() && getAlpha() == 1.0_hf;
3774}
3775
3776bool Layer::canReceiveInput() const {
3777 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3778}
3779
3780bool Layer::isVisible() const {
3781 if (!hasSomethingToDraw()) {
3782 return false;
3783 }
3784
3785 if (isHiddenByPolicy()) {
3786 return false;
3787 }
3788
3789 return getAlpha() > 0.0f || hasBlur();
3790}
3791
3792void Layer::onPostComposition(const DisplayDevice* display,
3793 const std::shared_ptr<FenceTime>& glDoneFence,
3794 const std::shared_ptr<FenceTime>& presentFence,
3795 const CompositorTiming& compositorTiming) {
3796 // mFrameLatencyNeeded is true when a new frame was latched for the
3797 // composition.
3798 if (!mBufferInfo.mFrameLatencyNeeded) return;
3799
3800 for (const auto& handle : mDrawingState.callbackHandles) {
3801 handle->gpuCompositionDoneFence = glDoneFence;
3802 handle->compositorTiming = compositorTiming;
3803 }
3804
3805 // Update mFrameTracker.
3806 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3807 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3808
3809 const int32_t layerId = getSequence();
3810 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3811
3812 const auto outputLayer = findOutputLayerForDisplay(display);
3813 if (outputLayer && outputLayer->requiresClientComposition()) {
3814 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3815 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3816 clientCompositionTimestamp,
3817 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3818 // Update the SurfaceFrames in the drawing state
3819 if (mDrawingState.bufferSurfaceFrameTX) {
3820 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3821 }
3822 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3823 surfaceFrame->setGpuComposition();
3824 }
3825 }
3826
3827 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3828 if (frameReadyFence->isValid()) {
3829 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3830 } else {
3831 // There was no fence for this frame, so assume that it was ready
3832 // to be presented at the desired present time.
3833 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3834 }
3835
3836 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08003837 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003838 const std::optional<Fps> renderRate =
3839 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3840
3841 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3842 const auto gameMode = getGameMode();
3843
3844 if (presentFence->isValid()) {
3845 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3846 refreshRate, renderRate, vote, gameMode);
3847 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3848 presentFence,
3849 FrameTracer::FrameEvent::PRESENT_FENCE);
3850 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3851 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3852 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003853 // The HWC doesn't support present fences, so use the present timestamp instead.
3854 const nsecs_t presentTimestamp =
3855 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3856
3857 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3858 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3859 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3860
Patrick Williamsbb25f802022-08-30 23:02:34 +00003861 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3862 refreshRate, renderRate, vote, gameMode);
3863 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3864 mCurrentFrameNumber, actualPresentTime,
3865 FrameTracer::FrameEvent::PRESENT_FENCE);
3866 mFrameTracker.setActualPresentTime(actualPresentTime);
3867 }
3868 }
3869
3870 mFrameTracker.advanceFrame();
3871 mBufferInfo.mFrameLatencyNeeded = false;
3872}
3873
3874bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003875 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
3876 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
3877}
3878
3879bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003880 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3881 getDrawingState().frameNumber);
3882
3883 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3884
3885 if (refreshRequired) {
3886 return refreshRequired;
3887 }
3888
3889 // If the head buffer's acquire fence hasn't signaled yet, return and
3890 // try again later
3891 if (!fenceHasSignaled()) {
3892 ATRACE_NAME("!fenceHasSignaled()");
3893 mFlinger->onLayerUpdate();
3894 return false;
3895 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00003896 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003897 if (mDrawingState.buffer == nullptr) {
3898 return false;
3899 }
3900
3901 // Capture the old state of the layer for comparisons later
3902 BufferInfo oldBufferInfo = mBufferInfo;
3903 const bool oldOpacity = isOpaque(mDrawingState);
3904 mPreviousFrameNumber = mCurrentFrameNumber;
3905 mCurrentFrameNumber = mDrawingState.frameNumber;
3906 gatherBufferInfo();
3907
3908 if (oldBufferInfo.mBuffer == nullptr) {
3909 // the first time we receive a buffer, we need to trigger a
3910 // geometry invalidation.
3911 recomputeVisibleRegions = true;
3912 }
3913
3914 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3915 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3916 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3917 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3918 recomputeVisibleRegions = true;
3919 }
3920
3921 if (oldBufferInfo.mBuffer != nullptr) {
3922 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3923 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3924 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3925 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3926 recomputeVisibleRegions = true;
3927 }
3928 }
3929
3930 if (oldOpacity != isOpaque(mDrawingState)) {
3931 recomputeVisibleRegions = true;
3932 }
3933
3934 return true;
3935}
3936
3937bool Layer::hasReadyFrame() const {
3938 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
3939}
3940
3941bool Layer::isProtected() const {
3942 return (mBufferInfo.mBuffer != nullptr) &&
3943 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
3944}
3945
Patrick Williamsbb25f802022-08-30 23:02:34 +00003946void Layer::latchAndReleaseBuffer() {
3947 if (hasReadyFrame()) {
3948 bool ignored = false;
3949 latchBuffer(ignored, systemTime());
3950 }
3951 releasePendingBuffer(systemTime());
3952}
3953
3954PixelFormat Layer::getPixelFormat() const {
3955 return mBufferInfo.mPixelFormat;
3956}
3957
3958bool Layer::getTransformToDisplayInverse() const {
3959 return mBufferInfo.mTransformToDisplayInverse;
3960}
3961
3962Rect Layer::getBufferCrop() const {
3963 // this is the crop rectangle that applies to the buffer
3964 // itself (as opposed to the window)
3965 if (!mBufferInfo.mCrop.isEmpty()) {
3966 // if the buffer crop is defined, we use that
3967 return mBufferInfo.mCrop;
3968 } else if (mBufferInfo.mBuffer != nullptr) {
3969 // otherwise we use the whole buffer
3970 return mBufferInfo.mBuffer->getBounds();
3971 } else {
3972 // if we don't have a buffer yet, we use an empty/invalid crop
3973 return Rect();
3974 }
3975}
3976
3977uint32_t Layer::getBufferTransform() const {
3978 return mBufferInfo.mTransform;
3979}
3980
3981ui::Dataspace Layer::getDataSpace() const {
3982 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
3983}
3984
3985ui::Dataspace Layer::getRequestedDataSpace() const {
3986 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
3987}
3988
3989ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
3990 ui::Dataspace updatedDataspace = dataspace;
3991 // translate legacy dataspaces to modern dataspaces
3992 switch (dataspace) {
3993 case ui::Dataspace::SRGB:
3994 updatedDataspace = ui::Dataspace::V0_SRGB;
3995 break;
3996 case ui::Dataspace::SRGB_LINEAR:
3997 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
3998 break;
3999 case ui::Dataspace::JFIF:
4000 updatedDataspace = ui::Dataspace::V0_JFIF;
4001 break;
4002 case ui::Dataspace::BT601_625:
4003 updatedDataspace = ui::Dataspace::V0_BT601_625;
4004 break;
4005 case ui::Dataspace::BT601_525:
4006 updatedDataspace = ui::Dataspace::V0_BT601_525;
4007 break;
4008 case ui::Dataspace::BT709:
4009 updatedDataspace = ui::Dataspace::V0_BT709;
4010 break;
4011 default:
4012 break;
4013 }
4014
4015 return updatedDataspace;
4016}
4017
4018sp<GraphicBuffer> Layer::getBuffer() const {
4019 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4020}
4021
Patrick Williamsbb25f802022-08-30 23:02:34 +00004022void Layer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
4023 mTransformHint = getFixedTransformHint();
4024 if (mTransformHint == ui::Transform::ROT_INVALID) {
4025 mTransformHint = displayTransformHint;
4026 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004027 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004028}
4029
4030const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4031 return mBufferInfo.mBuffer;
4032}
4033
4034bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004035 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004036 return false;
4037 }
4038
4039 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004040 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004041 mDrawingState.modified = true;
4042 setTransactionFlags(eTransactionNeeded);
4043 return true;
4044}
4045
4046bool Layer::fillsColor() const {
4047 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4048 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4049}
4050
4051bool Layer::hasBlur() const {
4052 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4053}
4054
Vishnu Nairba354102022-08-01 00:14:18 +00004055void Layer::updateSnapshot(bool updateGeometry) {
4056 if (!getCompositionEngineLayerFE()) {
4057 return;
4058 }
4059
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004060 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004061 if (updateGeometry) {
4062 prepareBasicGeometryCompositionState();
4063 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004064 snapshot->roundedCorner = getRoundedCornerState();
4065 snapshot->stretchEffect = getStretchEffect();
4066 snapshot->transformedBounds = mScreenBounds;
4067 if (mEffectiveShadowRadius > 0.f) {
4068 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4069
4070 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4071 // it if transparent regions are present. This may not be necessary since shadows are
4072 // typically cast by layers without transparent regions.
4073 snapshot->shadowSettings.boundaries = mBounds;
4074
4075 const float casterAlpha = snapshot->alpha;
4076 const bool casterIsOpaque =
4077 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4078
4079 // If the casting layer is translucent, we need to fill in the shadow underneath the
4080 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4081 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4082 snapshot->shadowSettings.ambientColor *= casterAlpha;
4083 snapshot->shadowSettings.spotColor *= casterAlpha;
4084 }
4085 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004086 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004087 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004088 snapshot->layerOpaqueFlagSet =
4089 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004090 snapshot->isHdrY410 = isHdrY410();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004091 sp<Layer> p = mDrawingParent.promote();
4092 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004093 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004094 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004095 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004096 }
4097 snapshot->bufferSize = getBufferSize(mDrawingState);
4098 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004099 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004100 preparePerFrameCompositionState();
4101}
4102
Vishnu Naire14c6b32022-08-06 04:20:15 +00004103void Layer::updateChildrenSnapshots(bool updateGeometry) {
4104 for (const sp<Layer>& child : mDrawingChildren) {
4105 child->updateSnapshot(updateGeometry);
4106 child->updateChildrenSnapshots(updateGeometry);
4107 }
4108}
4109
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004110void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4111 mSnapshot->layerMetadata = parentMetadata;
4112 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4113 for (const sp<Layer>& child : mDrawingChildren) {
4114 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4115 }
4116}
4117
4118void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4119 std::unordered_set<Layer*>& visited) {
4120 if (visited.find(this) != visited.end()) {
4121 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4122 return;
4123 }
4124 visited.insert(this);
4125
4126 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4127
4128 if (mDrawingState.zOrderRelatives.empty()) {
4129 return;
4130 }
4131 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4132 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4133 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4134 sp<Layer> relative = weakRelative.promote();
4135 if (!relative) {
4136 continue;
4137 }
4138 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4139 }
4140}
4141
Chavi Weingarten328a8312023-01-26 21:17:52 +00004142bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004143 TrustedPresentationListener const& listener) {
4144 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4145 mTrustedPresentationListener = listener;
4146 mTrustedPresentationThresholds = thresholds;
4147 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4148 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4149 mFlinger->mNumTrustedPresentationListeners++;
4150 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4151 mFlinger->mNumTrustedPresentationListeners--;
4152 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004153
4154 // Reset trusted presentation states to ensure we start the time again.
4155 mEnteredTrustedPresentationStateTime = -1;
4156 mLastReportedTrustedPresentationState = false;
4157 mLastComputedTrustedPresentationState = false;
4158
4159 // If there's a new trusted presentation listener, the code needs to go through the composite
4160 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4161 // we're already in the requested state.
4162 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004163}
4164
Vishnu Naira156f482023-02-22 00:23:38 +00004165void Layer::updateLastLatchTime(nsecs_t latchTime) {
4166 mLastLatchTime = latchTime;
4167}
4168
Mathias Agopian13127d82013-03-05 17:47:11 -08004169// ---------------------------------------------------------------------------
4170
Marin Shalamanov46084422020-10-13 12:33:42 +02004171std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004172 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4173 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004174}
4175
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004176} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004177
4178#if defined(__gl_h_)
4179#error "don't include gl/gl.h in this file"
4180#endif
4181
4182#if defined(__gl2_h_)
4183#error "don't include gl2/gl2.h in this file"
4184#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004185
4186// TODO(b/129481165): remove the #pragma below and fix conversion issues
4187#pragma clang diagnostic pop // ignored "-Wconversion"