blob: d4660ff1323ce0f80402529ac93552801d0f9ec4 [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>
55#include <ui/GraphicBuffer.h>
56#include <ui/PixelFormat.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#include <utils/Errors.h>
58#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080059#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080061#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Alec Mourie60041e2019-06-14 18:59:51 -070063#include <algorithm>
64#include <mutex>
65#include <sstream>
66
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070067#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080068#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070069#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070070#include "FrameTracer/FrameTracer.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080071#include "LayerProtoHelper.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080073#include "TimeStats/TimeStats.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070074#include "TunnelModeEnabledReporter.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070075
David Sodman41fdfc92017-11-06 16:09:56 -080076#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000077#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079namespace android {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010080namespace {
81constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000082
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000083const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000084
Patrick Williamsbb25f802022-08-30 23:02:34 +000085bool assignTransform(ui::Transform* dst, ui::Transform& from) {
86 if (*dst == from) {
87 return false;
88 }
89 *dst = from;
90 return true;
91}
92
93TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
94 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
95 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
96 const auto frameRateCompatibility = [frameRate] {
97 switch (frameRate.type) {
98 case Layer::FrameRateCompatibility::Default:
99 return FrameRateCompatibility::Default;
100 case Layer::FrameRateCompatibility::ExactOrMultiple:
101 return FrameRateCompatibility::ExactOrMultiple;
102 default:
103 return FrameRateCompatibility::Undefined;
104 }
105 }();
106
107 const auto seamlessness = [frameRate] {
108 switch (frameRate.seamlessness) {
109 case scheduler::Seamlessness::OnlySeamless:
110 return Seamlessness::ShouldBeSeamless;
111 case scheduler::Seamlessness::SeamedAndSeamless:
112 return Seamlessness::NotRequired;
113 default:
114 return Seamlessness::Undefined;
115 }
116 }();
117
118 return TimeStats::SetFrameRateVote{.frameRate = frameRate.rate.getValue(),
119 .frameRateCompatibility = frameRateCompatibility,
120 .seamlessness = seamlessness};
121}
122
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100123} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800124
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700125using namespace ftl::flag_operators;
126
Yiwei Zhang5434a782018-12-05 18:06:32 -0800127using base::StringAppendF;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800128using gui::GameMode;
129using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500130using gui::WindowInfo;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800131
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700132using PresentState = frametimeline::SurfaceFrame::PresentState;
133
Lloyd Piquef1c675b2018-09-12 20:45:39 -0700134std::atomic<int32_t> Layer::sSequence{1};
Mathias Agopian13127d82013-03-05 17:47:11 -0800135
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700136Layer::Layer(const LayerCreationArgs& args)
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800137 : sequence(args.sequence.value_or(sSequence++)),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700138 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000139 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700140 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800141 mWindowType(static_cast<WindowInfo::Type>(
142 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000143 mLayerCreationFlags(args.flags),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000144 mBorderEnabled(false),
145 mTextureName(args.textureName),
Vishnu Naire14c6b32022-08-06 04:20:15 +0000146 mHwcSlotGenerator(sp<HwcSlotGenerator>::make()),
147 mLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000148 ALOGV("Creating Layer %s", getDebugName());
149
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700150 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700151 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
152 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
153 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700154 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
155 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Vishnu Naira84a2202022-01-12 20:12:55 -0800156 if (args.sequence) {
157 sSequence = *args.sequence + 1;
158 }
Robert Carr6a160312021-05-17 12:08:20 -0700159 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700160 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700161 mDrawingState.z = 0;
162 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700163 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700164 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700165 mDrawingState.transform.set(0, 0);
166 mDrawingState.frameNumber = 0;
167 mDrawingState.bufferTransform = 0;
168 mDrawingState.transformToDisplayInverse = false;
169 mDrawingState.crop.makeInvalid();
170 mDrawingState.acquireFence = sp<Fence>::make(-1);
171 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
172 mDrawingState.dataspace = ui::Dataspace::UNKNOWN;
Vishnu Nairbc4ee5c2022-08-16 03:19:37 +0000173 mDrawingState.dataspaceRequested = false;
Robert Carr6a160312021-05-17 12:08:20 -0700174 mDrawingState.hdrMetadata.validTypes = 0;
175 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
176 mDrawingState.cornerRadius = 0.0f;
177 mDrawingState.backgroundBlurRadius = 0;
178 mDrawingState.api = -1;
179 mDrawingState.hasColorTransform = false;
180 mDrawingState.colorSpaceAgnostic = false;
181 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
182 mDrawingState.metadata = args.metadata;
183 mDrawingState.shadowRadius = 0.f;
184 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
185 mDrawingState.frameTimelineInfo = {};
186 mDrawingState.postTime = -1;
187 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000188 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700189 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700190 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000191 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700192
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700193 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
194 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700195 mDrawingState.color.r = -1.0_hf;
196 mDrawingState.color.g = -1.0_hf;
197 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700198 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700199
200 mFrameTracker.setDisplayRefreshPeriod(
201 args.flinger->mScheduler->getVsyncPeriodFromRefreshRateConfigs());
Robert Carr2e102c92018-10-23 12:11:15 -0700202
Vishnu Nair0f085c62019-08-30 08:49:12 -0700203 mCallingPid = args.callingPid;
204 mCallingUid = args.callingUid;
chaviw250bcbb2020-08-05 11:17:54 -0700205
206 if (mCallingUid == AID_GRAPHICS || mCallingUid == AID_SYSTEM) {
207 // If the system didn't send an ownerUid, use the callingUid for the ownerUid.
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800208 mOwnerUid = args.metadata.getInt32(gui::METADATA_OWNER_UID, mCallingUid);
209 mOwnerPid = args.metadata.getInt32(gui::METADATA_OWNER_PID, mCallingPid);
chaviw250bcbb2020-08-05 11:17:54 -0700210 } else {
211 // A create layer request from a non system request cannot specify the owner uid
212 mOwnerUid = mCallingUid;
Adithya Srinivasan9febda82020-10-19 10:49:41 -0700213 mOwnerPid = mCallingPid;
chaviw250bcbb2020-08-05 11:17:54 -0700214 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000215
216 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
217 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
218 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
219 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000220
221 mSnapshot->sequence = sequence;
222 mSnapshot->name = getDebugName();
223 mSnapshot->textureName = mTextureName;
224 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
225 mSnapshot->transform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800226}
227
228void Layer::onFirstRef() {
229 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700230}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700231
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700232Layer::~Layer() {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000233 // The original layer and the clone layer share the same texture and buffer. Therefore, only
234 // one of the layers, in this case the original layer, needs to handle the deletion. The
235 // original layer and the clone should be removed at the same time so there shouldn't be any
236 // issue with the clone layer trying to use the texture.
237 if (mBufferInfo.mBuffer != nullptr) {
238 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
239 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
240 mBufferInfo.mFence,
241 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
242 mOwnerUid));
243 }
244 if (!isClone()) {
245 // The original layer and the clone layer share the same texture. Therefore, only one of
246 // the layers, in this case the original layer, needs to handle the deletion. The original
247 // layer and the clone should be removed at the same time so there shouldn't be any issue
248 // with the clone layer trying to use the deleted texture.
249 mFlinger->deleteTextureAsync(mTextureName);
250 }
251 const int32_t layerId = getSequence();
252 mFlinger->mTimeStats->onDestroy(layerId);
253 mFlinger->mFrameTracer->onDestroy(layerId);
254
David Sodman577c8962017-12-08 14:50:53 -0800255 sp<Client> c(mClientRef.promote());
256 if (c != 0) {
257 c->detachLayer(this);
258 }
259
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000260 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700261 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700262
263 if (mDrawingState.sidebandStream != nullptr) {
264 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
265 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700266 if (mHadClonedChild) {
267 mFlinger->mNumClones--;
268 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700269}
270
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700271LayerCreationArgs::LayerCreationArgs(SurfaceFlinger* flinger, sp<Client> client, std::string name,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800272 uint32_t flags, LayerMetadata metadata)
Vishnu Nair0f085c62019-08-30 08:49:12 -0700273 : flinger(flinger),
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700274 client(std::move(client)),
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700275 name(std::move(name)),
Vishnu Nair0f085c62019-08-30 08:49:12 -0700276 flags(flags),
277 metadata(std::move(metadata)) {
278 IPCThreadState* ipc = IPCThreadState::self();
279 callingPid = ipc->getCallingPid();
280 callingUid = ipc->getCallingUid();
281}
282
Mathias Agopian13127d82013-03-05 17:47:11 -0800283// ---------------------------------------------------------------------------
284// callbacks
285// ---------------------------------------------------------------------------
286
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700287void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700288 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700289 return;
290 }
Robert Carr2e102c92018-10-23 12:11:15 -0700291
Robert Carr6a160312021-05-17 12:08:20 -0700292 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700293 if (strongRelative == nullptr) {
294 setZOrderRelativeOf(nullptr);
295 return;
296 }
297
298 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700299 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700300 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800301 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700302 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700303}
304
305void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700306 if (!mRemovedFromDrawingState) {
307 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700308 mFlinger->mScheduler->deregisterLayer(this);
309 }
Rob Carr4bba3702018-10-08 21:53:30 +0000310
Ady Abrahamd11bade2022-08-01 16:18:03 -0700311 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700312}
Chia-I Wu38512252017-05-17 14:36:16 -0700313
chaviw68d4dab2020-06-08 15:07:32 -0700314sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000315 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700316 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700317 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700318 }
319 return parent->getRootLayer();
320}
321
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700322void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700323 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
324 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700325 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700326
327 traverse(LayerVector::StateSet::Current, [&](Layer* layer) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700328 layer->removeFromCurrentState();
329 layer->removeRelativeZ(layersInTree);
chaviw68d4dab2020-06-08 15:07:32 -0700330 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700331}
332
chaviw61626f22018-11-15 16:26:27 -0800333void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700334 if (mRemovedFromDrawingState) {
335 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700336 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700337 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700338 }
chaviw61626f22018-11-15 16:26:27 -0800339
340 for (const auto& child : mCurrentChildren) {
341 child->addToCurrentState();
342 }
343}
344
Mathias Agopian13127d82013-03-05 17:47:11 -0800345// ---------------------------------------------------------------------------
346// set-up
347// ---------------------------------------------------------------------------
348
chaviw13fdc492017-06-27 12:40:18 -0700349bool Layer::getPremultipledAlpha() const {
350 return mPremultipliedAlpha;
351}
352
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700353sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800354 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700355 if (mGetHandleCalled) {
356 ALOGE("Get handle called twice" );
357 return nullptr;
358 }
359 mGetHandleCalled = true;
Ady Abrahamd11bade2022-08-01 16:18:03 -0700360 return sp<Handle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800361}
362
363// ---------------------------------------------------------------------------
364// h/w composer set-up
365// ---------------------------------------------------------------------------
366
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700367static Rect reduce(const Rect& win, const Region& exclude) {
368 if (CC_LIKELY(exclude.isEmpty())) {
369 return win;
370 }
371 if (exclude.isRect()) {
372 return win.reduce(exclude.getBounds());
373 }
374 return Region(win).subtract(exclude).getBounds();
375}
376
Dan Stoza80d61162017-12-20 15:57:52 -0800377static FloatRect reduce(const FloatRect& win, const Region& exclude) {
378 if (CC_LIKELY(exclude.isEmpty())) {
379 return win;
380 }
381 // Convert through Rect (by rounding) for lack of FloatRegion
382 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
383}
384
Vishnu Nair4351ad52019-02-11 14:13:02 -0800385Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800386 if (!reduceTransparentRegion) {
387 return Rect{mScreenBounds};
388 }
389
390 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800391 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800392 // Transform to screen space.
393 bounds = t.transform(bounds);
394 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700395}
396
Vishnu Nair4351ad52019-02-11 14:13:02 -0800397FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000398 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800399 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700400}
401
Vishnu Nairf0c28512019-02-08 12:40:28 -0800402FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
403 // Subtract the transparent region and snap to the bounds.
404 return reduce(mBounds, activeTransparentRegion);
405}
406
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700407void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
408 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800409 const State& s(getDrawingState());
410
411 // Calculate effective layer transform
412 mEffectiveTransform = parentTransform * getActiveTransform(s);
413
Garfield Tan2c1782c2022-02-16 15:25:05 -0800414 if (CC_UNLIKELY(!isTransformValid())) {
415 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
416 getDebugName());
417 return;
418 }
419
Vishnu Nair4351ad52019-02-11 14:13:02 -0800420 // Transform parent bounds to layer space
421 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
422
Vishnu Nairc652ff82019-03-15 12:48:54 -0700423 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800424 mSourceBounds = computeSourceBounds(parentBounds);
425
426 // Calculate bounds by croping diplay frame with layer crop and parent bounds
427 FloatRect bounds = mSourceBounds;
428 const Rect layerCrop = getCrop(s);
429 if (!layerCrop.isEmpty()) {
430 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
431 }
432 bounds = bounds.intersect(parentBounds);
433
434 mBounds = bounds;
435 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700436
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700437 // Use the layer's own shadow radius if set. Otherwise get the radius from
438 // parent.
439 if (s.shadowRadius > 0.f) {
440 mEffectiveShadowRadius = s.shadowRadius;
441 } else {
442 mEffectiveShadowRadius = parentShadowRadius;
443 }
444
445 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
446 // don't pass it to its children.
447 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
448
Vishnu Nair4351ad52019-02-11 14:13:02 -0800449 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700450 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800451 }
Vishnu Nairba354102022-08-01 00:14:18 +0000452
453 if (mPotentialCursor) {
454 prepareCursorCompositionState();
455 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800456}
457
Vishnu Nair60356342018-11-13 13:00:45 -0800458Rect Layer::getCroppedBufferSize(const State& s) const {
459 Rect size = getBufferSize(s);
460 Rect crop = getCrop(s);
461 if (!crop.isEmpty() && size.isValid()) {
462 size.intersect(crop, &size);
463 } else if (!crop.isEmpty()) {
464 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700465 }
Vishnu Nair60356342018-11-13 13:00:45 -0800466 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800467}
468
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700469void Layer::setupRoundedCornersCropCoordinates(Rect win,
470 const FloatRect& roundedCornersCrop) const {
471 // Translate win by the rounded corners rect coordinates, to have all values in
472 // layer coordinate space.
473 win.left -= roundedCornersCrop.left;
474 win.right -= roundedCornersCrop.left;
475 win.top -= roundedCornersCrop.top;
476 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700477}
478
Lloyd Piquede196652020-01-22 17:29:58 -0800479void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800480 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800481 const auto alpha = static_cast<float>(getAlpha());
482 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700483 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800484
485 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
486 if (!opaque || alpha != 1.0f) {
487 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
488 : Hwc2::IComposerClient::BlendMode::COVERAGE;
489 }
490
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000491 auto* snapshot = editLayerSnapshot();
492 snapshot->outputFilter = getOutputFilter();
493 snapshot->isVisible = isVisible();
494 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
495 snapshot->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800496
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000497 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800498 contentDirty = false;
499
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000500 snapshot->geomLayerBounds = mBounds;
501 snapshot->geomLayerTransform = getTransform();
502 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
503 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Lloyd Piquec6687342019-03-07 21:34:57 -0800504
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000505 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
506 snapshot->alpha = alpha;
507 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
508 snapshot->blurRegions = drawingState.blurRegions;
509 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800510}
511
Lloyd Piquede196652020-01-22 17:29:58 -0800512void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800513 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000514 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700515
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000516 snapshot->geomBufferSize = getBufferSize(drawingState);
517 snapshot->geomContentCrop = getBufferCrop();
518 snapshot->geomCrop = getCrop(drawingState);
519 snapshot->geomBufferTransform = getBufferTransform();
520 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
521 snapshot->geomUsesSourceCrop = usesSourceCrop();
522 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800523
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000524 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800525 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
526 for (const auto& [key, mandatory] : supportedMetadata) {
527 const auto& genericLayerMetadataCompatibilityMap =
528 mFlinger->getGenericLayerMetadataKeyMap();
529 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
530 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
531 continue;
532 }
533 const uint32_t id = compatIter->second;
534
535 auto it = drawingState.metadata.mMap.find(id);
536 if (it == std::end(drawingState.metadata.mMap)) {
537 continue;
538 }
539
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000540 snapshot->metadata.emplace(key,
541 compositionengine::GenericLayerMetadataEntry{mandatory,
542 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800543 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800544}
David Sodmanba340492018-08-05 21:51:33 -0700545
Lloyd Piquede196652020-01-22 17:29:58 -0800546void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800547 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000548 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800549
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000550 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800551
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000552 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
553 snapshot->dataspace = getDataSpace();
554 snapshot->colorTransform = getColorTransform();
555 snapshot->colorTransformIsIdentity = !hasColorTransform();
556 snapshot->surfaceDamage = surfaceDamageRegion;
557 snapshot->hasProtectedContent = isProtected();
558 snapshot->dimmingEnabled = isDimmingEnabled();
Lloyd Pique688abd42019-02-15 15:42:24 -0800559
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700560 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700561
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000562 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800563
564 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400565 // Rounded corners no longer force client composition, since we may use a
566 // hole punch so that the layer will appear to have rounded corners.
567 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000568 snapshot->stretchEffect.hasEffect()) {
569 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800570 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700571 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000572 snapshot->blurRegions = drawingState.blurRegions;
573 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400574
575 // Layer framerate is used in caching decisions.
576 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
577 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000578 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000579
580 if (hasBufferOrSidebandStream()) {
581 preparePerFrameBufferCompositionState();
582 } else {
583 preparePerFrameEffectsCompositionState();
584 }
585}
586
587void Layer::preparePerFrameBufferCompositionState() {
588 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000589 auto* snapshot = editLayerSnapshot();
590 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
591 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000592 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
593 return;
594 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000595 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000596 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
597 } else {
598 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000599 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
600 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000601 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
602 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
603 }
604
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000605 snapshot->buffer = getBuffer();
606 snapshot->bufferSlot = (mBufferInfo.mBufferSlot == BufferQueue::INVALID_BUFFER_SLOT)
Patrick Williamsbb25f802022-08-30 23:02:34 +0000607 ? 0
608 : mBufferInfo.mBufferSlot;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000609 snapshot->acquireFence = mBufferInfo.mFence;
610 snapshot->frameNumber = mBufferInfo.mFrameNumber;
611 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000612}
613
614void Layer::preparePerFrameEffectsCompositionState() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000615 auto* snapshot = editLayerSnapshot();
616 snapshot->color = getColor();
617 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000618 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800619}
620
Lloyd Piquede196652020-01-22 17:29:58 -0800621void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800622 const State& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000623 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800624
625 // Apply the layer's transform, followed by the display's global transform
626 // Here we're guaranteed that the layer's transform preserves rects
627 Rect win = getCroppedBufferSize(drawingState);
628 // Subtract the transparent region and snap to the bounds
629 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
630 Rect frame(getTransform().transform(bounds));
631
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000632 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800633}
634
Lloyd Piquea83776c2019-01-29 18:42:32 -0800635const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700636 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800637}
638
Mathias Agopian13127d82013-03-05 17:47:11 -0800639// ---------------------------------------------------------------------------
640// drawing...
641// ---------------------------------------------------------------------------
642
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500643aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
644 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700645 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800646 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500647 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800648 }
649 if (outputLayer->getState().hwc) {
650 return (*outputLayer->getState().hwc).hwcCompositionType;
651 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500652 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800653 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800654}
655
Mathias Agopian13127d82013-03-05 17:47:11 -0800656// ----------------------------------------------------------------------------
657// local state
658// ----------------------------------------------------------------------------
659
David Sodman41fdfc92017-11-06 16:09:56 -0800660bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800661 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700662 if (s.flags & layer_state_t::eLayerSecure) {
663 return true;
664 }
665
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000666 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700667 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700668}
669
Mathias Agopian13127d82013-03-05 17:47:11 -0800670// ----------------------------------------------------------------------------
671// transaction
672// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800673
Marissa Wall61c58622018-07-18 10:12:20 -0700674uint32_t Layer::doTransaction(uint32_t flags) {
675 ATRACE_CALL();
676
Robert Carr0758e5d2021-03-11 22:15:04 -0800677 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700678 mDrawingStateModified = mDrawingState.modified;
679 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700680
Alec Mourib416efd2018-09-06 21:01:59 +0000681 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700682
Robert Carr6a160312021-05-17 12:08:20 -0700683 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800684 // invalidate and recompute the visible regions if needed
685 flags |= Layer::eVisibleRegion;
686 }
687
Robert Carr6a160312021-05-17 12:08:20 -0700688 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800689 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000690 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800691 flags |= eVisibleRegion;
692 this->contentDirty = true;
693
694 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700695 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800696 }
697
Arthur Hung9ed43392022-05-27 06:31:57 +0000698 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
699 mFlinger->mUpdateInputInfo = true;
700 }
701
Robert Carr6a160312021-05-17 12:08:20 -0700702 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800703
Mathias Agopian13127d82013-03-05 17:47:11 -0800704 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800705}
706
Robert Carr6a160312021-05-17 12:08:20 -0700707void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000708 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
709 // bufferSurfaceFrameTX will be presented in latchBuffer.
710 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
711 if (surfaceFrame->getPresentState() != PresentState::Presented) {
712 // With applyPendingStates, we could end up having presented surfaceframes from previous
713 // states
714 surfaceFrame->setPresentState(PresentState::Presented);
715 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
716 }
717 }
Robert Carr6a160312021-05-17 12:08:20 -0700718 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700719}
720
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700721uint32_t Layer::clearTransactionFlags(uint32_t mask) {
722 const auto flags = mTransactionFlags & mask;
723 mTransactionFlags &= ~mask;
724 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800725}
726
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700727void Layer::setTransactionFlags(uint32_t mask) {
728 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800729}
730
Robert Carr1f0a16a2016-10-24 16:27:39 -0700731bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
732 ssize_t idx = mCurrentChildren.indexOf(childLayer);
733 if (idx < 0) {
734 return false;
735 }
736 if (childLayer->setLayer(z)) {
737 mCurrentChildren.removeAt(idx);
738 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800739 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700740 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800741 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700742}
743
Robert Carr503c7042017-09-27 15:06:08 -0700744bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
745 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
746 ssize_t idx = mCurrentChildren.indexOf(childLayer);
747 if (idx < 0) {
748 return false;
749 }
750 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
751 mCurrentChildren.removeAt(idx);
752 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800753 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700754 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800755 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700756}
757
Robert Carrae060832016-11-28 10:51:00 -0800758bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700759 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
760 mDrawingState.sequence++;
761 mDrawingState.z = z;
762 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700763
Robert Carra70e91c2021-06-11 13:59:52 -0700764 mFlinger->mSomeChildrenChanged = true;
765
Robert Carrdb66e622017-04-10 16:55:57 -0700766 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700767 if (mDrawingState.zOrderRelativeOf != nullptr) {
768 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700769 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700770 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700771 }
chaviw606e5cf2019-03-01 10:12:10 -0800772 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700773 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800774 setTransactionFlags(eTransactionNeeded);
775 return true;
776}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700777
Robert Carrdb66e622017-04-10 16:55:57 -0700778void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700779 mDrawingState.zOrderRelatives.remove(relative);
780 mDrawingState.sequence++;
781 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700782 setTransactionFlags(eTransactionNeeded);
783}
784
785void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700786 mDrawingState.zOrderRelatives.add(relative);
787 mDrawingState.modified = true;
788 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700789 setTransactionFlags(eTransactionNeeded);
790}
791
chaviw606e5cf2019-03-01 10:12:10 -0800792void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700793 mDrawingState.zOrderRelativeOf = relativeOf;
794 mDrawingState.sequence++;
795 mDrawingState.modified = true;
796 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700797
chaviw606e5cf2019-03-01 10:12:10 -0800798 setTransactionFlags(eTransactionNeeded);
799}
800
Robert Carr503d2bd2017-12-04 15:49:47 -0800801bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nairf9096652021-07-20 18:49:42 -0700802 sp<Layer> relative = fromHandle(relativeToHandle).promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700803 if (relative == nullptr) {
804 return false;
805 }
806
Robert Carr6a160312021-05-17 12:08:20 -0700807 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
808 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800809 return false;
810 }
811
Robert Carr88b85e12022-03-21 15:47:35 -0700812 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
813 (relative->mDrawingState.zOrderRelativeOf == this)) {
814 ALOGE("Detected relative layer loop between %s and %s",
815 mName.c_str(), relative->mName.c_str());
816 ALOGE("Ignoring new call to set relative layer");
817 return false;
818 }
819
Robert Carra70e91c2021-06-11 13:59:52 -0700820 mFlinger->mSomeChildrenChanged = true;
821
Robert Carr6a160312021-05-17 12:08:20 -0700822 mDrawingState.sequence++;
823 mDrawingState.modified = true;
824 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700825
Robert Carr6a160312021-05-17 12:08:20 -0700826 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700827 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700828 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700829 }
chaviw606e5cf2019-03-01 10:12:10 -0800830 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700831 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700832
833 setTransactionFlags(eTransactionNeeded);
834
835 return true;
836}
837
Winson Chunga30f7c92021-06-29 15:42:56 -0700838bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
839 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
840 mDrawingState.isTrustedOverlay = isTrustedOverlay;
841 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000842 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700843 setTransactionFlags(eTransactionNeeded);
844 return true;
845}
846
847bool Layer::isTrustedOverlay() const {
848 if (getDrawingState().isTrustedOverlay) {
849 return true;
850 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000851 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700852 return (p != nullptr) && p->isTrustedOverlay();
853}
854
Dan Stoza9e56aa02015-11-02 13:00:03 -0800855bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700856 if (mDrawingState.color.a == alpha) return false;
857 mDrawingState.sequence++;
858 mDrawingState.color.a = alpha;
859 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800860 setTransactionFlags(eTransactionNeeded);
861 return true;
862}
chaviw13fdc492017-06-27 12:40:18 -0700863
Valerie Haudd0b7572019-01-29 14:59:27 -0800864bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700865 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700866 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800867 }
Robert Carr6a160312021-05-17 12:08:20 -0700868 mDrawingState.sequence++;
869 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800870 setTransactionFlags(eTransactionNeeded);
871
Robert Carr6a160312021-05-17 12:08:20 -0700872 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -0800873 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -0800874 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700875 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -0700876 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800877 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700878 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -0700879
Valerie Haudd0b7572019-01-29 14:59:27 -0800880 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -0700881 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -0800882 mFlinger->mLayersAdded = true;
883 // set up SF to handle added color layer
884 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -0700885 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -0800886 }
887 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -0700888 } else if (mDrawingState.bgColorLayer && alpha == 0) {
889 mDrawingState.bgColorLayer->reparent(nullptr);
890 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -0800891 return true;
892 }
893
Robert Carr6a160312021-05-17 12:08:20 -0700894 mDrawingState.bgColorLayer->setColor(color);
895 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
896 mDrawingState.bgColorLayer->setAlpha(alpha);
897 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -0800898
chaviw13fdc492017-06-27 12:40:18 -0700899 return true;
900}
901
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700902bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -0700903 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700904
Robert Carr6a160312021-05-17 12:08:20 -0700905 mDrawingState.sequence++;
906 mDrawingState.cornerRadius = cornerRadius;
907 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700908 setTransactionFlags(eTransactionNeeded);
909 return true;
910}
911
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800912bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -0700913 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -0700914 // If we start or stop drawing blur then the layer's visibility state may change so increment
915 // the magic sequence number.
916 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
917 mDrawingState.sequence++;
918 }
Robert Carr6a160312021-05-17 12:08:20 -0700919 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
920 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800921 setTransactionFlags(eTransactionNeeded);
922 return true;
923}
Marissa Wall61c58622018-07-18 10:12:20 -0700924
Mathias Agopian13127d82013-03-05 17:47:11 -0800925bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +0000926 mDrawingState.sequence++;
927 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -0700928 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800929 setTransactionFlags(eTransactionNeeded);
930 return true;
931}
Ana Krulecc84d09b2019-11-02 23:10:29 +0100932
Lucas Dupinc3800b82020-10-02 16:24:48 -0700933bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -0700934 // If we start or stop drawing blur then the layer's visibility state may change so increment
935 // the magic sequence number.
936 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
937 mDrawingState.sequence++;
938 }
Robert Carr6a160312021-05-17 12:08:20 -0700939 mDrawingState.blurRegions = blurRegions;
940 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -0700941 setTransactionFlags(eTransactionNeeded);
942 return true;
943}
944
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800945bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -0700946 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
947 if (mDrawingState.flags == newFlags) return false;
948 mDrawingState.sequence++;
949 mDrawingState.flags = newFlags;
950 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800951 setTransactionFlags(eTransactionNeeded);
952 return true;
953}
Robert Carr99e27f02016-06-16 15:18:02 -0700954
chaviw25714502021-02-11 10:01:08 -0800955bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +0000956 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -0700957 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -0700958 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -0700959
Robert Carr6a160312021-05-17 12:08:20 -0700960 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800961 setTransactionFlags(eTransactionNeeded);
962 return true;
963}
Robert Carr8d5227b2017-03-16 15:41:03 -0700964
Evan Roskyef876c92019-01-25 17:46:06 -0800965bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -0700966 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
967 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -0800968 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -0800969 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500970}
971
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700972bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -0700973 if (mDrawingState.layerStack == layerStack) return false;
974 mDrawingState.sequence++;
975 mDrawingState.layerStack = layerStack;
976 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800977 setTransactionFlags(eTransactionNeeded);
978 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700979}
980
Peiyong Linc502cb72019-03-01 15:00:23 -0800981bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -0700982 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -0800983 return false;
984 }
Robert Carr6a160312021-05-17 12:08:20 -0700985 mDrawingState.sequence++;
986 mDrawingState.colorSpaceAgnostic = agnostic;
987 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -0800988 setTransactionFlags(eTransactionNeeded);
989 return true;
990}
991
Sally Qi81d95e62022-03-21 19:41:33 -0700992bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
993 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
994
995 mDrawingState.sequence++;
996 mDrawingState.dimmingEnabled = dimmingEnabled;
997 mDrawingState.modified = true;
998 setTransactionFlags(eTransactionNeeded);
999 return true;
1000}
1001
Ana Krulecc84d09b2019-11-02 23:10:29 +01001002bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001003 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1004 mDrawingState.frameRateSelectionPriority = priority;
1005 mDrawingState.sequence++;
1006 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001007 setTransactionFlags(eTransactionNeeded);
1008 return true;
1009}
1010
1011int32_t Layer::getFrameRateSelectionPriority() const {
1012 // Check if layer has priority set.
1013 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1014 return mDrawingState.frameRateSelectionPriority;
1015 }
1016 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001017 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001018 if (parent != nullptr) {
1019 return parent->getFrameRateSelectionPriority();
1020 }
1021
1022 return Layer::PRIORITY_UNSET;
1023}
1024
Andy Labrada096227e2022-06-15 16:58:11 +00001025bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1026 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1027 mDrawingState.defaultFrameRateCompatibility = compatibility;
1028 mDrawingState.modified = true;
1029 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1030 setTransactionFlags(eTransactionNeeded);
1031 return true;
1032}
1033
1034scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1035 return mDrawingState.defaultFrameRateCompatibility;
1036}
1037
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001038bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1039 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1040};
1041
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001042ui::LayerStack Layer::getLayerStack() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001043 if (const auto parent = mDrawingParent.promote()) {
1044 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001045 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001046 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001047}
1048
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001049bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001050 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001051 return false;
1052 }
1053
Robert Carr6a160312021-05-17 12:08:20 -07001054 mDrawingState.sequence++;
1055 mDrawingState.shadowRadius = shadowRadius;
1056 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001057 setTransactionFlags(eTransactionNeeded);
1058 return true;
1059}
1060
Vishnu Nair6213bd92020-05-08 17:42:25 -07001061bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001062 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001063 return false;
1064 }
1065
Robert Carr6a160312021-05-17 12:08:20 -07001066 mDrawingState.sequence++;
1067 mDrawingState.fixedTransformHint = fixedTransformHint;
1068 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001069 setTransactionFlags(eTransactionNeeded);
1070 return true;
1071}
1072
John Reckcdb4ed72021-02-04 13:39:33 -05001073bool Layer::setStretchEffect(const StretchEffect& effect) {
1074 StretchEffect temp = effect;
1075 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001076 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001077 return false;
1078 }
Robert Carr6a160312021-05-17 12:08:20 -07001079 mDrawingState.sequence++;
1080 mDrawingState.stretchEffect = temp;
1081 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001082 setTransactionFlags(eTransactionNeeded);
1083 return true;
1084}
1085
John Reckc00c6692021-02-16 11:37:33 -05001086StretchEffect Layer::getStretchEffect() const {
1087 if (mDrawingState.stretchEffect.hasEffect()) {
1088 return mDrawingState.stretchEffect;
1089 }
1090
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001091 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001092 if (parent != nullptr) {
1093 auto effect = parent->getStretchEffect();
1094 if (effect.hasEffect()) {
1095 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1096 return effect;
1097 }
1098 }
1099 return StretchEffect{};
1100}
1101
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001102bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1103 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001104 return false;
1105 }
1106 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001107 mBorderWidth = width;
1108 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001109 return true;
1110}
1111
1112bool Layer::isBorderEnabled() {
1113 return mBorderEnabled;
1114}
1115
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001116float Layer::getBorderWidth() {
1117 return mBorderWidth;
1118}
1119
1120const half4& Layer::getBorderColor() {
1121 return mBorderColor;
1122}
1123
Ady Abrahama850c182021-08-04 13:04:37 -07001124bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1125 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1126 const auto frameRate = [&] {
1127 if (mDrawingState.frameRate.rate.isValid() ||
1128 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1129 return mDrawingState.frameRate;
1130 }
1131
1132 return parentFrameRate;
1133 }();
1134
1135 *transactionNeeded |= setFrameRateForLayerTree(frameRate);
1136
1137 // The frame rate is propagated to the children
1138 bool childrenHaveFrameRate = false;
1139 for (const sp<Layer>& child : mCurrentChildren) {
1140 childrenHaveFrameRate |=
1141 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1142 }
1143
1144 // If we don't have a valid frame rate, but the children do, we set this
1145 // layer as NoVote to allow the children to control the refresh rate
1146 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1147 childrenHaveFrameRate) {
1148 *transactionNeeded |=
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001149 setFrameRateForLayerTree(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001150 }
1151
1152 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1153 // the same reason we are allowing touch boost for those layers. See
1154 // RefreshRateConfigs::getBestRefreshRate for more details.
1155 const auto layerVotedWithDefaultCompatibility =
1156 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1157 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1158 const auto layerVotedWithExactCompatibility =
1159 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1160 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1161 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1162}
1163
Ady Abraham60e42ea2020-03-09 19:17:31 -07001164void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001165 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001166 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001167 while (auto parent = layer->getParent()) {
1168 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001169 }
Ady Abrahama850c182021-08-04 13:04:37 -07001170 return layer;
1171 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001172
Ady Abraham60e42ea2020-03-09 19:17:31 -07001173 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001174 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001175
Ady Abrahama850c182021-08-04 13:04:37 -07001176 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001177 if (transactionNeeded) {
1178 mFlinger->setTransactionFlags(eTraversalNeeded);
1179 }
1180}
1181
Ady Abraham71c437d2020-01-31 15:56:57 -08001182bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001183 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001184 return false;
1185 }
1186
Robert Carr6a160312021-05-17 12:08:20 -07001187 mDrawingState.sequence++;
1188 mDrawingState.frameRate = frameRate;
1189 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001190
1191 updateTreeHasFrameRateVote();
1192
Steven Thomas3172e202020-01-06 19:25:30 -08001193 setTransactionFlags(eTransactionNeeded);
1194 return true;
1195}
1196
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001197void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1198 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001199 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001200
1201 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1202 // there are two transactions with the same token, the first one without a buffer and the
1203 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1204 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001205 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1206 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001207 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001208 mDrawingState.bufferSurfaceFrameTX = it->second;
1209 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1210 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1211 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001212 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001213 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001214 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1215 }
1216}
1217
1218void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1219 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001220 mDrawingState.frameTimelineInfo = info;
1221 mDrawingState.postTime = postTime;
1222 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001223 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001224
Robert Carr6a160312021-05-17 12:08:20 -07001225 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001226 bufferSurfaceFrameTX != nullptr) {
1227 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1228 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1229 // being used for BufferSurfaceFrame, don't create a new one.
1230 return;
1231 }
1232 }
1233 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1234 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1235 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001236 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1237 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001238 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001239 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001240 } else {
1241 if (it->second->getPresentState() == PresentState::Presented) {
1242 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1243 // have been from previous vsync.
1244 it->second = createSurfaceFrameForTransaction(info, postTime);
1245 }
1246 }
1247}
1248
1249void Layer::addSurfaceFrameDroppedForBuffer(
1250 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001251 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001252 surfaceFrame->setPresentState(PresentState::Dropped);
1253 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1254}
1255
1256void Layer::addSurfaceFramePresentedForBuffer(
1257 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1258 nsecs_t currentLatchTime) {
1259 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1260 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1261 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1262 mLastLatchTime = currentLatchTime;
1263}
1264
1265std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1266 const FrameTimelineInfo& info, nsecs_t postTime) {
1267 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001268 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1269 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001270 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001271 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001272 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001273 // For Transactions, the post time is considered to be both queue and acquire fence time.
1274 surfaceFrame->setActualQueueTime(postTime);
1275 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001276 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1277 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001278 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001279 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001280 onSurfaceFrameCreated(surfaceFrame);
1281 return surfaceFrame;
1282}
1283
1284std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1285 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1286 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001287 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001288 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001289 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001290 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001291 // For buffers, acquire fence time will set during latch.
1292 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001293 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1294 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001295 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001296 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001297 onSurfaceFrameCreated(surfaceFrame);
1298 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001299}
1300
Ady Abrahama850c182021-08-04 13:04:37 -07001301bool Layer::setFrameRateForLayerTree(FrameRate frameRate) {
1302 if (mDrawingState.frameRateForLayerTree == frameRate) {
1303 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001304 }
1305
Ady Abrahama850c182021-08-04 13:04:37 -07001306 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001307
Ady Abrahama850c182021-08-04 13:04:37 -07001308 // TODO(b/195668952): we probably don't need to dirty visible regions here
1309 // or even store frameRateForLayerTree in mDrawingState
1310 mDrawingState.sequence++;
1311 mDrawingState.modified = true;
1312 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001313
Dominik Laskowski068173d2021-08-11 17:22:59 -07001314 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
1315 mFlinger->mScheduler->recordLayerHistory(this, systemTime(), LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001316
1317 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001318}
1319
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001320Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1321 return getDrawingState().frameRateForLayerTree;
1322}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001323
Robert Carr1f0a16a2016-10-24 16:27:39 -07001324bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001325 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001326 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001327 if (parent != nullptr && parent->isHiddenByPolicy()) {
1328 return true;
1329 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001330 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1331 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1332 if (zOrderRelativeOf != nullptr) {
1333 if (zOrderRelativeOf->isHiddenByPolicy()) {
1334 return true;
1335 }
1336 }
1337 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001338 if (CC_UNLIKELY(!isTransformValid())) {
1339 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1340 return true;
1341 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001342 return s.flags & layer_state_t::eLayerHidden;
1343}
1344
David Sodman41fdfc92017-11-06 16:09:56 -08001345uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001346 // TODO: should we do something special if mSecure is set?
1347 if (mProtectedByApp) {
1348 // need a hardware-protected path to external video sink
1349 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001350 }
Riley Andrews03414a12014-07-01 14:22:59 -07001351 if (mPotentialCursor) {
1352 usage |= GraphicBuffer::USAGE_CURSOR;
1353 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001354 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001355 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001356}
1357
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001358void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1359 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1360 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001361 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001362
Vishnu Nair6213bd92020-05-08 17:42:25 -07001363 setTransformHint(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001364}
1365
Mathias Agopian13127d82013-03-05 17:47:11 -08001366// ----------------------------------------------------------------------------
1367// debugging
1368// ----------------------------------------------------------------------------
1369
Marissa Wall61c58622018-07-18 10:12:20 -07001370// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001371gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001372 using namespace std::string_literals;
1373
Huihong Luo05539a12022-02-23 10:29:40 -08001374 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001375 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001376 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001377 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001378 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001379 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001380
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001381 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001382 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001383 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001384 info.mX = ds.transform.tx();
1385 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001386 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001387 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001388 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001389 info.mFlags = ds.flags;
1390 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001391 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001392 info.mMatrix[0][0] = ds.transform[0][0];
1393 info.mMatrix[0][1] = ds.transform[0][1];
1394 info.mMatrix[1][0] = ds.transform[1][0];
1395 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001396 {
chaviwd62d3062019-09-04 14:48:02 -07001397 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001398 if (buffer != 0) {
1399 info.mActiveBufferWidth = buffer->getWidth();
1400 info.mActiveBufferHeight = buffer->getHeight();
1401 info.mActiveBufferStride = buffer->getStride();
1402 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001403 } else {
1404 info.mActiveBufferWidth = 0;
1405 info.mActiveBufferHeight = 0;
1406 info.mActiveBufferStride = 0;
1407 info.mActiveBufferFormat = 0;
1408 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001409 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001410 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001411 info.mIsOpaque = isOpaque(ds);
1412 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001413 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001414 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001415}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001416
Yiwei Zhang5434a782018-12-05 18:06:32 -08001417void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001418 result.append(kDumpTableRowLength, '-');
1419 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001420 result.append(" Layer name\n");
1421 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001422 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001423 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001424 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001425 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001426 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001427 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1428 result.append(kDumpTableRowLength, '-');
1429 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001430}
1431
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001432void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1433 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001434 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001435 return;
1436 }
1437
Yiwei Zhang5434a782018-12-05 18:06:32 -08001438 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001439 if (mName.length() > 77) {
1440 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001441 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001442 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001443 shortened.append(mName, mName.length() - 36);
1444 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001445 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001446 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001447 }
1448
Yiwei Zhang5434a782018-12-05 18:06:32 -08001449 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001450
Alec Mourib416efd2018-09-06 21:01:59 +00001451 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001452 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001453
Chia-I Wu1e043612018-03-01 09:45:09 -08001454 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001455 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001456 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001457 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001458 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001459 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001460 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001461 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1462 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001463 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001464 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001465 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001466 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001467 const auto frameRate = getFrameRateForLayerTree();
1468 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1469 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001470 ftl::enum_string(frameRate.type).c_str(),
1471 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001472 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001473 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001474 }
Dan Stozae22aec72016-08-01 13:20:59 -07001475
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001476 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1477 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1478
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001479 result.append(kDumpTableRowLength, '-');
1480 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001481}
Dan Stozae22aec72016-08-01 13:20:59 -07001482
Yiwei Zhang5434a782018-12-05 18:06:32 -08001483void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001484 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001485}
1486
Svetoslavd85084b2014-03-20 10:28:31 -07001487void Layer::clearFrameStats() {
1488 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001489}
1490
Jamie Gennis6547ff42013-07-16 20:12:42 -07001491void Layer::logFrameStats() {
1492 mFrameTracker.logAndResetStats(mName);
1493}
1494
Svetoslavd85084b2014-03-20 10:28:31 -07001495void Layer::getFrameStats(FrameStats* outStats) const {
1496 mFrameTracker.getStats(outStats);
1497}
1498
Vishnu Nair0f085c62019-08-30 08:49:12 -07001499void Layer::dumpCallingUidPid(std::string& result) const {
chaviw250bcbb2020-08-05 11:17:54 -07001500 StringAppendF(&result, "Layer %s (%s) callingPid:%d callingUid:%d ownerUid:%d\n",
1501 getName().c_str(), getType(), mCallingPid, mCallingUid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001502}
1503
Brian Anderson5ea5e592016-12-01 16:54:33 -08001504void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001505 const int32_t layerId = getSequence();
1506 mFlinger->mTimeStats->onDestroy(layerId);
1507 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001508}
1509
Chia-I Wu98f1c102017-05-30 14:54:08 -07001510size_t Layer::getChildrenCount() const {
1511 size_t count = 0;
1512 for (const sp<Layer>& child : mCurrentChildren) {
1513 count += 1 + child->getChildrenCount();
1514 }
1515 return count;
1516}
1517
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001518void Layer::setGameModeForTree(GameMode gameMode) {
1519 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001520 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1521 gameMode =
1522 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001523 }
1524 setGameMode(gameMode);
1525 for (const sp<Layer>& child : mCurrentChildren) {
1526 child->setGameModeForTree(gameMode);
1527 }
1528}
1529
Robert Carr1f0a16a2016-10-24 16:27:39 -07001530void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001531 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001532 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001533
Robert Carr1f0a16a2016-10-24 16:27:39 -07001534 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001535 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001536 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001537 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001538}
1539
1540ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001541 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001542 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001543
Robert Carr1323c952019-01-28 18:13:27 -08001544 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001545 const auto removeResult = mCurrentChildren.remove(layer);
1546
1547 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001548 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001549 layer->updateTreeHasFrameRateVote();
1550
1551 return removeResult;
1552}
1553
Robert Carr15eae092018-03-23 13:43:53 -07001554void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001555 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001556 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001557 const float parentShadowRadius =
1558 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001559 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001560 parentShadowRadius);
Vishnu Naire14c6b32022-08-06 04:20:15 +00001561 child->updateSnapshot(true /* updateGeometry */);
1562 child->updateChildrenSnapshots(true /* updateGeometry */);
Robert Carr578038f2018-03-09 12:25:24 -08001563 }
1564}
1565
chaviwf1961f72017-09-18 16:41:07 -07001566bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001567 sp<Layer> newParent;
1568 if (newParentHandle != nullptr) {
Vishnu Nairf9096652021-07-20 18:49:42 -07001569 newParent = fromHandle(newParentHandle).promote();
Robert Carr54cf5b12019-01-25 14:02:28 -08001570 if (newParent == nullptr) {
1571 ALOGE("Unable to promote Layer handle");
1572 return false;
1573 }
1574 if (newParent == this) {
1575 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1576 return false;
1577 }
1578 }
1579
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001580 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001581 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001582 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001583 }
1584
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001585 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001586 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001587 if (!newParent->isRemovedFromCurrentState()) {
1588 addToCurrentState();
1589 } else {
1590 onRemovedFromCurrentState();
1591 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001592 } else {
1593 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001594 }
1595
chaviw06178942017-07-27 10:25:59 -07001596 return true;
1597}
1598
Peiyong Lind3788632018-09-18 16:01:31 -07001599bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001600 static const mat4 identityMatrix = mat4();
1601
Robert Carr6a160312021-05-17 12:08:20 -07001602 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001603 return false;
1604 }
Robert Carr6a160312021-05-17 12:08:20 -07001605 ++mDrawingState.sequence;
1606 mDrawingState.colorTransform = matrix;
1607 mDrawingState.hasColorTransform = matrix != identityMatrix;
1608 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001609 setTransactionFlags(eTransactionNeeded);
1610 return true;
1611}
1612
chaviwf66724d2018-11-28 16:35:21 -08001613mat4 Layer::getColorTransform() const {
1614 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001615 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001616 colorTransform = parent->getColorTransform() * colorTransform;
1617 }
1618 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001619}
1620
1621bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001622 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001623 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001624 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1625 }
1626 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001627}
1628
Chia-I Wu11481472018-05-04 10:43:19 -07001629bool Layer::isLegacyDataSpace() const {
1630 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001631 return !(getDataSpace() &
1632 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1633 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001634}
1635
Robert Carr1f0a16a2016-10-24 16:27:39 -07001636void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001637 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001638}
1639
Robert Carr6a160312021-05-17 12:08:20 -07001640int32_t Layer::getZ(LayerVector::StateSet) const {
1641 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001642}
1643
Robert Carr1c5481e2019-07-01 14:42:27 -07001644bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001645 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001646 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001647 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001648}
1649
David Sodman41fdfc92017-11-06 16:09:56 -08001650__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001651 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001652 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1653 "makeTraversalList received invalid stateSet");
1654 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1655 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001656 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001657
Robert Carr29abff82017-12-04 13:51:20 -08001658 if (state.zOrderRelatives.size() == 0) {
1659 *outSkipRelativeZUsers = true;
1660 return children;
1661 }
1662
chaviwfd462612018-05-31 16:11:27 -07001663 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001664 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001665 sp<Layer> strongRelative = weakRelative.promote();
1666 if (strongRelative != nullptr) {
1667 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001668 }
1669 }
1670
Dan Stoza412903f2017-04-27 13:42:17 -07001671 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001672 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001673 continue;
1674 }
Robert Carrdb66e622017-04-10 16:55:57 -07001675 traverse.add(child);
1676 }
1677
1678 return traverse;
1679}
1680
Robert Carr1f0a16a2016-10-24 16:27:39 -07001681/**
Robert Carrdb66e622017-04-10 16:55:57 -07001682 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001683 */
Dan Stoza412903f2017-04-27 13:42:17 -07001684void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001685 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1686 // produce a new list for traversing, including our relatives, and not including our children
1687 // who are relatives of another surface. In the case that there are no relative Z,
1688 // makeTraversalList returns our children directly to avoid significant overhead.
1689 // However in this case we need to take the responsibility for filtering children which
1690 // are relatives of another surface here.
1691 bool skipRelativeZUsers = false;
1692 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001693
Robert Carr1f0a16a2016-10-24 16:27:39 -07001694 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001695 for (; i < list.size(); i++) {
1696 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001697 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1698 continue;
1699 }
1700
chaviw301b1d82019-11-06 13:15:09 -08001701 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001702 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001703 }
Dan Stoza412903f2017-04-27 13:42:17 -07001704 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001705 }
Robert Carr29abff82017-12-04 13:51:20 -08001706
Dan Stoza412903f2017-04-27 13:42:17 -07001707 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001708 for (; i < list.size(); i++) {
1709 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001710
Robert Carr29abff82017-12-04 13:51:20 -08001711 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1712 continue;
1713 }
Dan Stoza412903f2017-04-27 13:42:17 -07001714 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001715 }
1716}
1717
1718/**
Robert Carrdb66e622017-04-10 16:55:57 -07001719 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001720 */
Dan Stoza412903f2017-04-27 13:42:17 -07001721void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1722 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001723 // See traverseInZOrder for documentation.
1724 bool skipRelativeZUsers = false;
1725 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001726
Robert Carr1f0a16a2016-10-24 16:27:39 -07001727 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001728 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001729 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001730
1731 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1732 continue;
1733 }
1734
chaviw301b1d82019-11-06 13:15:09 -08001735 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001736 break;
1737 }
Dan Stoza412903f2017-04-27 13:42:17 -07001738 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001739 }
Dan Stoza412903f2017-04-27 13:42:17 -07001740 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001741 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001742 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001743
1744 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1745 continue;
1746 }
1747
Dan Stoza412903f2017-04-27 13:42:17 -07001748 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001749 }
1750}
1751
Edgar Arriaga844fa672020-01-16 14:21:42 -08001752void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1753 visitor(this);
1754 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001755 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001756 for (const sp<Layer>& child : children) {
1757 child->traverse(state, visitor);
1758 }
1759}
1760
chaviw4b129c22018-04-09 16:19:43 -07001761LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1762 const std::vector<Layer*>& layersInTree) {
1763 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1764 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001765 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1766 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001767 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001768
chaviwfd462612018-05-31 16:11:27 -07001769 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001770 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1771 sp<Layer> strongRelative = weakRelative.promote();
1772 // Only add relative layers that are also descendents of the top most parent of the tree.
1773 // If a relative layer is not a descendent, then it should be ignored.
1774 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1775 traverse.add(strongRelative);
1776 }
1777 }
1778
1779 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001780 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001781 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1782 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1783 // the child here since it won't be added later as a relative.
1784 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1785 childState.zOrderRelativeOf.promote().get())) {
1786 continue;
1787 }
1788 traverse.add(child);
1789 }
1790
1791 return traverse;
1792}
1793
1794void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1795 LayerVector::StateSet stateSet,
1796 const LayerVector::Visitor& visitor) {
1797 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001798
1799 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001800 for (; i < list.size(); i++) {
1801 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001802 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001803 break;
1804 }
chaviw4b129c22018-04-09 16:19:43 -07001805 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001806 }
chaviw4b129c22018-04-09 16:19:43 -07001807
chaviwa76b2712017-09-20 12:02:26 -07001808 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001809 for (; i < list.size(); i++) {
1810 const auto& relative = list[i];
1811 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001812 }
1813}
1814
chaviw4b129c22018-04-09 16:19:43 -07001815std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1816 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1817 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1818
1819 std::vector<Layer*> layersInTree = {this};
1820 for (size_t i = 0; i < children.size(); i++) {
1821 const auto& child = children[i];
1822 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1823 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1824 }
1825
1826 return layersInTree;
1827}
1828
1829void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1830 const LayerVector::Visitor& visitor) {
1831 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1832 std::sort(layersInTree.begin(), layersInTree.end());
1833 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1834}
1835
Peiyong Linefefaac2018-08-17 12:27:51 -07001836ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001837 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001838}
1839
Garfield Tan2c1782c2022-02-16 15:25:05 -08001840bool Layer::isTransformValid() const {
1841 float transformDet = getTransform().det();
1842 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1843}
1844
chaviw13fdc492017-06-27 12:40:18 -07001845half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001846 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001847
chaviw13fdc492017-06-27 12:40:18 -07001848 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1849 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07001850}
Robert Carr6452f122017-03-21 10:41:29 -07001851
Vishnu Nair6213bd92020-05-08 17:42:25 -07001852ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07001853 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001854 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
1855 return fixedTransformHint;
1856 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001857 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07001858 if (!p) return fixedTransformHint;
1859 return p->getFixedTransformHint();
1860}
1861
chaviw13fdc492017-06-27 12:40:18 -07001862half4 Layer::getColor() const {
1863 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001864 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07001865}
Robert Carr6452f122017-03-21 10:41:29 -07001866
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001867int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00001868 if (getDrawingState().backgroundBlurRadius == 0) {
1869 return 0;
1870 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01001871
Vishnu Nair29810f72022-07-01 16:38:41 +00001872 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01001873 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1874 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001875}
1876
Galia Peychevae0acf382021-04-12 21:22:34 +02001877const std::vector<BlurRegion> Layer::getBlurRegions() const {
1878 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02001879 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02001880 for (auto& region : regionsCopy) {
1881 region.alpha = region.alpha * layerAlpha;
1882 }
1883 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001884}
1885
Vishnu Naire14c6b32022-08-06 04:20:15 +00001886RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001887 // Get parent settings
1888 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001889 const auto& parent = mDrawingParent.promote();
1890 if (parent != nullptr) {
1891 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001892 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001893 ui::Transform t = getActiveTransform(getDrawingState());
1894 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001895 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001896 parentSettings.radius.x *= t.getScaleX();
1897 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001898 }
1899 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001900
1901 // Get layer settings
1902 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001903 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001904 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001905 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001906
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001907 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001908 // If the parent and the layer have rounded corner settings, use the parent settings if the
1909 // parent crop is entirely inside the layer crop.
1910 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
1911 if (parentSettings.cropRect.left > layerCropRect.left &&
1912 parentSettings.cropRect.top > layerCropRect.top &&
1913 parentSettings.cropRect.right < layerCropRect.right &&
1914 parentSettings.cropRect.bottom < layerCropRect.bottom) {
1915 return parentSettings;
1916 } else {
1917 return layerSettings;
1918 }
Vishnu Nairb1845592021-10-07 12:17:57 -07001919 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001920 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001921 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001922 return parentSettings;
1923 }
1924 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001925}
1926
Robert Carr88b85e12022-03-21 15:47:35 -07001927bool Layer::findInHierarchy(const sp<Layer>& l) {
1928 if (l == this) {
1929 return true;
1930 }
1931 for (auto& child : mDrawingChildren) {
1932 if (child->findInHierarchy(l)) {
1933 return true;
1934 }
1935 }
1936 return false;
1937}
1938
Robert Carr1f0a16a2016-10-24 16:27:39 -07001939void Layer::commitChildList() {
1940 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
1941 const auto& child = mCurrentChildren[i];
1942 child->commitChildList();
1943 }
1944 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07001945 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07001946 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
1947 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1948 if (zOrderRelativeOf == nullptr) return;
1949 if (findInHierarchy(zOrderRelativeOf)) {
1950 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
1951 zOrderRelativeOf->mName.c_str());
1952 ALOGE("Severing rel Z loop, potentially dangerous");
1953 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07001954 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07001955 }
1956 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001957}
1958
Vishnu Nair6fabeec2019-03-12 13:42:49 -07001959
chaviw3277faf2021-05-19 16:45:23 -05001960void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07001961 mDrawingState.inputInfo = info;
Vishnu Nairf9096652021-07-20 18:49:42 -07001962 mDrawingState.touchableRegionCrop = fromHandle(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07001963 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00001964 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07001965 setTransactionFlags(eTransactionNeeded);
1966}
1967
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08001968LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08001969 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08001970 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08001971 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
1972
Vishnu Nair00b90132021-11-05 14:03:40 -07001973 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001974 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
1975
Vishnu Nair60db8c02020-04-02 11:55:16 -07001976 // Only populate for the primary display.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001977 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -05001978 const auto compositionType = getCompositionType(*display);
Vishnu Nair60db8c02020-04-02 11:55:16 -07001979 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08001980 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
1981 [&]() { return layerProto->mutable_visible_region(); });
Vishnu Nair60db8c02020-04-02 11:55:16 -07001982 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08001983 }
1984
chaviw08f3cb22020-01-13 13:17:21 -08001985 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08001986 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08001987 }
chaviw6d89e2d2020-01-14 14:42:01 -08001988
1989 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08001990}
1991
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08001992void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07001993 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08001994 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07001995 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08001996 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07001997 [&]() { return layerInfo->mutable_active_buffer(); });
1998 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
1999 layerInfo->mutable_buffer_transform());
2000 }
2001 layerInfo->set_invalidate(contentDirty);
2002 layerInfo->set_is_protected(isProtected());
2003 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2004 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002005 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002006 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002007 layerInfo->set_corner_radius(
2008 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002009 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2010 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2011 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2012 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2013 [&]() { return layerInfo->mutable_position(); });
2014 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002015 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2016 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002017
Vishnu Nair00b90132021-11-05 14:03:40 -07002018 if (hasColorTransform()) {
2019 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002020 }
2021
Vishnu Nair60db8c02020-04-02 11:55:16 -07002022 LayerProtoHelper::writeToProto(mSourceBounds,
2023 [&]() { return layerInfo->mutable_source_bounds(); });
2024 LayerProtoHelper::writeToProto(mScreenBounds,
2025 [&]() { return layerInfo->mutable_screen_bounds(); });
2026 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2027 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2028 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002029}
2030
2031void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002032 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002033 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2034 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002035 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002036
chaviw766c9c52021-02-10 17:36:47 -08002037 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002038
Vishnu Nair00b90132021-11-05 14:03:40 -07002039 layerInfo->set_id(sequence);
2040 layerInfo->set_name(getName().c_str());
2041 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002042
Vishnu Nair00b90132021-11-05 14:03:40 -07002043 for (const auto& child : children) {
2044 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002045 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002046
Vishnu Nair00b90132021-11-05 14:03:40 -07002047 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2048 sp<Layer> strongRelative = weakRelative.promote();
2049 if (strongRelative != nullptr) {
2050 layerInfo->add_relatives(strongRelative->sequence);
2051 }
2052 }
2053
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002054 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002055 [&]() { return layerInfo->mutable_transparent_region(); });
2056
2057 layerInfo->set_layer_stack(getLayerStack().id);
2058 layerInfo->set_z(state.z);
2059
2060 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2061 return layerInfo->mutable_requested_position();
2062 });
2063
Vishnu Nair00b90132021-11-05 14:03:40 -07002064 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2065
2066 layerInfo->set_is_opaque(isOpaque(state));
2067
2068 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2069 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2070 LayerProtoHelper::writeToProto(state.color,
2071 [&]() { return layerInfo->mutable_requested_color(); });
2072 layerInfo->set_flags(state.flags);
2073
2074 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2075 layerInfo->mutable_requested_transform());
2076
2077 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2078 if (parent != nullptr) {
2079 layerInfo->set_parent(parent->sequence);
2080 } else {
2081 layerInfo->set_parent(-1);
2082 }
2083
2084 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2085 if (zOrderRelativeOf != nullptr) {
2086 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2087 } else {
2088 layerInfo->set_z_order_relative_of(-1);
2089 }
2090
2091 layerInfo->set_is_relative_of(state.isRelativeOf);
2092
2093 layerInfo->set_owner_uid(mOwnerUid);
2094
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002095 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002096 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002097 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002098 info = fillInputInfo(
2099 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002100 } else {
2101 info = state.inputInfo;
2102 }
2103
2104 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002105 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002106 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002107
Vishnu Nair00b90132021-11-05 14:03:40 -07002108 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002109 auto protoMap = layerInfo->mutable_metadata();
2110 for (const auto& entry : state.metadata.mMap) {
2111 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2112 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002113 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002114
2115 LayerProtoHelper::writeToProto(state.destinationFrame,
2116 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002117}
2118
Robert Carr2e102c92018-10-23 12:11:15 -07002119bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002120 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002121}
2122
Prabir Pradhan33da9462022-06-14 14:55:57 +00002123// Applies the given transform to the region, while protecting against overflows caused by any
2124// offsets. If applying the offset in the transform to any of the Rects in the region would result
2125// in an overflow, they are not added to the output Region.
2126static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2127 const std::string& debugWindowName) {
2128 // Round the translation using the same rounding strategy used by ui::Transform.
2129 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2130 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2131
2132 ui::Transform transformWithoutOffset = t;
2133 transformWithoutOffset.set(0.f, 0.f);
2134
2135 const Region transformed = transformWithoutOffset.transform(r);
2136
2137 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2138 Region ret;
2139 for (const auto& rect : transformed) {
2140 Rect newRect;
2141 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2142 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2143 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2144 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2145 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2146 debugWindowName.c_str());
2147 continue;
2148 }
2149 ret.orSelf(newRect);
2150 }
2151 return ret;
2152}
2153
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002154void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
2155 Rect tmpBounds = getInputBounds();
2156 if (!tmpBounds.isValid()) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002157 info.touchableRegion.clear();
2158 // A layer could have invalid input bounds and still expect to receive touch input if it has
2159 // replaceTouchableRegionWithCrop. For that case, the input transform needs to be calculated
2160 // correctly to determine the coordinate space for input events. Use an empty rect so that
2161 // the layer will receive input in its own layer space.
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002162 tmpBounds = Rect::EMPTY_RECT;
chaviw7e72caf2020-12-02 16:50:43 -08002163 }
2164
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002165 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2166 // frame and transform used for the layer, which determines the bounds and the coordinate space
2167 // within which the layer will receive input.
2168 //
2169 // The coordinate space within which each of the bounds are specified is explicitly documented
2170 // in the variable name. For example "inputBoundsInLayer" is specified in layer space. A
2171 // Transform converts one coordinate space to another, which is apparent in its naming. For
2172 // example, "layerToDisplay" transforms layer space to display space.
2173 //
2174 // Coordinate space definitions:
2175 // - display: The display device's coordinate space. Correlates to pixels on the display.
2176 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2177 // - layer: The coordinate space of this layer.
2178 // - input: The coordinate space in which this layer will receive input events. This could be
2179 // different than layer space if a surfaceInset is used, which changes the origin
2180 // of the input space.
2181 const FloatRect inputBoundsInLayer = tmpBounds.toFloatRect();
chaviw7e72caf2020-12-02 16:50:43 -08002182
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002183 // Clamp surface inset to the input bounds.
2184 const auto surfaceInset = static_cast<float>(info.surfaceInset);
2185 const float xSurfaceInset =
2186 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getWidth() / 2.f));
2187 const float ySurfaceInset =
2188 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getHeight() / 2.f));
chaviw1ff3d1e2020-07-01 15:53:47 -07002189
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002190 // Apply the insets to the input bounds.
2191 const FloatRect insetBoundsInLayer(inputBoundsInLayer.left + xSurfaceInset,
2192 inputBoundsInLayer.top + ySurfaceInset,
2193 inputBoundsInLayer.right - xSurfaceInset,
2194 inputBoundsInLayer.bottom - ySurfaceInset);
Ady Abraham282f1d72019-07-24 18:05:56 -07002195
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002196 // Crop the input bounds to ensure it is within the parent's bounds.
2197 const FloatRect croppedInsetBoundsInLayer = mBounds.intersect(insetBoundsInLayer);
Ady Abraham282f1d72019-07-24 18:05:56 -07002198
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002199 const ui::Transform layerToScreen = getInputTransform();
2200 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
Vishnu Nair8033a492018-12-05 07:27:23 -08002201
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002202 const Rect roundedFrameInDisplay{layerToDisplay.transform(croppedInsetBoundsInLayer)};
2203 info.frameLeft = roundedFrameInDisplay.left;
2204 info.frameTop = roundedFrameInDisplay.top;
2205 info.frameRight = roundedFrameInDisplay.right;
2206 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002207
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002208 ui::Transform inputToLayer;
2209 inputToLayer.set(insetBoundsInLayer.left, insetBoundsInLayer.top);
2210 const ui::Transform inputToDisplay = layerToDisplay * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002211
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002212 // InputDispatcher expects a display-to-input transform.
2213 info.transform = inputToDisplay.inverse();
2214
2215 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002216 info.touchableRegion =
2217 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002218}
2219
chaviw3277faf2021-05-19 16:45:23 -05002220void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002221 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002222 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002223 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002224 }
2225 if (p != nullptr) {
2226 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2227 }
2228}
2229
Vishnu Naira066d902021-09-13 18:40:17 -07002230gui::DropInputMode Layer::getDropInputMode() const {
2231 gui::DropInputMode mode = mDrawingState.dropInputMode;
2232 if (mode == gui::DropInputMode::ALL) {
2233 return mode;
2234 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002235 sp<Layer> parent = mDrawingParent.promote();
2236 if (parent) {
2237 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002238 if (parentMode != gui::DropInputMode::NONE) {
2239 return parentMode;
2240 }
2241 }
2242 return mode;
2243}
2244
2245void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002246 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002247 return;
2248 }
2249
2250 // Check if we need to drop input unconditionally
2251 gui::DropInputMode dropInputMode = getDropInputMode();
2252 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002253 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002254 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2255 return;
2256 }
2257
2258 // Check if we need to check if the window is obscured by parent
2259 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2260 return;
2261 }
2262
2263 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002264 sp<Layer> parent = mDrawingParent.promote();
2265 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002266 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002267 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2268 static_cast<float>(getAlpha()));
2269 }
2270
2271 // Check if the parent has cropped the buffer
2272 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2273 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002274 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002275 return;
2276 }
2277
2278 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2279 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2280 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2281 // match then the layer has not been cropped by its parents.
2282 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2283 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2284
2285 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002286 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002287 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2288 getDebugName());
2289 } else {
2290 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2291 // input if the window is obscured. This check should be done in surfaceflinger but the
2292 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2293 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002294 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002295 }
2296}
2297
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002298WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002299 if (!hasInputInfo()) {
2300 mDrawingState.inputInfo.name = getName();
2301 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2302 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002303 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002304 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002305 }
2306
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002307 const ui::Transform& displayTransform =
2308 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2309
chaviw3277faf2021-05-19 16:45:23 -05002310 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002311 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002312 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002313
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002314 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002315
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002316 if (displayArgs.transform == nullptr) {
2317 // Do not let the window receive touches if it is not associated with a valid display
2318 // transform. We still allow the window to receive keys and prevent ANRs.
2319 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2320 }
2321
Robert Carr5dc426e2020-06-10 14:29:14 -07002322 // For compatibility reasons we let layers which can receive input
2323 // receive input before they have actually submitted a buffer. Because
2324 // of this we use canReceiveInput instead of isVisible to check the
2325 // policy-visibility, ignoring the buffer state. However for layers with
2326 // hasInputInfo()==false we can use the real visibility state.
2327 // We are just using these layers for occlusion detection in
2328 // InputDispatcher, and obviously if they aren't visible they can't occlude
2329 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002330 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2331 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2332
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002333 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002334 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002335 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002336
Vishnu Nair16a938f2021-09-24 07:14:54 -07002337 // If the window will be blacked out on a display because the display does not have the secure
2338 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002339 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002340 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002341 }
2342
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002343 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2344 if (info.replaceTouchableRegionWithCrop) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002345 const Rect bounds(cropLayer ? cropLayer->mScreenBounds : mScreenBounds);
2346 info.touchableRegion = Region(displayTransform.transform(bounds));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002347 } else if (cropLayer != nullptr) {
[1;3C2b9fc252021-02-04 16:16:50 -08002348 info.touchableRegion = info.touchableRegion.intersect(
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002349 displayTransform.transform(Rect{cropLayer->mScreenBounds}));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002350 }
2351
Winson Chunga30f7c92021-06-29 15:42:56 -07002352 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2353 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002354 if (isTrustedOverlay()) {
2355 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2356 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002357
chaviwaf87b3e2019-10-01 16:59:28 -07002358 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2359 // touches from going outside the cloned area.
2360 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002361 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002362 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2363 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002364 info.touchableRegion = info.touchableRegion.intersect(rect);
2365 }
2366 }
2367
Robert Carr720e5062018-07-30 17:45:14 -07002368 return info;
2369}
2370
chaviwaf87b3e2019-10-01 16:59:28 -07002371sp<Layer> Layer::getClonedRoot() {
2372 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002373 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002374 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002375 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002376 return nullptr;
2377 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002378 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002379}
2380
Robert Carredd13602020-04-13 17:24:34 -07002381bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002382 return mDrawingState.inputInfo.token != nullptr ||
2383 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002384}
2385
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002386compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002387 const DisplayDevice* display) const {
2388 if (!display) return nullptr;
Lloyd Piquede196652020-01-22 17:29:58 -08002389 return display->getCompositionDisplay()->getOutputLayerForLayer(getCompositionEngineLayerFE());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002390}
2391
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002392Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2393 const auto outputLayer = findOutputLayerForDisplay(display);
2394 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002395}
2396
chaviwb4c6e582019-08-16 14:35:07 -07002397void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002398 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002399 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002400 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2401 mPotentialCursor = clonedFrom->mPotentialCursor;
2402 mProtectedByApp = clonedFrom->mProtectedByApp;
2403 updateCloneBufferInfo();
2404}
2405
2406void Layer::updateCloneBufferInfo() {
2407 if (!isClone() || !isClonedFromAlive()) {
2408 return;
2409 }
2410
2411 sp<Layer> clonedFrom = getClonedFrom();
2412 mBufferInfo = clonedFrom->mBufferInfo;
2413 mSidebandStream = clonedFrom->mSidebandStream;
2414 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2415 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2416 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2417
2418 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2419 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2420 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2421 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2422 // the cloned drawingState again.
2423 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2424 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2425 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2426 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2427
2428 cloneDrawingState(clonedFrom.get());
2429
2430 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2431 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2432 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2433 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002434}
chaviw74b03172019-08-19 11:09:03 -07002435
2436void Layer::updateMirrorInfo() {
2437 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2438 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2439 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2440 // that case, we want to delete the reference to the clone since we want it to get
2441 // destroyed. The root, this layer, will still be around since the client can continue
2442 // to hold a reference, but no cloned layers will be displayed.
2443 mClonedChild = nullptr;
2444 return;
2445 }
2446
2447 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2448 // If the real layer exists and is in current state, add the clone as a child of the root.
2449 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2450 // copied to drawingState for the root layer. So the clonedChild is always removed from
2451 // drawingState and then needs to be added back each traversal.
2452 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2453 addChildToDrawing(mClonedChild);
2454 }
2455
2456 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002457 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002458 mClonedChild->updateClonedRelatives(clonedLayersMap);
2459}
2460
2461void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2462 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2463 // to the clone. If the real layer is no longer alive, continue traversing the children
2464 // since we may be able to pull out other children that are still alive.
2465 if (isClonedFromAlive()) {
2466 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002467 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002468 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002469 }
2470
2471 // The clone layer may have children in drawingState since they may have been created and
2472 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2473 // that already exist, since we can just re-use them.
2474 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2475 // not updated in the regular traversal. They are skipped since the root will lose the
2476 // reference to them when it copies its currentChildren to drawing.
2477 for (sp<Layer>& child : mDrawingChildren) {
2478 child->updateClonedDrawingState(clonedLayersMap);
2479 }
2480}
2481
2482void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2483 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2484 mDrawingChildren.clear();
2485
2486 if (!isClonedFromAlive()) {
2487 return;
2488 }
2489
2490 sp<Layer> clonedFrom = getClonedFrom();
2491 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2492 if (child == mirrorRoot) {
2493 // This is to avoid cyclical mirroring.
2494 continue;
2495 }
2496 sp<Layer> clonedChild = clonedLayersMap[child];
2497 if (clonedChild == nullptr) {
2498 clonedChild = child->createClone();
2499 clonedLayersMap[child] = clonedChild;
2500 }
2501 addChildToDrawing(clonedChild);
2502 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2503 }
2504}
2505
chaviwaf87b3e2019-10-01 16:59:28 -07002506void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2507 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2508 if (cropLayer != nullptr) {
2509 if (clonedLayersMap.count(cropLayer) == 0) {
2510 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2511 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002512 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002513 } else {
2514 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2515 mDrawingState.touchableRegionCrop = clonedCropLayer;
2516 }
2517 }
2518 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2519 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002520 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002521}
2522
2523void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002524 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002525 mDrawingState.zOrderRelatives.clear();
2526
2527 if (!isClonedFromAlive()) {
2528 return;
2529 }
2530
chaviwaf87b3e2019-10-01 16:59:28 -07002531 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002532 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002533 const sp<Layer>& relative = relativeWeak.promote();
2534 if (clonedLayersMap.count(relative) > 0) {
2535 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002536 mDrawingState.zOrderRelatives.add(clonedRelative);
2537 }
2538 }
2539
2540 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2541 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2542 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2543 // still traverse the children, but the layer with the missing relativeOf will not be shown
2544 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002545 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2546 if (clonedLayersMap.count(relativeOf) > 0) {
2547 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002548 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2549 }
2550
chaviwaf87b3e2019-10-01 16:59:28 -07002551 updateClonedInputInfo(clonedLayersMap);
2552
chaviw74b03172019-08-19 11:09:03 -07002553 for (sp<Layer>& child : mDrawingChildren) {
2554 child->updateClonedRelatives(clonedLayersMap);
2555 }
2556}
2557
2558void Layer::addChildToDrawing(const sp<Layer>& layer) {
2559 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002560 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002561}
2562
Steven Thomas62a4cf82020-01-31 12:04:03 -08002563Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2564 switch (compatibility) {
2565 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2566 return FrameRateCompatibility::Default;
2567 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2568 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002569 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2570 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002571 case ANATIVEWINDOW_FRAME_RATE_MIN:
2572 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002573 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2574 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002575 default:
2576 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2577 return FrameRateCompatibility::Default;
2578 }
2579}
2580
Marin Shalamanovc5986772021-03-16 16:09:49 +01002581scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2582 switch (strategy) {
2583 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2584 return Seamlessness::OnlySeamless;
2585 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2586 return Seamlessness::SeamedAndSeamless;
2587 default:
2588 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2589 return Seamlessness::Default;
2590 }
2591}
2592
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002593bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002594 const State& s(mDrawingState);
2595 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2596 return true;
2597 }
2598
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002599 sp<Layer> parent = mDrawingParent.promote();
2600 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002601}
2602
Robert Carr6a0382d2021-07-01 15:57:17 -07002603void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2604 mClonedChild = clonedChild;
2605 mHadClonedChild = true;
2606 mFlinger->mNumClones++;
2607}
2608
Vishnu Nairf9096652021-07-20 18:49:42 -07002609const String16 Layer::Handle::kDescriptor = String16("android.Layer.Handle");
2610
2611wp<Layer> Layer::fromHandle(const sp<IBinder>& handleBinder) {
2612 if (handleBinder == nullptr) {
2613 return nullptr;
2614 }
2615
2616 BBinder* b = handleBinder->localBinder();
2617 if (b == nullptr || b->getInterfaceDescriptor() != Handle::kDescriptor) {
2618 return nullptr;
2619 }
2620
2621 // We can safely cast this binder since its local and we verified its interface descriptor.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002622 sp<Handle> handle = sp<Handle>::cast(handleBinder);
Vishnu Nairf9096652021-07-20 18:49:42 -07002623 return handle->owner;
2624}
2625
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002626bool Layer::setDropInputMode(gui::DropInputMode mode) {
2627 if (mDrawingState.dropInputMode == mode) {
2628 return false;
2629 }
2630 mDrawingState.dropInputMode = mode;
2631 return true;
2632}
2633
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002634void Layer::cloneDrawingState(const Layer* from) {
2635 mDrawingState = from->mDrawingState;
2636 // Skip callback info since they are not applicable for cloned layers.
2637 mDrawingState.releaseBufferListener = nullptr;
2638 mDrawingState.callbackHandles = {};
2639}
2640
Patrick Williamsbb25f802022-08-30 23:02:34 +00002641void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2642 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
2643 const sp<Fence>& releaseFence,
2644 uint32_t currentMaxAcquiredBufferCount) {
2645 if (!listener) {
2646 return;
2647 }
2648 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
2649 listener->onReleaseBuffer({buffer->getId(), framenumber},
2650 releaseFence ? releaseFence : Fence::NO_FENCE,
2651 currentMaxAcquiredBufferCount);
2652}
2653
2654void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2655 // If we are displayed on multiple displays in a single composition cycle then we would
2656 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2657 // For example we can only use it if all the displays are client comp, and we need
2658 // to merge all the client comp fences. We could do this, but for now we just
2659 // disable the optimization when a layer is composed on multiple displays.
2660 if (mClearClientCompositionFenceOnLayerDisplayed) {
2661 mLastClientCompositionFence = nullptr;
2662 } else {
2663 mClearClientCompositionFenceOnLayerDisplayed = true;
2664 }
2665
2666 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2667 // buffer that was presented on this layer. The first transaction that came in this frame that
2668 // replaced the previous buffer on this layer needs this release fence, because the fence will
2669 // let the client know when that previous buffer is removed from the screen.
2670 //
2671 // Every other transaction on this layer does not need a release fence because no other
2672 // Transactions that were set on this layer this frame are going to have their preceding buffer
2673 // removed from the display this frame.
2674 //
2675 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2676 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2677 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2678 // the previous buffer will be released this frame. The third transaction also contains a
2679 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2680 // transaction will now no longer be presented so it is released immediately and the third
2681 // transaction doesn't need a previous release fence.
2682 sp<CallbackHandle> ch;
2683 for (auto& handle : mDrawingState.callbackHandles) {
2684 if (handle->releasePreviousBuffer &&
2685 mDrawingState.releaseBufferEndpoint == handle->listener) {
2686 ch = handle;
2687 break;
2688 }
2689 }
2690
2691 // Prevent tracing the same release multiple times.
2692 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2693 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2694 }
2695
2696 if (ch != nullptr) {
2697 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2698 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2699 ch->name = mName;
2700 }
2701}
2702
2703void Layer::onSurfaceFrameCreated(
2704 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Vishnu Nair22491b82022-10-18 14:59:14 -07002705 if (!hasBufferOrSidebandStreamInDrawing()) {
2706 return;
2707 }
2708
Patrick Williamsbb25f802022-08-30 23:02:34 +00002709 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2710 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2711 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2712 // leak.
2713 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2714 mName.c_str());
2715 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2716 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2717 mPendingJankClassifications.pop_front();
2718 }
2719 mPendingJankClassifications.emplace_back(surfaceFrame);
2720}
2721
2722void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2723 for (const auto& handle : mDrawingState.callbackHandles) {
2724 handle->transformHint = mTransformHint;
2725 handle->dequeueReadyTime = dequeueReadyTime;
2726 handle->currentMaxAcquiredBufferCount =
2727 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2728 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2729 handle->previousReleaseCallbackId.framenumber);
2730 }
2731
2732 for (auto& handle : mDrawingState.callbackHandles) {
2733 if (handle->releasePreviousBuffer &&
2734 mDrawingState.releaseBufferEndpoint == handle->listener) {
2735 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2736 break;
2737 }
2738 }
2739
2740 std::vector<JankData> jankData;
2741 jankData.reserve(mPendingJankClassifications.size());
2742 while (!mPendingJankClassifications.empty() &&
2743 mPendingJankClassifications.front()->getJankType()) {
2744 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
2745 mPendingJankClassifications.front();
2746 mPendingJankClassifications.pop_front();
2747 jankData.emplace_back(
2748 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
2749 }
2750
2751 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2752 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002753 mDrawingState.callbackHandles = {};
2754}
2755
2756bool Layer::willPresentCurrentTransaction() const {
2757 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2758 return (getSidebandStreamChanged() || getAutoRefresh() ||
2759 (mDrawingState.modified &&
2760 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2761}
2762
2763bool Layer::setTransform(uint32_t transform) {
2764 if (mDrawingState.bufferTransform == transform) return false;
2765 mDrawingState.bufferTransform = transform;
2766 mDrawingState.modified = true;
2767 setTransactionFlags(eTransactionNeeded);
2768 return true;
2769}
2770
2771bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2772 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2773 mDrawingState.sequence++;
2774 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2775 mDrawingState.modified = true;
2776 setTransactionFlags(eTransactionNeeded);
2777 return true;
2778}
2779
2780bool Layer::setBufferCrop(const Rect& bufferCrop) {
2781 if (mDrawingState.bufferCrop == bufferCrop) return false;
2782
2783 mDrawingState.sequence++;
2784 mDrawingState.bufferCrop = bufferCrop;
2785
2786 mDrawingState.modified = true;
2787 setTransactionFlags(eTransactionNeeded);
2788 return true;
2789}
2790
2791bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2792 if (mDrawingState.destinationFrame == destinationFrame) return false;
2793
2794 mDrawingState.sequence++;
2795 mDrawingState.destinationFrame = destinationFrame;
2796
2797 mDrawingState.modified = true;
2798 setTransactionFlags(eTransactionNeeded);
2799 return true;
2800}
2801
2802// Translate destination frame into scale and position. If a destination frame is not set, use the
2803// provided scale and position
2804bool Layer::updateGeometry() {
2805 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2806 mDrawingState.destinationFrame.isEmpty()) {
2807 // If destination frame is not set, use the requested transform set via
2808 // Layer::setPosition and Layer::setMatrix.
2809 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2810 }
2811
2812 Rect destRect = mDrawingState.destinationFrame;
2813 int32_t destW = destRect.width();
2814 int32_t destH = destRect.height();
2815 if (destRect.left < 0) {
2816 destRect.left = 0;
2817 destRect.right = destW;
2818 }
2819 if (destRect.top < 0) {
2820 destRect.top = 0;
2821 destRect.bottom = destH;
2822 }
2823
2824 if (!mDrawingState.buffer) {
2825 ui::Transform t;
2826 t.set(destRect.left, destRect.top);
2827 return assignTransform(&mDrawingState.transform, t);
2828 }
2829
2830 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2831 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2832 // Undo any transformations on the buffer.
2833 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2834 std::swap(bufferWidth, bufferHeight);
2835 }
2836 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
2837 if (mDrawingState.transformToDisplayInverse) {
2838 if (invTransform & ui::Transform::ROT_90) {
2839 std::swap(bufferWidth, bufferHeight);
2840 }
2841 }
2842
2843 float sx = destW / static_cast<float>(bufferWidth);
2844 float sy = destH / static_cast<float>(bufferHeight);
2845 ui::Transform t;
2846 t.set(sx, 0, 0, sy);
2847 t.set(destRect.left, destRect.top);
2848 return assignTransform(&mDrawingState.transform, t);
2849}
2850
2851bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
2852 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
2853 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
2854 return false;
2855 }
2856
2857 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
2858
2859 mDrawingState.sequence++;
2860 mDrawingState.modified = true;
2861 setTransactionFlags(eTransactionNeeded);
2862
2863 return true;
2864}
2865
2866bool Layer::setPosition(float x, float y) {
2867 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
2868 return false;
2869 }
2870
2871 mRequestedTransform.set(x, y);
2872
2873 mDrawingState.sequence++;
2874 mDrawingState.modified = true;
2875 setTransactionFlags(eTransactionNeeded);
2876
2877 return true;
2878}
2879
2880bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
2881 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
2882 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
2883 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00002884 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00002885 if (!buffer) {
2886 return false;
2887 }
2888
2889 const bool frameNumberChanged =
2890 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
2891 const uint64_t frameNumber =
2892 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00002893 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002894
2895 if (mDrawingState.buffer) {
2896 mReleasePreviousBuffer = true;
2897 if (!mBufferInfo.mBuffer ||
2898 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
2899 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
2900 // If mDrawingState has a buffer, and we are about to update again
2901 // before swapping to drawing state, then the first buffer will be
2902 // dropped and we should decrement the pending buffer count and
2903 // call any release buffer callbacks if set.
2904 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
2905 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
2906 mDrawingState.acquireFence,
2907 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
2908 mOwnerUid));
2909 decrementPendingBufferCount();
2910 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
2911 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
2912 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
2913 mDrawingState.bufferSurfaceFrameTX.reset();
2914 }
2915 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
2916 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
2917 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
2918 mLastClientCompositionFence,
2919 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
2920 mOwnerUid));
2921 mLastClientCompositionFence = nullptr;
2922 }
2923 }
2924
2925 mDrawingState.frameNumber = frameNumber;
2926 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
2927 mDrawingState.buffer = std::move(buffer);
2928 mDrawingState.clientCacheId = bufferData.cachedBuffer;
2929
2930 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
2931 ? bufferData.acquireFence
2932 : Fence::NO_FENCE;
2933 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
2934 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
2935 // We latched this buffer unsiganled, so we need to pass the acquire fence
2936 // on the callback instead of just the acquire time, since it's unknown at
2937 // this point.
2938 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
2939 } else {
2940 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
2941 }
2942
2943 mDrawingState.modified = true;
2944 setTransactionFlags(eTransactionNeeded);
2945
2946 const int32_t layerId = getSequence();
2947 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
2948 mOwnerUid, postTime, getGameMode());
2949 mDrawingState.desiredPresentTime = desiredPresentTime;
2950 mDrawingState.isAutoTimestamp = isAutoTimestamp;
2951
2952 const nsecs_t presentTime = [&] {
2953 if (!isAutoTimestamp) return desiredPresentTime;
2954
2955 const auto prediction =
2956 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
2957 if (prediction.has_value()) return prediction->presentTime;
2958
2959 return static_cast<nsecs_t>(0);
2960 }();
2961
2962 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
2963 mFlinger->mScheduler->recordLayerHistory(this, presentTime, LayerUpdateType::Buffer);
2964
2965 setFrameTimelineVsyncForBufferTransaction(info, postTime);
2966
2967 if (dequeueTime && *dequeueTime != 0) {
2968 const uint64_t bufferId = mDrawingState.buffer->getId();
2969 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
2970 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
2971 FrameTracer::FrameEvent::DEQUEUE);
2972 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
2973 FrameTracer::FrameEvent::QUEUE);
2974 }
2975
2976 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
2977 return true;
2978}
2979
2980bool Layer::setDataspace(ui::Dataspace dataspace) {
2981 mDrawingState.dataspaceRequested = true;
2982 if (mDrawingState.dataspace == dataspace) return false;
2983 mDrawingState.dataspace = dataspace;
2984 mDrawingState.modified = true;
2985 setTransactionFlags(eTransactionNeeded);
2986 return true;
2987}
2988
2989bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
2990 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
2991 mDrawingState.hdrMetadata = hdrMetadata;
2992 mDrawingState.modified = true;
2993 setTransactionFlags(eTransactionNeeded);
2994 return true;
2995}
2996
2997bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
2998 mDrawingState.surfaceDamageRegion = surfaceDamage;
2999 mDrawingState.modified = true;
3000 setTransactionFlags(eTransactionNeeded);
3001 return true;
3002}
3003
3004bool Layer::setApi(int32_t api) {
3005 if (mDrawingState.api == api) return false;
3006 mDrawingState.api = api;
3007 mDrawingState.modified = true;
3008 setTransactionFlags(eTransactionNeeded);
3009 return true;
3010}
3011
3012bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3013 if (mDrawingState.sidebandStream == sidebandStream) return false;
3014
3015 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3016 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3017 } else if (sidebandStream != nullptr) {
3018 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3019 }
3020
3021 mDrawingState.sidebandStream = sidebandStream;
3022 mDrawingState.modified = true;
3023 setTransactionFlags(eTransactionNeeded);
3024 if (!mSidebandStreamChanged.exchange(true)) {
3025 // mSidebandStreamChanged was false
3026 mFlinger->onLayerUpdate();
3027 }
3028 return true;
3029}
3030
3031bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles) {
3032 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3033 if (handles.empty()) {
3034 mReleasePreviousBuffer = false;
3035 return false;
3036 }
3037
3038 const bool willPresent = willPresentCurrentTransaction();
3039
3040 for (const auto& handle : handles) {
3041 // If this transaction set a buffer on this layer, release its previous buffer
3042 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3043
3044 // If this layer will be presented in this frame
3045 if (willPresent) {
3046 // If this transaction set an acquire fence on this layer, set its acquire time
3047 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3048 handle->frameNumber = mDrawingState.frameNumber;
3049
3050 // Store so latched time and release fence can be set
3051 mDrawingState.callbackHandles.push_back(handle);
3052
3053 } else { // If this layer will NOT need to be relatched and presented this frame
3054 // Notify the transaction completed thread this handle is done
3055 mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
3056 }
3057 }
3058
3059 mReleasePreviousBuffer = false;
3060 mCallbackHandleAcquireTimeOrFence = -1;
3061
3062 return willPresent;
3063}
3064
3065Rect Layer::getBufferSize(const State& /*s*/) const {
3066 // for buffer state layers we use the display frame size as the buffer size.
3067
3068 if (mBufferInfo.mBuffer == nullptr) {
3069 return Rect::INVALID_RECT;
3070 }
3071
3072 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3073 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3074
3075 // Undo any transformations on the buffer and return the result.
3076 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3077 std::swap(bufWidth, bufHeight);
3078 }
3079
3080 if (getTransformToDisplayInverse()) {
3081 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3082 if (invTransform & ui::Transform::ROT_90) {
3083 std::swap(bufWidth, bufHeight);
3084 }
3085 }
3086
3087 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3088}
3089
3090FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3091 if (mBufferInfo.mBuffer == nullptr) {
3092 return parentBounds;
3093 }
3094
3095 return getBufferSize(getDrawingState()).toFloatRect();
3096}
3097
3098bool Layer::fenceHasSignaled() const {
3099 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3100 return true;
3101 }
3102
3103 const bool fenceSignaled =
3104 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3105 if (!fenceSignaled) {
3106 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3107 TimeStats::LatchSkipReason::LateAcquire);
3108 }
3109
3110 return fenceSignaled;
3111}
3112
Vishnu Naire14c6b32022-08-06 04:20:15 +00003113bool Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003114 for (const auto& handle : mDrawingState.callbackHandles) {
3115 handle->refreshStartTime = refreshStartTime;
3116 }
3117 return hasReadyFrame();
3118}
3119
3120void Layer::setAutoRefresh(bool autoRefresh) {
3121 mDrawingState.autoRefresh = autoRefresh;
3122}
3123
3124bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3125 // 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 +00003126 auto* snapshot = editLayerSnapshot();
3127 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003128
3129 if (mSidebandStreamChanged.exchange(false)) {
3130 const State& s(getDrawingState());
3131 // mSidebandStreamChanged was true
3132 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003133 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003134 if (mSidebandStream != nullptr) {
3135 setTransactionFlags(eTransactionNeeded);
3136 mFlinger->setTransactionFlags(eTraversalNeeded);
3137 }
3138 recomputeVisibleRegions = true;
3139
3140 return true;
3141 }
3142 return false;
3143}
3144
3145bool Layer::hasFrameUpdate() const {
3146 const State& c(getDrawingState());
3147 return (mDrawingStateModified || mDrawingState.modified) &&
3148 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3149}
3150
3151void Layer::updateTexImage(nsecs_t latchTime) {
3152 const State& s(getDrawingState());
3153
3154 if (!s.buffer) {
3155 if (s.bgColorLayer) {
3156 for (auto& handle : mDrawingState.callbackHandles) {
3157 handle->latchTime = latchTime;
3158 }
3159 }
3160 return;
3161 }
3162
3163 for (auto& handle : mDrawingState.callbackHandles) {
3164 if (handle->frameNumber == mDrawingState.frameNumber) {
3165 handle->latchTime = latchTime;
3166 }
3167 }
3168
3169 const int32_t layerId = getSequence();
3170 const uint64_t bufferId = mDrawingState.buffer->getId();
3171 const uint64_t frameNumber = mDrawingState.frameNumber;
3172 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3173 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3174 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3175
3176 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3177 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3178 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3179 FrameTracer::FrameEvent::LATCH);
3180
3181 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3182 if (bufferSurfaceFrame != nullptr &&
3183 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3184 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3185 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3186 // are processing the next state.
3187 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3188 mDrawingState.acquireFenceTime->getSignalTime(),
3189 latchTime);
3190 mDrawingState.bufferSurfaceFrameTX.reset();
3191 }
3192
3193 std::deque<sp<CallbackHandle>> remainingHandles;
3194 mFlinger->getTransactionCallbackInvoker()
3195 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3196 mDrawingState.callbackHandles = remainingHandles;
3197
3198 mDrawingStateModified = false;
3199}
3200
3201void Layer::gatherBufferInfo() {
3202 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3203 decrementPendingBufferCount();
3204 }
3205
3206 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3207 mBufferInfo.mBuffer = mDrawingState.buffer;
3208 mBufferInfo.mFence = mDrawingState.acquireFence;
3209 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3210 mBufferInfo.mPixelFormat =
3211 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3212 mBufferInfo.mFrameLatencyNeeded = true;
3213 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3214 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3215 mBufferInfo.mFence = mDrawingState.acquireFence;
3216 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3217 auto lastDataspace = mBufferInfo.mDataspace;
3218 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3219 if (lastDataspace != mBufferInfo.mDataspace) {
3220 mFlinger->mSomeDataspaceChanged = true;
3221 }
3222 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3223 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3224 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3225 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3226 mBufferInfo.mApi = mDrawingState.api;
3227 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
3228 mBufferInfo.mBufferSlot = mHwcSlotGenerator->getHwcCacheSlot(mDrawingState.clientCacheId);
3229}
3230
3231Rect Layer::computeBufferCrop(const State& s) {
3232 if (s.buffer && !s.bufferCrop.isEmpty()) {
3233 Rect bufferCrop;
3234 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3235 return bufferCrop;
3236 } else if (s.buffer) {
3237 return s.buffer->getBounds();
3238 } else {
3239 return s.bufferCrop;
3240 }
3241}
3242
3243sp<Layer> Layer::createClone() {
3244 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3245 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003246 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003247 layer->mHwcSlotGenerator = mHwcSlotGenerator;
3248 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3249 return layer;
3250}
3251
3252bool Layer::bufferNeedsFiltering() const {
3253 const State& s(getDrawingState());
3254 if (!s.buffer) {
3255 return false;
3256 }
3257
3258 int32_t bufferWidth = static_cast<int32_t>(s.buffer->getWidth());
3259 int32_t bufferHeight = static_cast<int32_t>(s.buffer->getHeight());
3260
3261 // Undo any transformations on the buffer and return the result.
3262 if (s.bufferTransform & ui::Transform::ROT_90) {
3263 std::swap(bufferWidth, bufferHeight);
3264 }
3265
3266 if (s.transformToDisplayInverse) {
3267 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3268 if (invTransform & ui::Transform::ROT_90) {
3269 std::swap(bufferWidth, bufferHeight);
3270 }
3271 }
3272
3273 const Rect layerSize{getBounds()};
3274 int32_t layerWidth = layerSize.getWidth();
3275 int32_t layerHeight = layerSize.getHeight();
3276
3277 // Align the layer orientation with the buffer before comparism
3278 if (mTransformHint & ui::Transform::ROT_90) {
3279 std::swap(layerWidth, layerHeight);
3280 }
3281
3282 return layerWidth != bufferWidth || layerHeight != bufferHeight;
3283}
3284
3285void Layer::decrementPendingBufferCount() {
3286 int32_t pendingBuffers = --mPendingBufferTransactions;
3287 tracePendingBufferCount(pendingBuffers);
3288}
3289
3290void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3291 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3292}
3293
3294/*
3295 * We don't want to send the layer's transform to input, but rather the
3296 * parent's transform. This is because Layer's transform is
3297 * information about how the buffer is placed on screen. The parent's
3298 * transform makes more sense to send since it's information about how the
3299 * layer is placed on screen. This transform is used by input to determine
3300 * how to go from screen space back to window space.
3301 */
3302ui::Transform Layer::getInputTransform() const {
3303 if (!hasBufferOrSidebandStream()) {
3304 return getTransform();
3305 }
3306 sp<Layer> parent = mDrawingParent.promote();
3307 if (parent == nullptr) {
3308 return ui::Transform();
3309 }
3310
3311 return parent->getTransform();
3312}
3313
3314/**
3315 * Similar to getInputTransform, we need to update the bounds to include the transform.
3316 * This is because bounds don't include the buffer transform, where the input assumes
3317 * that's already included.
3318 */
3319Rect Layer::getInputBounds() const {
3320 if (!hasBufferOrSidebandStream()) {
3321 return getCroppedBufferSize(getDrawingState());
3322 }
3323
3324 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
3325 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
3326 return bufferBounds;
3327 }
3328 return mDrawingState.transform.transform(bufferBounds);
3329}
3330
3331bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3332 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3333
3334 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3335 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3336 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3337 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3338 layer_state_t::eReparent;
3339
3340 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3341 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3342 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3343 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3344 layer_state_t::eInputInfoChanged;
3345
3346 if ((s.what & requiredFlags) != requiredFlags) {
3347 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3348 (s.what | requiredFlags) & ~s.what);
3349 return false;
3350 }
3351
3352 if (s.what & deniedFlags) {
3353 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3354 return false;
3355 }
3356
3357 if (s.what & allowedFlags) {
3358 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3359 }
3360
3361 if (s.what & layer_state_t::ePositionChanged) {
3362 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3363 ALOGV("%s: false [ePositionChanged changed]", __func__);
3364 return false;
3365 }
3366 }
3367
3368 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003369 if (mDrawingState.color.a != s.color.a) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003370 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3371 return false;
3372 }
3373 }
3374
3375 if (s.what & layer_state_t::eColorTransformChanged) {
3376 if (mDrawingState.colorTransform != s.colorTransform) {
3377 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3378 return false;
3379 }
3380 }
3381
3382 if (s.what & layer_state_t::eBackgroundColorChanged) {
3383 if (mDrawingState.bgColorLayer || s.bgColorAlpha != 0) {
3384 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3385 return false;
3386 }
3387 }
3388
3389 if (s.what & layer_state_t::eMatrixChanged) {
3390 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3391 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3392 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3393 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3394 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3395 return false;
3396 }
3397 }
3398
3399 if (s.what & layer_state_t::eCornerRadiusChanged) {
3400 if (mDrawingState.cornerRadius != s.cornerRadius) {
3401 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3402 return false;
3403 }
3404 }
3405
3406 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3407 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3408 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3409 return false;
3410 }
3411 }
3412
Vishnu Nairbbceb462022-10-10 04:52:13 +00003413 if (s.what & layer_state_t::eBufferTransformChanged) {
3414 if (mDrawingState.bufferTransform != s.bufferTransform) {
3415 ALOGV("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003416 return false;
3417 }
3418 }
3419
3420 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3421 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3422 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3423 return false;
3424 }
3425 }
3426
3427 if (s.what & layer_state_t::eCropChanged) {
3428 if (mDrawingState.crop != s.crop) {
3429 ALOGV("%s: false [eCropChanged changed]", __func__);
3430 return false;
3431 }
3432 }
3433
3434 if (s.what & layer_state_t::eDataspaceChanged) {
3435 if (mDrawingState.dataspace != s.dataspace) {
3436 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3437 return false;
3438 }
3439 }
3440
3441 if (s.what & layer_state_t::eHdrMetadataChanged) {
3442 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3443 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3444 return false;
3445 }
3446 }
3447
3448 if (s.what & layer_state_t::eSidebandStreamChanged) {
3449 if (mDrawingState.sidebandStream != s.sidebandStream) {
3450 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3451 return false;
3452 }
3453 }
3454
3455 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3456 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3457 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3458 return false;
3459 }
3460 }
3461
3462 if (s.what & layer_state_t::eShadowRadiusChanged) {
3463 if (mDrawingState.shadowRadius != s.shadowRadius) {
3464 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3465 return false;
3466 }
3467 }
3468
3469 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3470 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3471 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3472 return false;
3473 }
3474 }
3475
3476 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3477 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3478 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3479 return false;
3480 }
3481 }
3482
3483 if (s.what & layer_state_t::eStretchChanged) {
3484 StretchEffect temp = s.stretchEffect;
3485 temp.sanitize();
3486 if (mDrawingState.stretchEffect != temp) {
3487 ALOGV("%s: false [eStretchChanged changed]", __func__);
3488 return false;
3489 }
3490 }
3491
3492 if (s.what & layer_state_t::eBufferCropChanged) {
3493 if (mDrawingState.bufferCrop != s.bufferCrop) {
3494 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3495 return false;
3496 }
3497 }
3498
3499 if (s.what & layer_state_t::eDestinationFrameChanged) {
3500 if (mDrawingState.destinationFrame != s.destinationFrame) {
3501 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3502 return false;
3503 }
3504 }
3505
3506 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3507 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3508 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3509 return false;
3510 }
3511 }
3512
3513 ALOGV("%s: true", __func__);
3514 return true;
3515}
3516
3517bool Layer::isHdrY410() const {
3518 // pixel format is HDR Y410 masquerading as RGBA_1010102
3519 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3520 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3521 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3522}
3523
Vishnu Naire14c6b32022-08-06 04:20:15 +00003524sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003525 // There's no need to get a CE Layer if the layer isn't going to draw anything.
Vishnu Naire14c6b32022-08-06 04:20:15 +00003526 return hasSomethingToDraw() ? mLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003527}
3528
Vishnu Naire14c6b32022-08-06 04:20:15 +00003529const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003530 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003531}
3532
Vishnu Naire14c6b32022-08-06 04:20:15 +00003533LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003534 return mSnapshot.get();
3535}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003536
Patrick Williamsbb25f802022-08-30 23:02:34 +00003537const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003538 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003539}
3540
3541void Layer::useSurfaceDamage() {
3542 if (mFlinger->mForceFullDamage) {
3543 surfaceDamageRegion = Region::INVALID_REGION;
3544 } else {
3545 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3546 }
3547}
3548
3549void Layer::useEmptyDamage() {
3550 surfaceDamageRegion.clear();
3551}
3552
3553bool Layer::isOpaque(const Layer::State& s) const {
3554 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3555 // layer's opaque flag.
3556 if (!hasSomethingToDraw()) {
3557 return false;
3558 }
3559
3560 // if the layer has the opaque flag, then we're always opaque
3561 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3562 return true;
3563 }
3564
3565 // If the buffer has no alpha channel, then we are opaque
3566 if (hasBufferOrSidebandStream() && isOpaqueFormat(getPixelFormat())) {
3567 return true;
3568 }
3569
3570 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3571 return fillsColor() && getAlpha() == 1.0_hf;
3572}
3573
3574bool Layer::canReceiveInput() const {
3575 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3576}
3577
3578bool Layer::isVisible() const {
3579 if (!hasSomethingToDraw()) {
3580 return false;
3581 }
3582
3583 if (isHiddenByPolicy()) {
3584 return false;
3585 }
3586
3587 return getAlpha() > 0.0f || hasBlur();
3588}
3589
3590void Layer::onPostComposition(const DisplayDevice* display,
3591 const std::shared_ptr<FenceTime>& glDoneFence,
3592 const std::shared_ptr<FenceTime>& presentFence,
3593 const CompositorTiming& compositorTiming) {
3594 // mFrameLatencyNeeded is true when a new frame was latched for the
3595 // composition.
3596 if (!mBufferInfo.mFrameLatencyNeeded) return;
3597
3598 for (const auto& handle : mDrawingState.callbackHandles) {
3599 handle->gpuCompositionDoneFence = glDoneFence;
3600 handle->compositorTiming = compositorTiming;
3601 }
3602
3603 // Update mFrameTracker.
3604 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3605 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3606
3607 const int32_t layerId = getSequence();
3608 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3609
3610 const auto outputLayer = findOutputLayerForDisplay(display);
3611 if (outputLayer && outputLayer->requiresClientComposition()) {
3612 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3613 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3614 clientCompositionTimestamp,
3615 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3616 // Update the SurfaceFrames in the drawing state
3617 if (mDrawingState.bufferSurfaceFrameTX) {
3618 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3619 }
3620 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3621 surfaceFrame->setGpuComposition();
3622 }
3623 }
3624
3625 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3626 if (frameReadyFence->isValid()) {
3627 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3628 } else {
3629 // There was no fence for this frame, so assume that it was ready
3630 // to be presented at the desired present time.
3631 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3632 }
3633
3634 if (display) {
Dominik Laskowskif8734e02022-08-26 09:06:59 -07003635 const Fps refreshRate = display->refreshRateConfigs().getActiveModePtr()->getFps();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003636 const std::optional<Fps> renderRate =
3637 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3638
3639 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3640 const auto gameMode = getGameMode();
3641
3642 if (presentFence->isValid()) {
3643 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3644 refreshRate, renderRate, vote, gameMode);
3645 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3646 presentFence,
3647 FrameTracer::FrameEvent::PRESENT_FENCE);
3648 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3649 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3650 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003651 // The HWC doesn't support present fences, so use the present timestamp instead.
3652 const nsecs_t presentTimestamp =
3653 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3654
3655 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3656 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3657 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3658
Patrick Williamsbb25f802022-08-30 23:02:34 +00003659 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3660 refreshRate, renderRate, vote, gameMode);
3661 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3662 mCurrentFrameNumber, actualPresentTime,
3663 FrameTracer::FrameEvent::PRESENT_FENCE);
3664 mFrameTracker.setActualPresentTime(actualPresentTime);
3665 }
3666 }
3667
3668 mFrameTracker.advanceFrame();
3669 mBufferInfo.mFrameLatencyNeeded = false;
3670}
3671
3672bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
3673 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3674 getDrawingState().frameNumber);
3675
3676 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3677
3678 if (refreshRequired) {
3679 return refreshRequired;
3680 }
3681
3682 // If the head buffer's acquire fence hasn't signaled yet, return and
3683 // try again later
3684 if (!fenceHasSignaled()) {
3685 ATRACE_NAME("!fenceHasSignaled()");
3686 mFlinger->onLayerUpdate();
3687 return false;
3688 }
3689
3690 updateTexImage(latchTime);
3691 if (mDrawingState.buffer == nullptr) {
3692 return false;
3693 }
3694
3695 // Capture the old state of the layer for comparisons later
3696 BufferInfo oldBufferInfo = mBufferInfo;
3697 const bool oldOpacity = isOpaque(mDrawingState);
3698 mPreviousFrameNumber = mCurrentFrameNumber;
3699 mCurrentFrameNumber = mDrawingState.frameNumber;
3700 gatherBufferInfo();
3701
3702 if (oldBufferInfo.mBuffer == nullptr) {
3703 // the first time we receive a buffer, we need to trigger a
3704 // geometry invalidation.
3705 recomputeVisibleRegions = true;
3706 }
3707
3708 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3709 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3710 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3711 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3712 recomputeVisibleRegions = true;
3713 }
3714
3715 if (oldBufferInfo.mBuffer != nullptr) {
3716 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3717 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3718 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3719 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3720 recomputeVisibleRegions = true;
3721 }
3722 }
3723
3724 if (oldOpacity != isOpaque(mDrawingState)) {
3725 recomputeVisibleRegions = true;
3726 }
3727
3728 return true;
3729}
3730
3731bool Layer::hasReadyFrame() const {
3732 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
3733}
3734
3735bool Layer::isProtected() const {
3736 return (mBufferInfo.mBuffer != nullptr) &&
3737 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
3738}
3739
3740// As documented in libhardware header, formats in the range
3741// 0x100 - 0x1FF are specific to the HAL implementation, and
3742// are known to have no alpha channel
3743// TODO: move definition for device-specific range into
3744// hardware.h, instead of using hard-coded values here.
3745#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
3746
3747bool Layer::isOpaqueFormat(PixelFormat format) {
3748 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
3749 return true;
3750 }
3751 switch (format) {
3752 case PIXEL_FORMAT_RGBA_8888:
3753 case PIXEL_FORMAT_BGRA_8888:
3754 case PIXEL_FORMAT_RGBA_FP16:
3755 case PIXEL_FORMAT_RGBA_1010102:
3756 case PIXEL_FORMAT_R_8:
3757 return false;
3758 }
3759 // in all other case, we have no blending (also for unknown formats)
3760 return true;
3761}
3762
3763bool Layer::needsFiltering(const DisplayDevice* display) const {
3764 if (!hasBufferOrSidebandStream()) {
3765 return false;
3766 }
3767 const auto outputLayer = findOutputLayerForDisplay(display);
3768 if (outputLayer == nullptr) {
3769 return false;
3770 }
3771
3772 // We need filtering if the sourceCrop rectangle size does not match the
3773 // displayframe rectangle size (not a 1:1 render)
3774 const auto& compositionState = outputLayer->getState();
3775 const auto displayFrame = compositionState.displayFrame;
3776 const auto sourceCrop = compositionState.sourceCrop;
3777 return sourceCrop.getHeight() != displayFrame.getHeight() ||
3778 sourceCrop.getWidth() != displayFrame.getWidth();
3779}
3780
3781bool Layer::needsFilteringForScreenshots(const DisplayDevice* display,
3782 const ui::Transform& inverseParentTransform) const {
3783 if (!hasBufferOrSidebandStream()) {
3784 return false;
3785 }
3786 const auto outputLayer = findOutputLayerForDisplay(display);
3787 if (outputLayer == nullptr) {
3788 return false;
3789 }
3790
3791 // We need filtering if the sourceCrop rectangle size does not match the
3792 // viewport rectangle size (not a 1:1 render)
3793 const auto& compositionState = outputLayer->getState();
3794 const ui::Transform& displayTransform = display->getTransform();
3795 const ui::Transform inverseTransform = inverseParentTransform * displayTransform.inverse();
3796 // Undo the transformation of the displayFrame so that we're back into
3797 // layer-stack space.
3798 const Rect frame = inverseTransform.transform(compositionState.displayFrame);
3799 const FloatRect sourceCrop = compositionState.sourceCrop;
3800
3801 int32_t frameHeight = frame.getHeight();
3802 int32_t frameWidth = frame.getWidth();
3803 // If the display transform had a rotational component then undo the
3804 // rotation so that the orientation matches the source crop.
3805 if (displayTransform.getOrientation() & ui::Transform::ROT_90) {
3806 std::swap(frameHeight, frameWidth);
3807 }
3808 return sourceCrop.getHeight() != frameHeight || sourceCrop.getWidth() != frameWidth;
3809}
3810
3811void Layer::latchAndReleaseBuffer() {
3812 if (hasReadyFrame()) {
3813 bool ignored = false;
3814 latchBuffer(ignored, systemTime());
3815 }
3816 releasePendingBuffer(systemTime());
3817}
3818
3819PixelFormat Layer::getPixelFormat() const {
3820 return mBufferInfo.mPixelFormat;
3821}
3822
3823bool Layer::getTransformToDisplayInverse() const {
3824 return mBufferInfo.mTransformToDisplayInverse;
3825}
3826
3827Rect Layer::getBufferCrop() const {
3828 // this is the crop rectangle that applies to the buffer
3829 // itself (as opposed to the window)
3830 if (!mBufferInfo.mCrop.isEmpty()) {
3831 // if the buffer crop is defined, we use that
3832 return mBufferInfo.mCrop;
3833 } else if (mBufferInfo.mBuffer != nullptr) {
3834 // otherwise we use the whole buffer
3835 return mBufferInfo.mBuffer->getBounds();
3836 } else {
3837 // if we don't have a buffer yet, we use an empty/invalid crop
3838 return Rect();
3839 }
3840}
3841
3842uint32_t Layer::getBufferTransform() const {
3843 return mBufferInfo.mTransform;
3844}
3845
3846ui::Dataspace Layer::getDataSpace() const {
3847 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
3848}
3849
3850ui::Dataspace Layer::getRequestedDataSpace() const {
3851 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
3852}
3853
3854ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
3855 ui::Dataspace updatedDataspace = dataspace;
3856 // translate legacy dataspaces to modern dataspaces
3857 switch (dataspace) {
3858 case ui::Dataspace::SRGB:
3859 updatedDataspace = ui::Dataspace::V0_SRGB;
3860 break;
3861 case ui::Dataspace::SRGB_LINEAR:
3862 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
3863 break;
3864 case ui::Dataspace::JFIF:
3865 updatedDataspace = ui::Dataspace::V0_JFIF;
3866 break;
3867 case ui::Dataspace::BT601_625:
3868 updatedDataspace = ui::Dataspace::V0_BT601_625;
3869 break;
3870 case ui::Dataspace::BT601_525:
3871 updatedDataspace = ui::Dataspace::V0_BT601_525;
3872 break;
3873 case ui::Dataspace::BT709:
3874 updatedDataspace = ui::Dataspace::V0_BT709;
3875 break;
3876 default:
3877 break;
3878 }
3879
3880 return updatedDataspace;
3881}
3882
3883sp<GraphicBuffer> Layer::getBuffer() const {
3884 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
3885}
3886
Patrick Williamsbb25f802022-08-30 23:02:34 +00003887void Layer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
3888 mTransformHint = getFixedTransformHint();
3889 if (mTransformHint == ui::Transform::ROT_INVALID) {
3890 mTransformHint = displayTransformHint;
3891 }
3892}
3893
3894const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
3895 return mBufferInfo.mBuffer;
3896}
3897
3898bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003899 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003900 return false;
3901 }
3902
3903 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00003904 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003905 mDrawingState.modified = true;
3906 setTransactionFlags(eTransactionNeeded);
3907 return true;
3908}
3909
3910bool Layer::fillsColor() const {
3911 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
3912 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
3913}
3914
3915bool Layer::hasBlur() const {
3916 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
3917}
3918
Vishnu Nairba354102022-08-01 00:14:18 +00003919void Layer::updateSnapshot(bool updateGeometry) {
3920 if (!getCompositionEngineLayerFE()) {
3921 return;
3922 }
3923
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003924 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00003925 if (updateGeometry) {
3926 prepareBasicGeometryCompositionState();
3927 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003928 snapshot->roundedCorner = getRoundedCornerState();
3929 snapshot->stretchEffect = getStretchEffect();
3930 snapshot->transformedBounds = mScreenBounds;
3931 if (mEffectiveShadowRadius > 0.f) {
3932 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
3933
3934 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
3935 // it if transparent regions are present. This may not be necessary since shadows are
3936 // typically cast by layers without transparent regions.
3937 snapshot->shadowSettings.boundaries = mBounds;
3938
3939 const float casterAlpha = snapshot->alpha;
3940 const bool casterIsOpaque =
3941 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
3942
3943 // If the casting layer is translucent, we need to fill in the shadow underneath the
3944 // layer. Otherwise the generated shadow will only be shown around the casting layer.
3945 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
3946 snapshot->shadowSettings.ambientColor *= casterAlpha;
3947 snapshot->shadowSettings.spotColor *= casterAlpha;
3948 }
3949 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00003950 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003951 snapshot->contentOpaque = isOpaque(mDrawingState);
3952 snapshot->isHdrY410 = isHdrY410();
3953 snapshot->bufferNeedsFiltering = bufferNeedsFiltering();
3954 sp<Layer> p = mDrawingParent.promote();
3955 if (p != nullptr) {
3956 snapshot->transform = p->getTransform();
3957 } else {
3958 snapshot->transform.reset();
3959 }
3960 snapshot->bufferSize = getBufferSize(mDrawingState);
3961 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00003962 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00003963 preparePerFrameCompositionState();
3964}
3965
Vishnu Naire14c6b32022-08-06 04:20:15 +00003966void Layer::updateChildrenSnapshots(bool updateGeometry) {
3967 for (const sp<Layer>& child : mDrawingChildren) {
3968 child->updateSnapshot(updateGeometry);
3969 child->updateChildrenSnapshots(updateGeometry);
3970 }
3971}
3972
Vishnu Nair0a4fb002022-08-08 02:40:42 +00003973void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
3974 mSnapshot->layerMetadata = parentMetadata;
3975 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
3976 for (const sp<Layer>& child : mDrawingChildren) {
3977 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
3978 }
3979}
3980
3981void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
3982 std::unordered_set<Layer*>& visited) {
3983 if (visited.find(this) != visited.end()) {
3984 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
3985 return;
3986 }
3987 visited.insert(this);
3988
3989 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
3990
3991 if (mDrawingState.zOrderRelatives.empty()) {
3992 return;
3993 }
3994 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
3995 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
3996 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
3997 sp<Layer> relative = weakRelative.promote();
3998 if (!relative) {
3999 continue;
4000 }
4001 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4002 }
4003}
4004
Patrick Williams377c0142022-10-13 17:33:38 +00004005LayerSnapshotGuard::LayerSnapshotGuard(Layer* layer) : mLayer(layer) {
4006 if (mLayer) {
4007 mLayer->mLayerFE->mSnapshot = std::move(mLayer->mSnapshot);
4008 }
4009}
4010
4011LayerSnapshotGuard::~LayerSnapshotGuard() {
4012 if (mLayer) {
4013 mLayer->mSnapshot = std::move(mLayer->mLayerFE->mSnapshot);
4014 }
4015}
4016
4017LayerSnapshotGuard::LayerSnapshotGuard(LayerSnapshotGuard&& other) : mLayer(other.mLayer) {
4018 other.mLayer = nullptr;
4019}
4020
4021LayerSnapshotGuard& LayerSnapshotGuard::operator=(LayerSnapshotGuard&& other) {
4022 mLayer = other.mLayer;
4023 other.mLayer = nullptr;
4024 return *this;
4025}
4026
Mathias Agopian13127d82013-03-05 17:47:11 -08004027// ---------------------------------------------------------------------------
4028
Marin Shalamanov46084422020-10-13 12:33:42 +02004029std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004030 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4031 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004032}
4033
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004034} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004035
4036#if defined(__gl_h_)
4037#error "don't include gl/gl.h in this file"
4038#endif
4039
4040#if defined(__gl2_h_)
4041#error "don't include gl2/gl2.h in this file"
4042#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004043
4044// TODO(b/129481165): remove the #pragma below and fix conversion issues
4045#pragma clang diagnostic pop // ignored "-Wconversion"