blob: ca330e46c7b26fec7b0f09850f200102bb692713 [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>
Patrick Williamsbb25f802022-08-30 23:02:34 +000043#include <gui/GLConsumer.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080044#include <gui/LayerDebugInfo.h>
45#include <gui/Surface.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000046#include <gui/TraceUtils.h>
Alec Mourie60041e2019-06-14 18:59:51 -070047#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070048#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080049#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070050#include <stdint.h>
51#include <stdlib.h>
52#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000053#include <system/graphics-base-v1.0.h>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070054#include <ui/DataspaceUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080055#include <ui/DebugUtils.h>
56#include <ui/GraphicBuffer.h>
57#include <ui/PixelFormat.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058#include <utils/Errors.h>
59#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080060#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080062#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Alec Mourie60041e2019-06-14 18:59:51 -070064#include <algorithm>
65#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070066#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070067#include <sstream>
68
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070069#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080070#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070071#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070072#include "FrameTracer/FrameTracer.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080073#include "LayerProtoHelper.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080075#include "TimeStats/TimeStats.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070076#include "TunnelModeEnabledReporter.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070077
David Sodman41fdfc92017-11-06 16:09:56 -080078#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000079#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081namespace android {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010082namespace {
83constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000084
85static constexpr float defaultMaxLuminance = 1000.0;
86
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000087const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000088
89constexpr mat4 inverseOrientation(uint32_t transform) {
90 const mat4 flipH(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
91 const mat4 flipV(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1);
92 const mat4 rot90(0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
93 mat4 tr;
94
95 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
96 tr = tr * rot90;
97 }
98 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
99 tr = tr * flipH;
100 }
101 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
102 tr = tr * flipV;
103 }
104 return inverse(tr);
105}
106
107bool assignTransform(ui::Transform* dst, ui::Transform& from) {
108 if (*dst == from) {
109 return false;
110 }
111 *dst = from;
112 return true;
113}
114
115TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
116 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
117 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
118 const auto frameRateCompatibility = [frameRate] {
119 switch (frameRate.type) {
120 case Layer::FrameRateCompatibility::Default:
121 return FrameRateCompatibility::Default;
122 case Layer::FrameRateCompatibility::ExactOrMultiple:
123 return FrameRateCompatibility::ExactOrMultiple;
124 default:
125 return FrameRateCompatibility::Undefined;
126 }
127 }();
128
129 const auto seamlessness = [frameRate] {
130 switch (frameRate.seamlessness) {
131 case scheduler::Seamlessness::OnlySeamless:
132 return Seamlessness::ShouldBeSeamless;
133 case scheduler::Seamlessness::SeamedAndSeamless:
134 return Seamlessness::NotRequired;
135 default:
136 return Seamlessness::Undefined;
137 }
138 }();
139
140 return TimeStats::SetFrameRateVote{.frameRate = frameRate.rate.getValue(),
141 .frameRateCompatibility = frameRateCompatibility,
142 .seamlessness = seamlessness};
143}
144
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100145} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800146
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700147using namespace ftl::flag_operators;
148
Yiwei Zhang5434a782018-12-05 18:06:32 -0800149using base::StringAppendF;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800150using gui::GameMode;
151using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500152using gui::WindowInfo;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800153
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700154using PresentState = frametimeline::SurfaceFrame::PresentState;
155
Lloyd Piquef1c675b2018-09-12 20:45:39 -0700156std::atomic<int32_t> Layer::sSequence{1};
Mathias Agopian13127d82013-03-05 17:47:11 -0800157
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700158Layer::Layer(const LayerCreationArgs& args)
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800159 : sequence(args.sequence.value_or(sSequence++)),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700160 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000161 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700162 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800163 mWindowType(static_cast<WindowInfo::Type>(
164 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000165 mLayerCreationFlags(args.flags),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000166 mBorderEnabled(false),
167 mTextureName(args.textureName),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000168 mHwcSlotGenerator(sp<HwcSlotGenerator>::make()) {
169 ALOGV("Creating Layer %s", getDebugName());
170
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700171 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700172 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
173 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
174 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700175 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
176 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Vishnu Naira84a2202022-01-12 20:12:55 -0800177 if (args.sequence) {
178 sSequence = *args.sequence + 1;
179 }
Robert Carr6a160312021-05-17 12:08:20 -0700180 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700181 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700182 mDrawingState.z = 0;
183 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700184 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700185 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700186 mDrawingState.transform.set(0, 0);
187 mDrawingState.frameNumber = 0;
188 mDrawingState.bufferTransform = 0;
189 mDrawingState.transformToDisplayInverse = false;
190 mDrawingState.crop.makeInvalid();
191 mDrawingState.acquireFence = sp<Fence>::make(-1);
192 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
193 mDrawingState.dataspace = ui::Dataspace::UNKNOWN;
Vishnu Nairbc4ee5c2022-08-16 03:19:37 +0000194 mDrawingState.dataspaceRequested = false;
Robert Carr6a160312021-05-17 12:08:20 -0700195 mDrawingState.hdrMetadata.validTypes = 0;
196 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
197 mDrawingState.cornerRadius = 0.0f;
198 mDrawingState.backgroundBlurRadius = 0;
199 mDrawingState.api = -1;
200 mDrawingState.hasColorTransform = false;
201 mDrawingState.colorSpaceAgnostic = false;
202 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
203 mDrawingState.metadata = args.metadata;
204 mDrawingState.shadowRadius = 0.f;
205 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
206 mDrawingState.frameTimelineInfo = {};
207 mDrawingState.postTime = -1;
208 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000209 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700210 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700211 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000212 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700213
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700214 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
215 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700216 mDrawingState.color.r = -1.0_hf;
217 mDrawingState.color.g = -1.0_hf;
218 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700219 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700220
221 mFrameTracker.setDisplayRefreshPeriod(
222 args.flinger->mScheduler->getVsyncPeriodFromRefreshRateConfigs());
Robert Carr2e102c92018-10-23 12:11:15 -0700223
Vishnu Nair0f085c62019-08-30 08:49:12 -0700224 mCallingPid = args.callingPid;
225 mCallingUid = args.callingUid;
chaviw250bcbb2020-08-05 11:17:54 -0700226
227 if (mCallingUid == AID_GRAPHICS || mCallingUid == AID_SYSTEM) {
228 // If the system didn't send an ownerUid, use the callingUid for the ownerUid.
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800229 mOwnerUid = args.metadata.getInt32(gui::METADATA_OWNER_UID, mCallingUid);
230 mOwnerPid = args.metadata.getInt32(gui::METADATA_OWNER_PID, mCallingPid);
chaviw250bcbb2020-08-05 11:17:54 -0700231 } else {
232 // A create layer request from a non system request cannot specify the owner uid
233 mOwnerUid = mCallingUid;
Adithya Srinivasan9febda82020-10-19 10:49:41 -0700234 mOwnerPid = mCallingPid;
chaviw250bcbb2020-08-05 11:17:54 -0700235 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000236
237 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
238 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
239 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
240 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000241
242 mSnapshot->sequence = sequence;
243 mSnapshot->name = getDebugName();
244 mSnapshot->textureName = mTextureName;
245 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
246 mSnapshot->transform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800247}
248
249void Layer::onFirstRef() {
250 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700251}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700252
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700253Layer::~Layer() {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000254 // The original layer and the clone layer share the same texture and buffer. Therefore, only
255 // one of the layers, in this case the original layer, needs to handle the deletion. The
256 // original layer and the clone should be removed at the same time so there shouldn't be any
257 // issue with the clone layer trying to use the texture.
258 if (mBufferInfo.mBuffer != nullptr) {
259 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
260 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
261 mBufferInfo.mFence,
262 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
263 mOwnerUid));
264 }
265 if (!isClone()) {
266 // The original layer and the clone layer share the same texture. Therefore, only one of
267 // the layers, in this case the original layer, needs to handle the deletion. The original
268 // layer and the clone should be removed at the same time so there shouldn't be any issue
269 // with the clone layer trying to use the deleted texture.
270 mFlinger->deleteTextureAsync(mTextureName);
271 }
272 const int32_t layerId = getSequence();
273 mFlinger->mTimeStats->onDestroy(layerId);
274 mFlinger->mFrameTracer->onDestroy(layerId);
275
David Sodman577c8962017-12-08 14:50:53 -0800276 sp<Client> c(mClientRef.promote());
277 if (c != 0) {
278 c->detachLayer(this);
279 }
280
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000281 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700282 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700283
284 if (mDrawingState.sidebandStream != nullptr) {
285 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
286 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700287 if (mHadClonedChild) {
288 mFlinger->mNumClones--;
289 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700290}
291
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700292LayerCreationArgs::LayerCreationArgs(SurfaceFlinger* flinger, sp<Client> client, std::string name,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800293 uint32_t flags, LayerMetadata metadata)
Vishnu Nair0f085c62019-08-30 08:49:12 -0700294 : flinger(flinger),
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700295 client(std::move(client)),
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700296 name(std::move(name)),
Vishnu Nair0f085c62019-08-30 08:49:12 -0700297 flags(flags),
298 metadata(std::move(metadata)) {
299 IPCThreadState* ipc = IPCThreadState::self();
300 callingPid = ipc->getCallingPid();
301 callingUid = ipc->getCallingUid();
302}
303
Mathias Agopian13127d82013-03-05 17:47:11 -0800304// ---------------------------------------------------------------------------
305// callbacks
306// ---------------------------------------------------------------------------
307
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700308void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700309 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700310 return;
311 }
Robert Carr2e102c92018-10-23 12:11:15 -0700312
Robert Carr6a160312021-05-17 12:08:20 -0700313 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700314 if (strongRelative == nullptr) {
315 setZOrderRelativeOf(nullptr);
316 return;
317 }
318
319 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700320 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700321 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800322 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700323 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700324}
325
326void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700327 if (!mRemovedFromDrawingState) {
328 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700329 mFlinger->mScheduler->deregisterLayer(this);
330 }
Rob Carr4bba3702018-10-08 21:53:30 +0000331
Ady Abrahamd11bade2022-08-01 16:18:03 -0700332 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700333}
Chia-I Wu38512252017-05-17 14:36:16 -0700334
chaviw68d4dab2020-06-08 15:07:32 -0700335sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000336 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700337 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700338 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700339 }
340 return parent->getRootLayer();
341}
342
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700343void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700344 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
345 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700346 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700347
348 traverse(LayerVector::StateSet::Current, [&](Layer* layer) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700349 layer->removeFromCurrentState();
350 layer->removeRelativeZ(layersInTree);
chaviw68d4dab2020-06-08 15:07:32 -0700351 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700352}
353
chaviw61626f22018-11-15 16:26:27 -0800354void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700355 if (mRemovedFromDrawingState) {
356 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700357 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700358 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700359 }
chaviw61626f22018-11-15 16:26:27 -0800360
361 for (const auto& child : mCurrentChildren) {
362 child->addToCurrentState();
363 }
364}
365
Mathias Agopian13127d82013-03-05 17:47:11 -0800366// ---------------------------------------------------------------------------
367// set-up
368// ---------------------------------------------------------------------------
369
chaviw13fdc492017-06-27 12:40:18 -0700370bool Layer::getPremultipledAlpha() const {
371 return mPremultipliedAlpha;
372}
373
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700374sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800375 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700376 if (mGetHandleCalled) {
377 ALOGE("Get handle called twice" );
378 return nullptr;
379 }
380 mGetHandleCalled = true;
Ady Abrahamd11bade2022-08-01 16:18:03 -0700381 return sp<Handle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800382}
383
384// ---------------------------------------------------------------------------
385// h/w composer set-up
386// ---------------------------------------------------------------------------
387
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700388static Rect reduce(const Rect& win, const Region& exclude) {
389 if (CC_LIKELY(exclude.isEmpty())) {
390 return win;
391 }
392 if (exclude.isRect()) {
393 return win.reduce(exclude.getBounds());
394 }
395 return Region(win).subtract(exclude).getBounds();
396}
397
Dan Stoza80d61162017-12-20 15:57:52 -0800398static FloatRect reduce(const FloatRect& win, const Region& exclude) {
399 if (CC_LIKELY(exclude.isEmpty())) {
400 return win;
401 }
402 // Convert through Rect (by rounding) for lack of FloatRegion
403 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
404}
405
Vishnu Nair4351ad52019-02-11 14:13:02 -0800406Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800407 if (!reduceTransparentRegion) {
408 return Rect{mScreenBounds};
409 }
410
411 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800412 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800413 // Transform to screen space.
414 bounds = t.transform(bounds);
415 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700416}
417
Vishnu Nair4351ad52019-02-11 14:13:02 -0800418FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000419 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800420 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700421}
422
Vishnu Nairf0c28512019-02-08 12:40:28 -0800423FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
424 // Subtract the transparent region and snap to the bounds.
425 return reduce(mBounds, activeTransparentRegion);
426}
427
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700428void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
429 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800430 const State& s(getDrawingState());
431
432 // Calculate effective layer transform
433 mEffectiveTransform = parentTransform * getActiveTransform(s);
434
Garfield Tan2c1782c2022-02-16 15:25:05 -0800435 if (CC_UNLIKELY(!isTransformValid())) {
436 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
437 getDebugName());
438 return;
439 }
440
Vishnu Nair4351ad52019-02-11 14:13:02 -0800441 // Transform parent bounds to layer space
442 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
443
Vishnu Nairc652ff82019-03-15 12:48:54 -0700444 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800445 mSourceBounds = computeSourceBounds(parentBounds);
446
447 // Calculate bounds by croping diplay frame with layer crop and parent bounds
448 FloatRect bounds = mSourceBounds;
449 const Rect layerCrop = getCrop(s);
450 if (!layerCrop.isEmpty()) {
451 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
452 }
453 bounds = bounds.intersect(parentBounds);
454
455 mBounds = bounds;
456 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700457
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700458 // Use the layer's own shadow radius if set. Otherwise get the radius from
459 // parent.
460 if (s.shadowRadius > 0.f) {
461 mEffectiveShadowRadius = s.shadowRadius;
462 } else {
463 mEffectiveShadowRadius = parentShadowRadius;
464 }
465
466 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
467 // don't pass it to its children.
468 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
469
Vishnu Nair4351ad52019-02-11 14:13:02 -0800470 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700471 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800472 }
Vishnu Nairba354102022-08-01 00:14:18 +0000473
474 if (mPotentialCursor) {
475 prepareCursorCompositionState();
476 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800477}
478
Vishnu Nair60356342018-11-13 13:00:45 -0800479Rect Layer::getCroppedBufferSize(const State& s) const {
480 Rect size = getBufferSize(s);
481 Rect crop = getCrop(s);
482 if (!crop.isEmpty() && size.isValid()) {
483 size.intersect(crop, &size);
484 } else if (!crop.isEmpty()) {
485 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700486 }
Vishnu Nair60356342018-11-13 13:00:45 -0800487 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800488}
489
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700490void Layer::setupRoundedCornersCropCoordinates(Rect win,
491 const FloatRect& roundedCornersCrop) const {
492 // Translate win by the rounded corners rect coordinates, to have all values in
493 // layer coordinate space.
494 win.left -= roundedCornersCrop.left;
495 win.right -= roundedCornersCrop.left;
496 win.top -= roundedCornersCrop.top;
497 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700498}
499
Lloyd Piquede196652020-01-22 17:29:58 -0800500void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800501 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800502 const auto alpha = static_cast<float>(getAlpha());
503 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700504 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800505
506 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
507 if (!opaque || alpha != 1.0f) {
508 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
509 : Hwc2::IComposerClient::BlendMode::COVERAGE;
510 }
511
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000512 auto* snapshot = editLayerSnapshot();
513 snapshot->outputFilter = getOutputFilter();
514 snapshot->isVisible = isVisible();
515 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
516 snapshot->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800517
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000518 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800519 contentDirty = false;
520
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000521 snapshot->geomLayerBounds = mBounds;
522 snapshot->geomLayerTransform = getTransform();
523 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
524 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Lloyd Piquec6687342019-03-07 21:34:57 -0800525
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000526 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
527 snapshot->alpha = alpha;
528 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
529 snapshot->blurRegions = drawingState.blurRegions;
530 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800531}
532
Lloyd Piquede196652020-01-22 17:29:58 -0800533void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800534 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000535 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700536
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000537 snapshot->geomBufferSize = getBufferSize(drawingState);
538 snapshot->geomContentCrop = getBufferCrop();
539 snapshot->geomCrop = getCrop(drawingState);
540 snapshot->geomBufferTransform = getBufferTransform();
541 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
542 snapshot->geomUsesSourceCrop = usesSourceCrop();
543 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800544
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000545 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800546 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
547 for (const auto& [key, mandatory] : supportedMetadata) {
548 const auto& genericLayerMetadataCompatibilityMap =
549 mFlinger->getGenericLayerMetadataKeyMap();
550 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
551 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
552 continue;
553 }
554 const uint32_t id = compatIter->second;
555
556 auto it = drawingState.metadata.mMap.find(id);
557 if (it == std::end(drawingState.metadata.mMap)) {
558 continue;
559 }
560
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000561 snapshot->metadata.emplace(key,
562 compositionengine::GenericLayerMetadataEntry{mandatory,
563 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800564 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800565}
David Sodmanba340492018-08-05 21:51:33 -0700566
Lloyd Piquede196652020-01-22 17:29:58 -0800567void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800568 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000569 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800570
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000571 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800572
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000573 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
574 snapshot->dataspace = getDataSpace();
575 snapshot->colorTransform = getColorTransform();
576 snapshot->colorTransformIsIdentity = !hasColorTransform();
577 snapshot->surfaceDamage = surfaceDamageRegion;
578 snapshot->hasProtectedContent = isProtected();
579 snapshot->dimmingEnabled = isDimmingEnabled();
Lloyd Pique688abd42019-02-15 15:42:24 -0800580
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700581 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700582
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000583 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800584
585 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400586 // Rounded corners no longer force client composition, since we may use a
587 // hole punch so that the layer will appear to have rounded corners.
588 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000589 snapshot->stretchEffect.hasEffect()) {
590 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800591 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700592 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000593 snapshot->blurRegions = drawingState.blurRegions;
594 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400595
596 // Layer framerate is used in caching decisions.
597 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
598 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000599 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000600
601 if (hasBufferOrSidebandStream()) {
602 preparePerFrameBufferCompositionState();
603 } else {
604 preparePerFrameEffectsCompositionState();
605 }
606}
607
608void Layer::preparePerFrameBufferCompositionState() {
609 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000610 auto* snapshot = editLayerSnapshot();
611 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
612 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000613 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
614 return;
615 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000616 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000617 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
618 } else {
619 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000620 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
621 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000622 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
623 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
624 }
625
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000626 snapshot->buffer = getBuffer();
627 snapshot->bufferSlot = (mBufferInfo.mBufferSlot == BufferQueue::INVALID_BUFFER_SLOT)
Patrick Williamsbb25f802022-08-30 23:02:34 +0000628 ? 0
629 : mBufferInfo.mBufferSlot;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000630 snapshot->acquireFence = mBufferInfo.mFence;
631 snapshot->frameNumber = mBufferInfo.mFrameNumber;
632 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000633}
634
635void Layer::preparePerFrameEffectsCompositionState() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000636 auto* snapshot = editLayerSnapshot();
637 snapshot->color = getColor();
638 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000639 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800640}
641
Lloyd Piquede196652020-01-22 17:29:58 -0800642void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800643 const State& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000644 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800645
646 // Apply the layer's transform, followed by the display's global transform
647 // Here we're guaranteed that the layer's transform preserves rects
648 Rect win = getCroppedBufferSize(drawingState);
649 // Subtract the transparent region and snap to the bounds
650 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
651 Rect frame(getTransform().transform(bounds));
652
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000653 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800654}
655
656sp<compositionengine::LayerFE> Layer::asLayerFE() const {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700657 compositionengine::LayerFE* layerFE = const_cast<compositionengine::LayerFE*>(
Lloyd Piquede196652020-01-22 17:29:58 -0800658 static_cast<const compositionengine::LayerFE*>(this));
Ady Abrahamd11bade2022-08-01 16:18:03 -0700659 return sp<compositionengine::LayerFE>::fromExisting(layerFE);
Lloyd Piquede196652020-01-22 17:29:58 -0800660}
661
Lloyd Piquea83776c2019-01-29 18:42:32 -0800662const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700663 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800664}
665
Mathias Agopian13127d82013-03-05 17:47:11 -0800666// ---------------------------------------------------------------------------
667// drawing...
668// ---------------------------------------------------------------------------
669
Vishnu Nair9b079a22020-01-21 14:36:08 -0800670std::optional<compositionengine::LayerFE::LayerSettings> Layer::prepareClientComposition(
Patrick Williams16d8b2c2022-08-08 17:29:05 +0000671 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000672 std::optional<compositionengine::LayerFE::LayerSettings> layerSettings =
673 prepareClientCompositionInternal(targetSettings);
674 // Nothing to render.
675 if (!layerSettings) {
676 return {};
677 }
678
679 // HWC requests to clear this layer.
680 if (targetSettings.clearContent) {
681 prepareClearClientComposition(*layerSettings, false /* blackout */);
682 return layerSettings;
683 }
684
685 // set the shadow for the layer if needed
686 prepareShadowClientComposition(*layerSettings, targetSettings.viewport);
687
688 return layerSettings;
689}
690
691std::optional<compositionengine::LayerFE::LayerSettings> Layer::prepareClientCompositionInternal(
692 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
693 ATRACE_CALL();
694
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000695 const auto* snapshot = getLayerSnapshot();
696 if (!snapshot) {
Lloyd Piquef16688f2019-02-19 17:47:57 -0800697 return {};
698 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800699
Vishnu Nair9b079a22020-01-21 14:36:08 -0800700 compositionengine::LayerFE::LayerSettings layerSettings;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000701 layerSettings.geometry.boundaries =
702 reduce(snapshot->geomLayerBounds, snapshot->transparentRegionHint);
703 layerSettings.geometry.positionTransform = snapshot->geomLayerTransform.asMatrix4();
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000704
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400705 // skip drawing content if the targetSettings indicate the content will be occluded
Ady Abrahambaa6cf52021-07-13 14:02:19 -0700706 const bool drawContent = targetSettings.realContentIsVisible || targetSettings.clearContent;
707 layerSettings.skipContentDraw = !drawContent;
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400708
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000709 if (hasColorTransform()) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000710 layerSettings.colorTransform = snapshot->colorTransform;
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000711 }
712
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000713 const auto& roundedCornerState = snapshot->roundedCorner;
Lloyd Piquef16688f2019-02-19 17:47:57 -0800714 layerSettings.geometry.roundedCornersRadius = roundedCornerState.radius;
715 layerSettings.geometry.roundedCornersCrop = roundedCornerState.cropRect;
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000716
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000717 layerSettings.alpha = snapshot->alpha;
718 layerSettings.sourceDataspace = snapshot->dataspace;
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700719
Alec Mouridda07d92022-04-25 22:39:25 +0000720 // Override the dataspace transfer from 170M to sRGB if the device configuration requests this.
721 // We do this here instead of in buffer info so that dumpsys can still report layers that are
722 // using the 170M transfer.
723 if (mFlinger->mTreat170mAsSrgb &&
724 (layerSettings.sourceDataspace & HAL_DATASPACE_TRANSFER_MASK) ==
725 HAL_DATASPACE_TRANSFER_SMPTE_170M) {
726 layerSettings.sourceDataspace = static_cast<ui::Dataspace>(
727 (layerSettings.sourceDataspace & HAL_DATASPACE_STANDARD_MASK) |
728 (layerSettings.sourceDataspace & HAL_DATASPACE_RANGE_MASK) |
729 HAL_DATASPACE_TRANSFER_SRGB);
730 }
731
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700732 layerSettings.whitePointNits = targetSettings.whitePointNits;
Alec Mourif54453c2021-05-13 16:28:28 -0700733 switch (targetSettings.blurSetting) {
734 case LayerFE::ClientCompositionTargetSettings::BlurSetting::Enabled:
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000735 layerSettings.backgroundBlurRadius = snapshot->backgroundBlurRadius;
736 layerSettings.blurRegions = snapshot->blurRegions;
737 layerSettings.blurRegionTransform = snapshot->geomInverseLayerTransform.asMatrix4();
Alec Mourif54453c2021-05-13 16:28:28 -0700738 break;
739 case LayerFE::ClientCompositionTargetSettings::BlurSetting::BackgroundBlurOnly:
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000740 layerSettings.backgroundBlurRadius = snapshot->backgroundBlurRadius;
Alec Mourif54453c2021-05-13 16:28:28 -0700741 break;
742 case LayerFE::ClientCompositionTargetSettings::BlurSetting::BlurRegionsOnly:
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000743 layerSettings.blurRegions = snapshot->blurRegions;
744 layerSettings.blurRegionTransform = snapshot->geomInverseLayerTransform.asMatrix4();
Alec Mourif54453c2021-05-13 16:28:28 -0700745 break;
746 case LayerFE::ClientCompositionTargetSettings::BlurSetting::Disabled:
747 default:
748 break;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +0100749 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000750 layerSettings.stretchEffect = snapshot->stretchEffect;
Ana Krulec6eab17a2020-12-09 15:52:36 -0800751 // Record the name of the layer for debugging further down the stack.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000752 layerSettings.name = snapshot->name;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000753
Vishnu Nairf115db82022-09-06 16:59:33 -0700754 if (hasEffect() && !hasBufferOrSidebandStream()) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000755 prepareEffectsClientComposition(layerSettings, targetSettings);
756 return layerSettings;
757 }
758
759 prepareBufferStateClientComposition(layerSettings, targetSettings);
Lloyd Piquef16688f2019-02-19 17:47:57 -0800760 return layerSettings;
Mathias Agopian13127d82013-03-05 17:47:11 -0800761}
762
Vishnu Nairb87d94f2020-02-13 09:17:36 -0800763void Layer::prepareClearClientComposition(LayerFE::LayerSettings& layerSettings,
764 bool blackout) const {
765 layerSettings.source.buffer.buffer = nullptr;
766 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
767 layerSettings.disableBlending = true;
Vishnu Nair3b653e72020-02-24 16:40:50 -0800768 layerSettings.bufferId = 0;
Vishnu Nairb87d94f2020-02-13 09:17:36 -0800769 layerSettings.frameNumber = 0;
770
771 // If layer is blacked out, force alpha to 1 so that we draw a black color layer.
772 layerSettings.alpha = blackout ? 1.0f : 0.0f;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000773 layerSettings.name = getLayerSnapshot()->name;
Vishnu Nairb87d94f2020-02-13 09:17:36 -0800774}
775
Patrick Williamsbb25f802022-08-30 23:02:34 +0000776void Layer::prepareEffectsClientComposition(
777 compositionengine::LayerFE::LayerSettings& layerSettings,
778 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
779 // If fill bounds are occluded or the fill color is invalid skip the fill settings.
780 if (targetSettings.realContentIsVisible && fillsColor()) {
781 // Set color for color fill settings.
782 layerSettings.source.solidColor = getColor().rgb;
783 } else if (hasBlur() || drawShadows()) {
784 layerSettings.skipContentDraw = true;
785 }
786}
787
788void Layer::prepareBufferStateClientComposition(
789 compositionengine::LayerFE::LayerSettings& layerSettings,
790 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000791 ATRACE_CALL();
792 const auto* snapshot = getLayerSnapshot();
793 if (CC_UNLIKELY(!snapshot->externalTexture)) {
794 // If there is no buffer for the layer or we have sidebandstream where there is no
795 // activeBuffer, then we need to return LayerSettings.
Patrick Williamsbb25f802022-08-30 23:02:34 +0000796 return;
797 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000798 const bool blackOutLayer =
799 (snapshot->hasProtectedContent && !targetSettings.supportsProtectedContent) ||
800 ((snapshot->isSecure || snapshot->hasProtectedContent) && !targetSettings.isSecure);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000801 const bool bufferCanBeUsedAsHwTexture =
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000802 snapshot->externalTexture->getUsage() & GraphicBuffer::USAGE_HW_TEXTURE;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000803 if (blackOutLayer || !bufferCanBeUsedAsHwTexture) {
804 ALOGE_IF(!bufferCanBeUsedAsHwTexture, "%s is blacked out as buffer is not gpu readable",
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000805 snapshot->name.c_str());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000806 prepareClearClientComposition(layerSettings, true /* blackout */);
807 return;
808 }
809
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000810 layerSettings.source.buffer.buffer = snapshot->externalTexture;
811 layerSettings.source.buffer.isOpaque = snapshot->contentOpaque;
812 layerSettings.source.buffer.fence = snapshot->acquireFence;
813 layerSettings.source.buffer.textureName = snapshot->textureName;
814 layerSettings.source.buffer.usePremultipliedAlpha = snapshot->premultipliedAlpha;
815 layerSettings.source.buffer.isY410BT2020 = snapshot->isHdrY410;
816 bool hasSmpte2086 = snapshot->hdrMetadata.validTypes & HdrMetadata::SMPTE2086;
817 bool hasCta861_3 = snapshot->hdrMetadata.validTypes & HdrMetadata::CTA861_3;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000818 float maxLuminance = 0.f;
819 if (hasSmpte2086 && hasCta861_3) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000820 maxLuminance = std::min(snapshot->hdrMetadata.smpte2086.maxLuminance,
821 snapshot->hdrMetadata.cta8613.maxContentLightLevel);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000822 } else if (hasSmpte2086) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000823 maxLuminance = snapshot->hdrMetadata.smpte2086.maxLuminance;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000824 } else if (hasCta861_3) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000825 maxLuminance = snapshot->hdrMetadata.cta8613.maxContentLightLevel;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000826 } else {
827 switch (layerSettings.sourceDataspace & HAL_DATASPACE_TRANSFER_MASK) {
828 case HAL_DATASPACE_TRANSFER_ST2084:
829 case HAL_DATASPACE_TRANSFER_HLG:
830 // Behavior-match previous releases for HDR content
831 maxLuminance = defaultMaxLuminance;
832 break;
833 }
834 }
835 layerSettings.source.buffer.maxLuminanceNits = maxLuminance;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000836 layerSettings.frameNumber = snapshot->frameNumber;
837 layerSettings.bufferId = snapshot->externalTexture->getId();
Patrick Williamsbb25f802022-08-30 23:02:34 +0000838
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000839 const bool useFiltering = targetSettings.needsFiltering ||
840 snapshot->geomLayerTransform.needsBilinearFiltering() || snapshot->bufferNeedsFiltering;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000841
842 // Query the texture matrix given our current filtering mode.
843 float textureMatrix[16];
844 getDrawingTransformMatrix(useFiltering, textureMatrix);
845
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000846 if (snapshot->geomBufferUsesDisplayInverseTransform) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000847 /*
848 * the code below applies the primary display's inverse transform to
849 * the texture transform
850 */
851 uint32_t transform = DisplayDevice::getPrimaryDisplayRotationFlags();
852 mat4 tr = inverseOrientation(transform);
853
854 /**
855 * TODO(b/36727915): This is basically a hack.
856 *
857 * Ensure that regardless of the parent transformation,
858 * this buffer is always transformed from native display
859 * orientation to display orientation. For example, in the case
860 * of a camera where the buffer remains in native orientation,
861 * we want the pixels to always be upright.
862 */
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000863 const auto parentTransform = snapshot->transform;
864 tr = tr * inverseOrientation(parentTransform.getOrientation());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000865
866 // and finally apply it to the original texture matrix
867 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
868 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
869 }
870
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000871 const Rect win{layerSettings.geometry.boundaries};
872 float bufferWidth = snapshot->bufferSize.getWidth();
873 float bufferHeight = snapshot->bufferSize.getHeight();
Patrick Williamsbb25f802022-08-30 23:02:34 +0000874
Patrick Williams83f36b22022-09-14 17:57:35 +0000875 // Layers can have a "buffer size" of [0, 0, -1, -1] when no display frame has
Patrick Williamsbb25f802022-08-30 23:02:34 +0000876 // been set and there is no parent layer bounds. In that case, the scale is meaningless so
877 // ignore them.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000878 if (!snapshot->bufferSize.isValid()) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000879 bufferWidth = float(win.right) - float(win.left);
880 bufferHeight = float(win.bottom) - float(win.top);
881 }
882
883 const float scaleHeight = (float(win.bottom) - float(win.top)) / bufferHeight;
884 const float scaleWidth = (float(win.right) - float(win.left)) / bufferWidth;
885 const float translateY = float(win.top) / bufferHeight;
886 const float translateX = float(win.left) / bufferWidth;
887
888 // Flip y-coordinates because GLConsumer expects OpenGL convention.
889 mat4 tr = mat4::translate(vec4(.5f, .5f, 0.f, 1.f)) * mat4::scale(vec4(1.f, -1.f, 1.f, 1.f)) *
890 mat4::translate(vec4(-.5f, -.5f, 0.f, 1.f)) *
891 mat4::translate(vec4(translateX, translateY, 0.f, 1.f)) *
892 mat4::scale(vec4(scaleWidth, scaleHeight, 1.0f, 1.0f));
893
894 layerSettings.source.buffer.useTextureFiltering = useFiltering;
895 layerSettings.source.buffer.textureTransform =
896 mat4(static_cast<const float*>(textureMatrix)) * tr;
897
898 return;
899}
900
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500901aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
902 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700903 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800904 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500905 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800906 }
907 if (outputLayer->getState().hwc) {
908 return (*outputLayer->getState().hwc).hwcCompositionType;
909 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500910 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800911 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800912}
913
Mathias Agopian13127d82013-03-05 17:47:11 -0800914// ----------------------------------------------------------------------------
915// local state
916// ----------------------------------------------------------------------------
917
David Sodman41fdfc92017-11-06 16:09:56 -0800918bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800919 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700920 if (s.flags & layer_state_t::eLayerSecure) {
921 return true;
922 }
923
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000924 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700925 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700926}
927
Mathias Agopian13127d82013-03-05 17:47:11 -0800928// ----------------------------------------------------------------------------
929// transaction
930// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800931
Marissa Wall61c58622018-07-18 10:12:20 -0700932uint32_t Layer::doTransaction(uint32_t flags) {
933 ATRACE_CALL();
934
Robert Carr0758e5d2021-03-11 22:15:04 -0800935 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700936 mDrawingStateModified = mDrawingState.modified;
937 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700938
Alec Mourib416efd2018-09-06 21:01:59 +0000939 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700940
Robert Carr6a160312021-05-17 12:08:20 -0700941 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800942 // invalidate and recompute the visible regions if needed
943 flags |= Layer::eVisibleRegion;
944 }
945
Robert Carr6a160312021-05-17 12:08:20 -0700946 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800947 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000948 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800949 flags |= eVisibleRegion;
950 this->contentDirty = true;
951
952 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700953 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800954 }
955
Arthur Hung9ed43392022-05-27 06:31:57 +0000956 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
957 mFlinger->mUpdateInputInfo = true;
958 }
959
Robert Carr6a160312021-05-17 12:08:20 -0700960 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800961
Mathias Agopian13127d82013-03-05 17:47:11 -0800962 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800963}
964
Robert Carr6a160312021-05-17 12:08:20 -0700965void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000966 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
967 // bufferSurfaceFrameTX will be presented in latchBuffer.
968 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
969 if (surfaceFrame->getPresentState() != PresentState::Presented) {
970 // With applyPendingStates, we could end up having presented surfaceframes from previous
971 // states
972 surfaceFrame->setPresentState(PresentState::Presented);
973 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
974 }
975 }
Robert Carr6a160312021-05-17 12:08:20 -0700976 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700977}
978
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700979uint32_t Layer::clearTransactionFlags(uint32_t mask) {
980 const auto flags = mTransactionFlags & mask;
981 mTransactionFlags &= ~mask;
982 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800983}
984
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700985void Layer::setTransactionFlags(uint32_t mask) {
986 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800987}
988
Robert Carr1f0a16a2016-10-24 16:27:39 -0700989bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
990 ssize_t idx = mCurrentChildren.indexOf(childLayer);
991 if (idx < 0) {
992 return false;
993 }
994 if (childLayer->setLayer(z)) {
995 mCurrentChildren.removeAt(idx);
996 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800997 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700998 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800999 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001000}
1001
Robert Carr503c7042017-09-27 15:06:08 -07001002bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
1003 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
1004 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1005 if (idx < 0) {
1006 return false;
1007 }
1008 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
1009 mCurrentChildren.removeAt(idx);
1010 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -08001011 return true;
Robert Carr503c7042017-09-27 15:06:08 -07001012 }
Robert Carr503d2bd2017-12-04 15:49:47 -08001013 return false;
Robert Carr503c7042017-09-27 15:06:08 -07001014}
1015
Robert Carrae060832016-11-28 10:51:00 -08001016bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -07001017 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
1018 mDrawingState.sequence++;
1019 mDrawingState.z = z;
1020 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001021
Robert Carra70e91c2021-06-11 13:59:52 -07001022 mFlinger->mSomeChildrenChanged = true;
1023
Robert Carrdb66e622017-04-10 16:55:57 -07001024 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -07001025 if (mDrawingState.zOrderRelativeOf != nullptr) {
1026 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -07001027 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001028 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -07001029 }
chaviw606e5cf2019-03-01 10:12:10 -08001030 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -07001031 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001032 setTransactionFlags(eTransactionNeeded);
1033 return true;
1034}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001035
Robert Carrdb66e622017-04-10 16:55:57 -07001036void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -07001037 mDrawingState.zOrderRelatives.remove(relative);
1038 mDrawingState.sequence++;
1039 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001040 setTransactionFlags(eTransactionNeeded);
1041}
1042
1043void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -07001044 mDrawingState.zOrderRelatives.add(relative);
1045 mDrawingState.modified = true;
1046 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -07001047 setTransactionFlags(eTransactionNeeded);
1048}
1049
chaviw606e5cf2019-03-01 10:12:10 -08001050void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -07001051 mDrawingState.zOrderRelativeOf = relativeOf;
1052 mDrawingState.sequence++;
1053 mDrawingState.modified = true;
1054 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -07001055
chaviw606e5cf2019-03-01 10:12:10 -08001056 setTransactionFlags(eTransactionNeeded);
1057}
1058
Robert Carr503d2bd2017-12-04 15:49:47 -08001059bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nairf9096652021-07-20 18:49:42 -07001060 sp<Layer> relative = fromHandle(relativeToHandle).promote();
Robert Carrdb66e622017-04-10 16:55:57 -07001061 if (relative == nullptr) {
1062 return false;
1063 }
1064
Robert Carr6a160312021-05-17 12:08:20 -07001065 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
1066 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -08001067 return false;
1068 }
1069
Robert Carr88b85e12022-03-21 15:47:35 -07001070 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
1071 (relative->mDrawingState.zOrderRelativeOf == this)) {
1072 ALOGE("Detected relative layer loop between %s and %s",
1073 mName.c_str(), relative->mName.c_str());
1074 ALOGE("Ignoring new call to set relative layer");
1075 return false;
1076 }
1077
Robert Carra70e91c2021-06-11 13:59:52 -07001078 mFlinger->mSomeChildrenChanged = true;
1079
Robert Carr6a160312021-05-17 12:08:20 -07001080 mDrawingState.sequence++;
1081 mDrawingState.modified = true;
1082 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -07001083
Robert Carr6a160312021-05-17 12:08:20 -07001084 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -07001085 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001086 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -07001087 }
chaviw606e5cf2019-03-01 10:12:10 -08001088 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001089 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -07001090
1091 setTransactionFlags(eTransactionNeeded);
1092
1093 return true;
1094}
1095
Winson Chunga30f7c92021-06-29 15:42:56 -07001096bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
1097 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
1098 mDrawingState.isTrustedOverlay = isTrustedOverlay;
1099 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00001100 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -07001101 setTransactionFlags(eTransactionNeeded);
1102 return true;
1103}
1104
1105bool Layer::isTrustedOverlay() const {
1106 if (getDrawingState().isTrustedOverlay) {
1107 return true;
1108 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001109 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -07001110 return (p != nullptr) && p->isTrustedOverlay();
1111}
1112
Dan Stoza9e56aa02015-11-02 13:00:03 -08001113bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -07001114 if (mDrawingState.color.a == alpha) return false;
1115 mDrawingState.sequence++;
1116 mDrawingState.color.a = alpha;
1117 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001118 setTransactionFlags(eTransactionNeeded);
1119 return true;
1120}
chaviw13fdc492017-06-27 12:40:18 -07001121
Valerie Haudd0b7572019-01-29 14:59:27 -08001122bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -07001123 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -07001124 return false;
Valerie Hauaa194562019-02-05 16:21:38 -08001125 }
Robert Carr6a160312021-05-17 12:08:20 -07001126 mDrawingState.sequence++;
1127 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -08001128 setTransactionFlags(eTransactionNeeded);
1129
Robert Carr6a160312021-05-17 12:08:20 -07001130 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001131 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001132 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001133 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001134 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08001135 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001136 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001137
Valerie Haudd0b7572019-01-29 14:59:27 -08001138 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001139 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001140 mFlinger->mLayersAdded = true;
1141 // set up SF to handle added color layer
1142 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -07001143 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001144 }
1145 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001146 } else if (mDrawingState.bgColorLayer && alpha == 0) {
1147 mDrawingState.bgColorLayer->reparent(nullptr);
1148 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001149 return true;
1150 }
1151
Robert Carr6a160312021-05-17 12:08:20 -07001152 mDrawingState.bgColorLayer->setColor(color);
1153 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1154 mDrawingState.bgColorLayer->setAlpha(alpha);
1155 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001156
chaviw13fdc492017-06-27 12:40:18 -07001157 return true;
1158}
1159
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001160bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001161 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001162
Robert Carr6a160312021-05-17 12:08:20 -07001163 mDrawingState.sequence++;
1164 mDrawingState.cornerRadius = cornerRadius;
1165 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001166 setTransactionFlags(eTransactionNeeded);
1167 return true;
1168}
1169
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001170bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001171 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001172 // If we start or stop drawing blur then the layer's visibility state may change so increment
1173 // the magic sequence number.
1174 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1175 mDrawingState.sequence++;
1176 }
Robert Carr6a160312021-05-17 12:08:20 -07001177 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1178 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001179 setTransactionFlags(eTransactionNeeded);
1180 return true;
1181}
Marissa Wall61c58622018-07-18 10:12:20 -07001182
Mathias Agopian13127d82013-03-05 17:47:11 -08001183bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001184 mDrawingState.sequence++;
1185 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001186 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001187 setTransactionFlags(eTransactionNeeded);
1188 return true;
1189}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001190
Lucas Dupinc3800b82020-10-02 16:24:48 -07001191bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001192 // If we start or stop drawing blur then the layer's visibility state may change so increment
1193 // the magic sequence number.
1194 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1195 mDrawingState.sequence++;
1196 }
Robert Carr6a160312021-05-17 12:08:20 -07001197 mDrawingState.blurRegions = blurRegions;
1198 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001199 setTransactionFlags(eTransactionNeeded);
1200 return true;
1201}
1202
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001203bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001204 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1205 if (mDrawingState.flags == newFlags) return false;
1206 mDrawingState.sequence++;
1207 mDrawingState.flags = newFlags;
1208 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001209 setTransactionFlags(eTransactionNeeded);
1210 return true;
1211}
Robert Carr99e27f02016-06-16 15:18:02 -07001212
chaviw25714502021-02-11 10:01:08 -08001213bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001214 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001215 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001216 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001217
Robert Carr6a160312021-05-17 12:08:20 -07001218 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001219 setTransactionFlags(eTransactionNeeded);
1220 return true;
1221}
Robert Carr8d5227b2017-03-16 15:41:03 -07001222
Evan Roskyef876c92019-01-25 17:46:06 -08001223bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001224 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1225 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001226 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001227 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001228}
1229
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001230bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001231 if (mDrawingState.layerStack == layerStack) return false;
1232 mDrawingState.sequence++;
1233 mDrawingState.layerStack = layerStack;
1234 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001235 setTransactionFlags(eTransactionNeeded);
1236 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001237}
1238
Peiyong Linc502cb72019-03-01 15:00:23 -08001239bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001240 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001241 return false;
1242 }
Robert Carr6a160312021-05-17 12:08:20 -07001243 mDrawingState.sequence++;
1244 mDrawingState.colorSpaceAgnostic = agnostic;
1245 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001246 setTransactionFlags(eTransactionNeeded);
1247 return true;
1248}
1249
Sally Qi81d95e62022-03-21 19:41:33 -07001250bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1251 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1252
1253 mDrawingState.sequence++;
1254 mDrawingState.dimmingEnabled = dimmingEnabled;
1255 mDrawingState.modified = true;
1256 setTransactionFlags(eTransactionNeeded);
1257 return true;
1258}
1259
Ana Krulecc84d09b2019-11-02 23:10:29 +01001260bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001261 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1262 mDrawingState.frameRateSelectionPriority = priority;
1263 mDrawingState.sequence++;
1264 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001265 setTransactionFlags(eTransactionNeeded);
1266 return true;
1267}
1268
1269int32_t Layer::getFrameRateSelectionPriority() const {
1270 // Check if layer has priority set.
1271 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1272 return mDrawingState.frameRateSelectionPriority;
1273 }
1274 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001275 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001276 if (parent != nullptr) {
1277 return parent->getFrameRateSelectionPriority();
1278 }
1279
1280 return Layer::PRIORITY_UNSET;
1281}
1282
Andy Labrada096227e2022-06-15 16:58:11 +00001283bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1284 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1285 mDrawingState.defaultFrameRateCompatibility = compatibility;
1286 mDrawingState.modified = true;
1287 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1288 setTransactionFlags(eTransactionNeeded);
1289 return true;
1290}
1291
1292scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1293 return mDrawingState.defaultFrameRateCompatibility;
1294}
1295
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001296bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1297 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1298};
1299
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001300ui::LayerStack Layer::getLayerStack() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001301 if (const auto parent = mDrawingParent.promote()) {
1302 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001303 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001304 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001305}
1306
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001307bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001308 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001309 return false;
1310 }
1311
Robert Carr6a160312021-05-17 12:08:20 -07001312 mDrawingState.sequence++;
1313 mDrawingState.shadowRadius = shadowRadius;
1314 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001315 setTransactionFlags(eTransactionNeeded);
1316 return true;
1317}
1318
Vishnu Nair6213bd92020-05-08 17:42:25 -07001319bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001320 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001321 return false;
1322 }
1323
Robert Carr6a160312021-05-17 12:08:20 -07001324 mDrawingState.sequence++;
1325 mDrawingState.fixedTransformHint = fixedTransformHint;
1326 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001327 setTransactionFlags(eTransactionNeeded);
1328 return true;
1329}
1330
John Reckcdb4ed72021-02-04 13:39:33 -05001331bool Layer::setStretchEffect(const StretchEffect& effect) {
1332 StretchEffect temp = effect;
1333 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001334 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001335 return false;
1336 }
Robert Carr6a160312021-05-17 12:08:20 -07001337 mDrawingState.sequence++;
1338 mDrawingState.stretchEffect = temp;
1339 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001340 setTransactionFlags(eTransactionNeeded);
1341 return true;
1342}
1343
John Reckc00c6692021-02-16 11:37:33 -05001344StretchEffect Layer::getStretchEffect() const {
1345 if (mDrawingState.stretchEffect.hasEffect()) {
1346 return mDrawingState.stretchEffect;
1347 }
1348
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001349 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001350 if (parent != nullptr) {
1351 auto effect = parent->getStretchEffect();
1352 if (effect.hasEffect()) {
1353 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1354 return effect;
1355 }
1356 }
1357 return StretchEffect{};
1358}
1359
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001360bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1361 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001362 return false;
1363 }
1364 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001365 mBorderWidth = width;
1366 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001367 return true;
1368}
1369
1370bool Layer::isBorderEnabled() {
1371 return mBorderEnabled;
1372}
1373
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001374float Layer::getBorderWidth() {
1375 return mBorderWidth;
1376}
1377
1378const half4& Layer::getBorderColor() {
1379 return mBorderColor;
1380}
1381
Ady Abrahama850c182021-08-04 13:04:37 -07001382bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1383 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1384 const auto frameRate = [&] {
1385 if (mDrawingState.frameRate.rate.isValid() ||
1386 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1387 return mDrawingState.frameRate;
1388 }
1389
1390 return parentFrameRate;
1391 }();
1392
1393 *transactionNeeded |= setFrameRateForLayerTree(frameRate);
1394
1395 // The frame rate is propagated to the children
1396 bool childrenHaveFrameRate = false;
1397 for (const sp<Layer>& child : mCurrentChildren) {
1398 childrenHaveFrameRate |=
1399 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1400 }
1401
1402 // If we don't have a valid frame rate, but the children do, we set this
1403 // layer as NoVote to allow the children to control the refresh rate
1404 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1405 childrenHaveFrameRate) {
1406 *transactionNeeded |=
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001407 setFrameRateForLayerTree(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001408 }
1409
1410 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1411 // the same reason we are allowing touch boost for those layers. See
1412 // RefreshRateConfigs::getBestRefreshRate for more details.
1413 const auto layerVotedWithDefaultCompatibility =
1414 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1415 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1416 const auto layerVotedWithExactCompatibility =
1417 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1418 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1419 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1420}
1421
Ady Abraham60e42ea2020-03-09 19:17:31 -07001422void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001423 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001424 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001425 while (auto parent = layer->getParent()) {
1426 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001427 }
Ady Abrahama850c182021-08-04 13:04:37 -07001428 return layer;
1429 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001430
Ady Abraham60e42ea2020-03-09 19:17:31 -07001431 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001432 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001433
Ady Abrahama850c182021-08-04 13:04:37 -07001434 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001435 if (transactionNeeded) {
1436 mFlinger->setTransactionFlags(eTraversalNeeded);
1437 }
1438}
1439
Ady Abraham71c437d2020-01-31 15:56:57 -08001440bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001441 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001442 return false;
1443 }
1444
Robert Carr6a160312021-05-17 12:08:20 -07001445 mDrawingState.sequence++;
1446 mDrawingState.frameRate = frameRate;
1447 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001448
1449 updateTreeHasFrameRateVote();
1450
Steven Thomas3172e202020-01-06 19:25:30 -08001451 setTransactionFlags(eTransactionNeeded);
1452 return true;
1453}
1454
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001455void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1456 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001457 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001458
1459 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1460 // there are two transactions with the same token, the first one without a buffer and the
1461 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1462 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001463 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1464 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001465 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001466 mDrawingState.bufferSurfaceFrameTX = it->second;
1467 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1468 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1469 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001470 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001471 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001472 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1473 }
1474}
1475
1476void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1477 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001478 mDrawingState.frameTimelineInfo = info;
1479 mDrawingState.postTime = postTime;
1480 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001481 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001482
Robert Carr6a160312021-05-17 12:08:20 -07001483 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001484 bufferSurfaceFrameTX != nullptr) {
1485 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1486 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1487 // being used for BufferSurfaceFrame, don't create a new one.
1488 return;
1489 }
1490 }
1491 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1492 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1493 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001494 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1495 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001496 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001497 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001498 } else {
1499 if (it->second->getPresentState() == PresentState::Presented) {
1500 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1501 // have been from previous vsync.
1502 it->second = createSurfaceFrameForTransaction(info, postTime);
1503 }
1504 }
1505}
1506
1507void Layer::addSurfaceFrameDroppedForBuffer(
1508 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001509 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001510 surfaceFrame->setPresentState(PresentState::Dropped);
1511 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1512}
1513
1514void Layer::addSurfaceFramePresentedForBuffer(
1515 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1516 nsecs_t currentLatchTime) {
1517 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1518 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1519 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1520 mLastLatchTime = currentLatchTime;
1521}
1522
1523std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1524 const FrameTimelineInfo& info, nsecs_t postTime) {
1525 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001526 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1527 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001528 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001529 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001530 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001531 // For Transactions, the post time is considered to be both queue and acquire fence time.
1532 surfaceFrame->setActualQueueTime(postTime);
1533 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001534 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1535 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001536 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001537 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001538 onSurfaceFrameCreated(surfaceFrame);
1539 return surfaceFrame;
1540}
1541
1542std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1543 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1544 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001545 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001546 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001547 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001548 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001549 // For buffers, acquire fence time will set during latch.
1550 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001551 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1552 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001553 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001554 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001555 // TODO(b/178542907): Implement onSurfaceFrameCreated for BQLayer as well.
1556 onSurfaceFrameCreated(surfaceFrame);
1557 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001558}
1559
Ady Abrahama850c182021-08-04 13:04:37 -07001560bool Layer::setFrameRateForLayerTree(FrameRate frameRate) {
1561 if (mDrawingState.frameRateForLayerTree == frameRate) {
1562 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001563 }
1564
Ady Abrahama850c182021-08-04 13:04:37 -07001565 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001566
Ady Abrahama850c182021-08-04 13:04:37 -07001567 // TODO(b/195668952): we probably don't need to dirty visible regions here
1568 // or even store frameRateForLayerTree in mDrawingState
1569 mDrawingState.sequence++;
1570 mDrawingState.modified = true;
1571 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001572
Dominik Laskowski068173d2021-08-11 17:22:59 -07001573 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
1574 mFlinger->mScheduler->recordLayerHistory(this, systemTime(), LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001575
1576 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001577}
1578
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001579Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1580 return getDrawingState().frameRateForLayerTree;
1581}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001582
Robert Carr1f0a16a2016-10-24 16:27:39 -07001583bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001584 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001585 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001586 if (parent != nullptr && parent->isHiddenByPolicy()) {
1587 return true;
1588 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001589 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1590 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1591 if (zOrderRelativeOf != nullptr) {
1592 if (zOrderRelativeOf->isHiddenByPolicy()) {
1593 return true;
1594 }
1595 }
1596 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001597 if (CC_UNLIKELY(!isTransformValid())) {
1598 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1599 return true;
1600 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001601 return s.flags & layer_state_t::eLayerHidden;
1602}
1603
David Sodman41fdfc92017-11-06 16:09:56 -08001604uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001605 // TODO: should we do something special if mSecure is set?
1606 if (mProtectedByApp) {
1607 // need a hardware-protected path to external video sink
1608 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001609 }
Riley Andrews03414a12014-07-01 14:22:59 -07001610 if (mPotentialCursor) {
1611 usage |= GraphicBuffer::USAGE_CURSOR;
1612 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001613 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001614 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001615}
1616
Vishnu Nair71fcf912022-10-18 09:14:20 -07001617void Layer::skipReportingTransformHint() {
1618 mSkipReportingTransformHint = true;
1619}
1620
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001621void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1622 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1623 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001624 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001625
Vishnu Nair6213bd92020-05-08 17:42:25 -07001626 setTransformHint(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001627}
1628
Mathias Agopian13127d82013-03-05 17:47:11 -08001629// ----------------------------------------------------------------------------
1630// debugging
1631// ----------------------------------------------------------------------------
1632
Marissa Wall61c58622018-07-18 10:12:20 -07001633// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001634gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001635 using namespace std::string_literals;
1636
Huihong Luo05539a12022-02-23 10:29:40 -08001637 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001638 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001639 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001640 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001641 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001642 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001643
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001644 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001645 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001646 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001647 info.mX = ds.transform.tx();
1648 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001649 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001650 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001651 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001652 info.mFlags = ds.flags;
1653 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001654 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001655 info.mMatrix[0][0] = ds.transform[0][0];
1656 info.mMatrix[0][1] = ds.transform[0][1];
1657 info.mMatrix[1][0] = ds.transform[1][0];
1658 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001659 {
chaviwd62d3062019-09-04 14:48:02 -07001660 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001661 if (buffer != 0) {
1662 info.mActiveBufferWidth = buffer->getWidth();
1663 info.mActiveBufferHeight = buffer->getHeight();
1664 info.mActiveBufferStride = buffer->getStride();
1665 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001666 } else {
1667 info.mActiveBufferWidth = 0;
1668 info.mActiveBufferHeight = 0;
1669 info.mActiveBufferStride = 0;
1670 info.mActiveBufferFormat = 0;
1671 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001672 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001673 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001674 info.mIsOpaque = isOpaque(ds);
1675 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001676 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001677 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001678}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001679
Yiwei Zhang5434a782018-12-05 18:06:32 -08001680void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001681 result.append(kDumpTableRowLength, '-');
1682 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001683 result.append(" Layer name\n");
1684 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001685 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001686 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001687 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001688 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001689 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001690 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1691 result.append(kDumpTableRowLength, '-');
1692 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001693}
1694
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001695void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1696 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001697 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001698 return;
1699 }
1700
Yiwei Zhang5434a782018-12-05 18:06:32 -08001701 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001702 if (mName.length() > 77) {
1703 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001704 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001705 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001706 shortened.append(mName, mName.length() - 36);
1707 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001708 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001709 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001710 }
1711
Yiwei Zhang5434a782018-12-05 18:06:32 -08001712 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001713
Alec Mourib416efd2018-09-06 21:01:59 +00001714 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001715 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001716
Chia-I Wu1e043612018-03-01 09:45:09 -08001717 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001718 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001719 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001720 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001721 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001722 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001723 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001724 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1725 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001726 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001727 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001728 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001729 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001730 const auto frameRate = getFrameRateForLayerTree();
1731 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1732 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001733 ftl::enum_string(frameRate.type).c_str(),
1734 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001735 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001736 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001737 }
Dan Stozae22aec72016-08-01 13:20:59 -07001738
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001739 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1740 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1741
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001742 result.append(kDumpTableRowLength, '-');
1743 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001744}
Dan Stozae22aec72016-08-01 13:20:59 -07001745
Yiwei Zhang5434a782018-12-05 18:06:32 -08001746void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001747 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001748}
1749
Svetoslavd85084b2014-03-20 10:28:31 -07001750void Layer::clearFrameStats() {
1751 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001752}
1753
Jamie Gennis6547ff42013-07-16 20:12:42 -07001754void Layer::logFrameStats() {
1755 mFrameTracker.logAndResetStats(mName);
1756}
1757
Svetoslavd85084b2014-03-20 10:28:31 -07001758void Layer::getFrameStats(FrameStats* outStats) const {
1759 mFrameTracker.getStats(outStats);
1760}
1761
Vishnu Nair0f085c62019-08-30 08:49:12 -07001762void Layer::dumpCallingUidPid(std::string& result) const {
chaviw250bcbb2020-08-05 11:17:54 -07001763 StringAppendF(&result, "Layer %s (%s) callingPid:%d callingUid:%d ownerUid:%d\n",
1764 getName().c_str(), getType(), mCallingPid, mCallingUid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001765}
1766
Brian Anderson5ea5e592016-12-01 16:54:33 -08001767void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001768 const int32_t layerId = getSequence();
1769 mFlinger->mTimeStats->onDestroy(layerId);
1770 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001771}
1772
Chia-I Wu98f1c102017-05-30 14:54:08 -07001773size_t Layer::getChildrenCount() const {
1774 size_t count = 0;
1775 for (const sp<Layer>& child : mCurrentChildren) {
1776 count += 1 + child->getChildrenCount();
1777 }
1778 return count;
1779}
1780
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001781void Layer::setGameModeForTree(GameMode gameMode) {
1782 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001783 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1784 gameMode =
1785 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001786 }
1787 setGameMode(gameMode);
1788 for (const sp<Layer>& child : mCurrentChildren) {
1789 child->setGameModeForTree(gameMode);
1790 }
1791}
1792
Robert Carr1f0a16a2016-10-24 16:27:39 -07001793void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001794 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001795 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001796
Robert Carr1f0a16a2016-10-24 16:27:39 -07001797 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001798 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001799 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001800 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001801}
1802
1803ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001804 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001805 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001806
Robert Carr1323c952019-01-28 18:13:27 -08001807 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001808 const auto removeResult = mCurrentChildren.remove(layer);
1809
1810 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001811 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001812 layer->updateTreeHasFrameRateVote();
1813
1814 return removeResult;
1815}
1816
Robert Carr15eae092018-03-23 13:43:53 -07001817void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001818 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001819 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001820 const float parentShadowRadius =
1821 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001822 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001823 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001824 }
1825}
1826
chaviwf1961f72017-09-18 16:41:07 -07001827bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001828 sp<Layer> newParent;
1829 if (newParentHandle != nullptr) {
Vishnu Nairf9096652021-07-20 18:49:42 -07001830 newParent = fromHandle(newParentHandle).promote();
Robert Carr54cf5b12019-01-25 14:02:28 -08001831 if (newParent == nullptr) {
1832 ALOGE("Unable to promote Layer handle");
1833 return false;
1834 }
1835 if (newParent == this) {
1836 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1837 return false;
1838 }
1839 }
1840
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001841 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001842 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001843 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001844 }
1845
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001846 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001847 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001848 if (!newParent->isRemovedFromCurrentState()) {
1849 addToCurrentState();
1850 } else {
1851 onRemovedFromCurrentState();
1852 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001853 } else {
1854 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001855 }
1856
chaviw06178942017-07-27 10:25:59 -07001857 return true;
1858}
1859
Peiyong Lind3788632018-09-18 16:01:31 -07001860bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001861 static const mat4 identityMatrix = mat4();
1862
Robert Carr6a160312021-05-17 12:08:20 -07001863 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001864 return false;
1865 }
Robert Carr6a160312021-05-17 12:08:20 -07001866 ++mDrawingState.sequence;
1867 mDrawingState.colorTransform = matrix;
1868 mDrawingState.hasColorTransform = matrix != identityMatrix;
1869 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001870 setTransactionFlags(eTransactionNeeded);
1871 return true;
1872}
1873
chaviwf66724d2018-11-28 16:35:21 -08001874mat4 Layer::getColorTransform() const {
1875 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001876 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001877 colorTransform = parent->getColorTransform() * colorTransform;
1878 }
1879 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001880}
1881
1882bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001883 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001884 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001885 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1886 }
1887 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001888}
1889
Chia-I Wu11481472018-05-04 10:43:19 -07001890bool Layer::isLegacyDataSpace() const {
1891 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001892 return !(getDataSpace() &
1893 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1894 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001895}
1896
Robert Carr1f0a16a2016-10-24 16:27:39 -07001897void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001898 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001899}
1900
Robert Carr6a160312021-05-17 12:08:20 -07001901int32_t Layer::getZ(LayerVector::StateSet) const {
1902 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001903}
1904
Robert Carr1c5481e2019-07-01 14:42:27 -07001905bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001906 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001907 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001908 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001909}
1910
David Sodman41fdfc92017-11-06 16:09:56 -08001911__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001912 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001913 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1914 "makeTraversalList received invalid stateSet");
1915 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1916 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001917 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001918
Robert Carr29abff82017-12-04 13:51:20 -08001919 if (state.zOrderRelatives.size() == 0) {
1920 *outSkipRelativeZUsers = true;
1921 return children;
1922 }
1923
chaviwfd462612018-05-31 16:11:27 -07001924 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001925 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001926 sp<Layer> strongRelative = weakRelative.promote();
1927 if (strongRelative != nullptr) {
1928 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001929 }
1930 }
1931
Dan Stoza412903f2017-04-27 13:42:17 -07001932 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001933 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001934 continue;
1935 }
Robert Carrdb66e622017-04-10 16:55:57 -07001936 traverse.add(child);
1937 }
1938
1939 return traverse;
1940}
1941
Robert Carr1f0a16a2016-10-24 16:27:39 -07001942/**
Robert Carrdb66e622017-04-10 16:55:57 -07001943 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001944 */
Dan Stoza412903f2017-04-27 13:42:17 -07001945void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001946 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1947 // produce a new list for traversing, including our relatives, and not including our children
1948 // who are relatives of another surface. In the case that there are no relative Z,
1949 // makeTraversalList returns our children directly to avoid significant overhead.
1950 // However in this case we need to take the responsibility for filtering children which
1951 // are relatives of another surface here.
1952 bool skipRelativeZUsers = false;
1953 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001954
Robert Carr1f0a16a2016-10-24 16:27:39 -07001955 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001956 for (; i < list.size(); i++) {
1957 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001958 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1959 continue;
1960 }
1961
chaviw301b1d82019-11-06 13:15:09 -08001962 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001963 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001964 }
Dan Stoza412903f2017-04-27 13:42:17 -07001965 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001966 }
Robert Carr29abff82017-12-04 13:51:20 -08001967
Dan Stoza412903f2017-04-27 13:42:17 -07001968 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001969 for (; i < list.size(); i++) {
1970 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001971
Robert Carr29abff82017-12-04 13:51:20 -08001972 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1973 continue;
1974 }
Dan Stoza412903f2017-04-27 13:42:17 -07001975 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001976 }
1977}
1978
1979/**
Robert Carrdb66e622017-04-10 16:55:57 -07001980 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001981 */
Dan Stoza412903f2017-04-27 13:42:17 -07001982void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1983 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001984 // See traverseInZOrder for documentation.
1985 bool skipRelativeZUsers = false;
1986 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001987
Robert Carr1f0a16a2016-10-24 16:27:39 -07001988 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001989 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001990 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001991
1992 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1993 continue;
1994 }
1995
chaviw301b1d82019-11-06 13:15:09 -08001996 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001997 break;
1998 }
Dan Stoza412903f2017-04-27 13:42:17 -07001999 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002000 }
Dan Stoza412903f2017-04-27 13:42:17 -07002001 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08002002 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002003 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08002004
2005 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
2006 continue;
2007 }
2008
Dan Stoza412903f2017-04-27 13:42:17 -07002009 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002010 }
2011}
2012
Edgar Arriaga844fa672020-01-16 14:21:42 -08002013void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
2014 visitor(this);
2015 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07002016 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002017 for (const sp<Layer>& child : children) {
2018 child->traverse(state, visitor);
2019 }
2020}
2021
chaviw4b129c22018-04-09 16:19:43 -07002022LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
2023 const std::vector<Layer*>& layersInTree) {
2024 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2025 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07002026 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2027 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002028 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002029
chaviwfd462612018-05-31 16:11:27 -07002030 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07002031 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2032 sp<Layer> strongRelative = weakRelative.promote();
2033 // Only add relative layers that are also descendents of the top most parent of the tree.
2034 // If a relative layer is not a descendent, then it should be ignored.
2035 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
2036 traverse.add(strongRelative);
2037 }
2038 }
2039
2040 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07002041 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002042 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
2043 // descendent of the top most parent of the tree. If it's not a descendent, then just add
2044 // the child here since it won't be added later as a relative.
2045 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
2046 childState.zOrderRelativeOf.promote().get())) {
2047 continue;
2048 }
2049 traverse.add(child);
2050 }
2051
2052 return traverse;
2053}
2054
2055void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
2056 LayerVector::StateSet stateSet,
2057 const LayerVector::Visitor& visitor) {
2058 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07002059
2060 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07002061 for (; i < list.size(); i++) {
2062 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08002063 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07002064 break;
2065 }
chaviw4b129c22018-04-09 16:19:43 -07002066 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002067 }
chaviw4b129c22018-04-09 16:19:43 -07002068
chaviwa76b2712017-09-20 12:02:26 -07002069 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07002070 for (; i < list.size(); i++) {
2071 const auto& relative = list[i];
2072 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002073 }
2074}
2075
chaviw4b129c22018-04-09 16:19:43 -07002076std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2077 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2078 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2079
2080 std::vector<Layer*> layersInTree = {this};
2081 for (size_t i = 0; i < children.size(); i++) {
2082 const auto& child = children[i];
2083 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2084 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2085 }
2086
2087 return layersInTree;
2088}
2089
2090void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2091 const LayerVector::Visitor& visitor) {
2092 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2093 std::sort(layersInTree.begin(), layersInTree.end());
2094 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2095}
2096
Peiyong Linefefaac2018-08-17 12:27:51 -07002097ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08002098 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002099}
2100
Garfield Tan2c1782c2022-02-16 15:25:05 -08002101bool Layer::isTransformValid() const {
2102 float transformDet = getTransform().det();
2103 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2104}
2105
chaviw13fdc492017-06-27 12:40:18 -07002106half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002107 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002108
chaviw13fdc492017-06-27 12:40:18 -07002109 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2110 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002111}
Robert Carr6452f122017-03-21 10:41:29 -07002112
Vishnu Nair6213bd92020-05-08 17:42:25 -07002113ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002114 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002115 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2116 return fixedTransformHint;
2117 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002118 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002119 if (!p) return fixedTransformHint;
2120 return p->getFixedTransformHint();
2121}
2122
chaviw13fdc492017-06-27 12:40:18 -07002123half4 Layer::getColor() const {
2124 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002125 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002126}
Robert Carr6452f122017-03-21 10:41:29 -07002127
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002128int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002129 if (getDrawingState().backgroundBlurRadius == 0) {
2130 return 0;
2131 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002132
Vishnu Nair29810f72022-07-01 16:38:41 +00002133 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002134 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2135 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002136}
2137
Galia Peychevae0acf382021-04-12 21:22:34 +02002138const std::vector<BlurRegion> Layer::getBlurRegions() const {
2139 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002140 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002141 for (auto& region : regionsCopy) {
2142 region.alpha = region.alpha * layerAlpha;
2143 }
2144 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002145}
2146
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002147Layer::RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002148 // Get parent settings
2149 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002150 const auto& parent = mDrawingParent.promote();
2151 if (parent != nullptr) {
2152 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002153 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002154 ui::Transform t = getActiveTransform(getDrawingState());
2155 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002156 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002157 parentSettings.radius.x *= t.getScaleX();
2158 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002159 }
2160 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002161
2162 // Get layer settings
2163 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002164 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002165 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002166 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002167
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002168 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002169 // If the parent and the layer have rounded corner settings, use the parent settings if the
2170 // parent crop is entirely inside the layer crop.
2171 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2172 if (parentSettings.cropRect.left > layerCropRect.left &&
2173 parentSettings.cropRect.top > layerCropRect.top &&
2174 parentSettings.cropRect.right < layerCropRect.right &&
2175 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2176 return parentSettings;
2177 } else {
2178 return layerSettings;
2179 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002180 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002181 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002182 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002183 return parentSettings;
2184 }
2185 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002186}
2187
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04002188void Layer::prepareShadowClientComposition(LayerFE::LayerSettings& caster,
Patrick Williams16d8b2c2022-08-08 17:29:05 +00002189 const Rect& layerStackRect) const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00002190 const auto* snapshot = getLayerSnapshot();
2191 renderengine::ShadowSettings state = snapshot->shadowSettings;
2192 if (state.length <= 0.f || (state.ambientColor.a <= 0.f && state.spotColor.a <= 0.f)) {
2193 return;
2194 }
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04002195
Vishnu Nair08f6eae2019-11-26 14:01:39 -08002196 // Shift the spot light x-position to the middle of the display and then
2197 // offset it by casting layer's screen pos.
Vishnu Nairbedb44b2022-08-02 21:47:40 +00002198 state.lightPos.x = (layerStackRect.width() / 2.f) - snapshot->transformedBounds.left;
2199 state.lightPos.y -= snapshot->transformedBounds.top;
2200 caster.shadow = state;
Vishnu Nair08f6eae2019-11-26 14:01:39 -08002201}
2202
Robert Carr88b85e12022-03-21 15:47:35 -07002203bool Layer::findInHierarchy(const sp<Layer>& l) {
2204 if (l == this) {
2205 return true;
2206 }
2207 for (auto& child : mDrawingChildren) {
2208 if (child->findInHierarchy(l)) {
2209 return true;
2210 }
2211 }
2212 return false;
2213}
2214
Robert Carr1f0a16a2016-10-24 16:27:39 -07002215void Layer::commitChildList() {
2216 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2217 const auto& child = mCurrentChildren[i];
2218 child->commitChildList();
2219 }
2220 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002221 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002222 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2223 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2224 if (zOrderRelativeOf == nullptr) return;
2225 if (findInHierarchy(zOrderRelativeOf)) {
2226 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2227 zOrderRelativeOf->mName.c_str());
2228 ALOGE("Severing rel Z loop, potentially dangerous");
2229 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002230 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002231 }
2232 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002233}
2234
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002235
chaviw3277faf2021-05-19 16:45:23 -05002236void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002237 mDrawingState.inputInfo = info;
Vishnu Nairf9096652021-07-20 18:49:42 -07002238 mDrawingState.touchableRegionCrop = fromHandle(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002239 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002240 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002241 setTransactionFlags(eTransactionNeeded);
2242}
2243
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002244LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002245 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002246 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002247 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2248
Vishnu Nair00b90132021-11-05 14:03:40 -07002249 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002250 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2251
Vishnu Nair60db8c02020-04-02 11:55:16 -07002252 // Only populate for the primary display.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002253 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -05002254 const auto compositionType = getCompositionType(*display);
Vishnu Nair60db8c02020-04-02 11:55:16 -07002255 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002256 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2257 [&]() { return layerProto->mutable_visible_region(); });
Vishnu Nair60db8c02020-04-02 11:55:16 -07002258 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08002259 }
2260
chaviw08f3cb22020-01-13 13:17:21 -08002261 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002262 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002263 }
chaviw6d89e2d2020-01-14 14:42:01 -08002264
2265 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002266}
2267
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002268void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002269 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002270 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002271 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002272 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002273 [&]() { return layerInfo->mutable_active_buffer(); });
2274 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2275 layerInfo->mutable_buffer_transform());
2276 }
2277 layerInfo->set_invalidate(contentDirty);
2278 layerInfo->set_is_protected(isProtected());
2279 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2280 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002281 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002282 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002283 layerInfo->set_corner_radius(
2284 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002285 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2286 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2287 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2288 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2289 [&]() { return layerInfo->mutable_position(); });
2290 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002291 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2292 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002293
Vishnu Nair00b90132021-11-05 14:03:40 -07002294 if (hasColorTransform()) {
2295 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002296 }
2297
Vishnu Nair60db8c02020-04-02 11:55:16 -07002298 LayerProtoHelper::writeToProto(mSourceBounds,
2299 [&]() { return layerInfo->mutable_source_bounds(); });
2300 LayerProtoHelper::writeToProto(mScreenBounds,
2301 [&]() { return layerInfo->mutable_screen_bounds(); });
2302 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2303 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2304 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002305}
2306
2307void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002308 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002309 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2310 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002311 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002312
chaviw766c9c52021-02-10 17:36:47 -08002313 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002314
Vishnu Nair00b90132021-11-05 14:03:40 -07002315 layerInfo->set_id(sequence);
2316 layerInfo->set_name(getName().c_str());
2317 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002318
Vishnu Nair00b90132021-11-05 14:03:40 -07002319 for (const auto& child : children) {
2320 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002321 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002322
Vishnu Nair00b90132021-11-05 14:03:40 -07002323 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2324 sp<Layer> strongRelative = weakRelative.promote();
2325 if (strongRelative != nullptr) {
2326 layerInfo->add_relatives(strongRelative->sequence);
2327 }
2328 }
2329
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002330 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002331 [&]() { return layerInfo->mutable_transparent_region(); });
2332
2333 layerInfo->set_layer_stack(getLayerStack().id);
2334 layerInfo->set_z(state.z);
2335
2336 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2337 return layerInfo->mutable_requested_position();
2338 });
2339
Vishnu Nair00b90132021-11-05 14:03:40 -07002340 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2341
2342 layerInfo->set_is_opaque(isOpaque(state));
2343
2344 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2345 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2346 LayerProtoHelper::writeToProto(state.color,
2347 [&]() { return layerInfo->mutable_requested_color(); });
2348 layerInfo->set_flags(state.flags);
2349
2350 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2351 layerInfo->mutable_requested_transform());
2352
2353 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2354 if (parent != nullptr) {
2355 layerInfo->set_parent(parent->sequence);
2356 } else {
2357 layerInfo->set_parent(-1);
2358 }
2359
2360 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2361 if (zOrderRelativeOf != nullptr) {
2362 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2363 } else {
2364 layerInfo->set_z_order_relative_of(-1);
2365 }
2366
2367 layerInfo->set_is_relative_of(state.isRelativeOf);
2368
2369 layerInfo->set_owner_uid(mOwnerUid);
2370
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002371 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002372 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002373 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002374 info = fillInputInfo(
2375 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002376 } else {
2377 info = state.inputInfo;
2378 }
2379
2380 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002381 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002382 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002383
Vishnu Nair00b90132021-11-05 14:03:40 -07002384 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002385 auto protoMap = layerInfo->mutable_metadata();
2386 for (const auto& entry : state.metadata.mMap) {
2387 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2388 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002389 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002390
2391 LayerProtoHelper::writeToProto(state.destinationFrame,
2392 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002393}
2394
Robert Carr2e102c92018-10-23 12:11:15 -07002395bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002396 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002397}
2398
Prabir Pradhan33da9462022-06-14 14:55:57 +00002399// Applies the given transform to the region, while protecting against overflows caused by any
2400// offsets. If applying the offset in the transform to any of the Rects in the region would result
2401// in an overflow, they are not added to the output Region.
2402static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2403 const std::string& debugWindowName) {
2404 // Round the translation using the same rounding strategy used by ui::Transform.
2405 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2406 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2407
2408 ui::Transform transformWithoutOffset = t;
2409 transformWithoutOffset.set(0.f, 0.f);
2410
2411 const Region transformed = transformWithoutOffset.transform(r);
2412
2413 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2414 Region ret;
2415 for (const auto& rect : transformed) {
2416 Rect newRect;
2417 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2418 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2419 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2420 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2421 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2422 debugWindowName.c_str());
2423 continue;
2424 }
2425 ret.orSelf(newRect);
2426 }
2427 return ret;
2428}
2429
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002430void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
2431 Rect tmpBounds = getInputBounds();
2432 if (!tmpBounds.isValid()) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002433 info.touchableRegion.clear();
2434 // A layer could have invalid input bounds and still expect to receive touch input if it has
2435 // replaceTouchableRegionWithCrop. For that case, the input transform needs to be calculated
2436 // correctly to determine the coordinate space for input events. Use an empty rect so that
2437 // the layer will receive input in its own layer space.
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002438 tmpBounds = Rect::EMPTY_RECT;
chaviw7e72caf2020-12-02 16:50:43 -08002439 }
2440
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002441 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2442 // frame and transform used for the layer, which determines the bounds and the coordinate space
2443 // within which the layer will receive input.
2444 //
2445 // The coordinate space within which each of the bounds are specified is explicitly documented
2446 // in the variable name. For example "inputBoundsInLayer" is specified in layer space. A
2447 // Transform converts one coordinate space to another, which is apparent in its naming. For
2448 // example, "layerToDisplay" transforms layer space to display space.
2449 //
2450 // Coordinate space definitions:
2451 // - display: The display device's coordinate space. Correlates to pixels on the display.
2452 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2453 // - layer: The coordinate space of this layer.
2454 // - input: The coordinate space in which this layer will receive input events. This could be
2455 // different than layer space if a surfaceInset is used, which changes the origin
2456 // of the input space.
2457 const FloatRect inputBoundsInLayer = tmpBounds.toFloatRect();
chaviw7e72caf2020-12-02 16:50:43 -08002458
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002459 // Clamp surface inset to the input bounds.
2460 const auto surfaceInset = static_cast<float>(info.surfaceInset);
2461 const float xSurfaceInset =
2462 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getWidth() / 2.f));
2463 const float ySurfaceInset =
2464 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getHeight() / 2.f));
chaviw1ff3d1e2020-07-01 15:53:47 -07002465
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002466 // Apply the insets to the input bounds.
2467 const FloatRect insetBoundsInLayer(inputBoundsInLayer.left + xSurfaceInset,
2468 inputBoundsInLayer.top + ySurfaceInset,
2469 inputBoundsInLayer.right - xSurfaceInset,
2470 inputBoundsInLayer.bottom - ySurfaceInset);
Ady Abraham282f1d72019-07-24 18:05:56 -07002471
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002472 // Crop the input bounds to ensure it is within the parent's bounds.
2473 const FloatRect croppedInsetBoundsInLayer = mBounds.intersect(insetBoundsInLayer);
Ady Abraham282f1d72019-07-24 18:05:56 -07002474
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002475 const ui::Transform layerToScreen = getInputTransform();
2476 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
Vishnu Nair8033a492018-12-05 07:27:23 -08002477
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002478 const Rect roundedFrameInDisplay{layerToDisplay.transform(croppedInsetBoundsInLayer)};
2479 info.frameLeft = roundedFrameInDisplay.left;
2480 info.frameTop = roundedFrameInDisplay.top;
2481 info.frameRight = roundedFrameInDisplay.right;
2482 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002483
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002484 ui::Transform inputToLayer;
2485 inputToLayer.set(insetBoundsInLayer.left, insetBoundsInLayer.top);
2486 const ui::Transform inputToDisplay = layerToDisplay * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002487
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002488 // InputDispatcher expects a display-to-input transform.
2489 info.transform = inputToDisplay.inverse();
2490
2491 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002492 info.touchableRegion =
2493 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002494}
2495
chaviw3277faf2021-05-19 16:45:23 -05002496void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002497 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002498 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002499 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002500 }
2501 if (p != nullptr) {
2502 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2503 }
2504}
2505
Vishnu Naira066d902021-09-13 18:40:17 -07002506gui::DropInputMode Layer::getDropInputMode() const {
2507 gui::DropInputMode mode = mDrawingState.dropInputMode;
2508 if (mode == gui::DropInputMode::ALL) {
2509 return mode;
2510 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002511 sp<Layer> parent = mDrawingParent.promote();
2512 if (parent) {
2513 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002514 if (parentMode != gui::DropInputMode::NONE) {
2515 return parentMode;
2516 }
2517 }
2518 return mode;
2519}
2520
2521void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002522 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002523 return;
2524 }
2525
2526 // Check if we need to drop input unconditionally
2527 gui::DropInputMode dropInputMode = getDropInputMode();
2528 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002529 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002530 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2531 return;
2532 }
2533
2534 // Check if we need to check if the window is obscured by parent
2535 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2536 return;
2537 }
2538
2539 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002540 sp<Layer> parent = mDrawingParent.promote();
2541 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002542 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002543 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2544 static_cast<float>(getAlpha()));
2545 }
2546
2547 // Check if the parent has cropped the buffer
2548 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2549 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002550 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002551 return;
2552 }
2553
2554 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2555 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2556 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2557 // match then the layer has not been cropped by its parents.
2558 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2559 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2560
2561 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002562 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002563 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2564 getDebugName());
2565 } else {
2566 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2567 // input if the window is obscured. This check should be done in surfaceflinger but the
2568 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2569 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002570 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002571 }
2572}
2573
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002574WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002575 if (!hasInputInfo()) {
2576 mDrawingState.inputInfo.name = getName();
2577 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2578 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002579 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002580 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002581 }
2582
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002583 const ui::Transform& displayTransform =
2584 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2585
chaviw3277faf2021-05-19 16:45:23 -05002586 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002587 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002588 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002589
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002590 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002591
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002592 if (displayArgs.transform == nullptr) {
2593 // Do not let the window receive touches if it is not associated with a valid display
2594 // transform. We still allow the window to receive keys and prevent ANRs.
2595 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2596 }
2597
Robert Carr5dc426e2020-06-10 14:29:14 -07002598 // For compatibility reasons we let layers which can receive input
2599 // receive input before they have actually submitted a buffer. Because
2600 // of this we use canReceiveInput instead of isVisible to check the
2601 // policy-visibility, ignoring the buffer state. However for layers with
2602 // hasInputInfo()==false we can use the real visibility state.
2603 // We are just using these layers for occlusion detection in
2604 // InputDispatcher, and obviously if they aren't visible they can't occlude
2605 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002606 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2607 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2608
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002609 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002610 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002611 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002612
Vishnu Nair16a938f2021-09-24 07:14:54 -07002613 // If the window will be blacked out on a display because the display does not have the secure
2614 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002615 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002616 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002617 }
2618
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002619 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2620 if (info.replaceTouchableRegionWithCrop) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002621 const Rect bounds(cropLayer ? cropLayer->mScreenBounds : mScreenBounds);
2622 info.touchableRegion = Region(displayTransform.transform(bounds));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002623 } else if (cropLayer != nullptr) {
[1;3C2b9fc252021-02-04 16:16:50 -08002624 info.touchableRegion = info.touchableRegion.intersect(
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002625 displayTransform.transform(Rect{cropLayer->mScreenBounds}));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002626 }
2627
Winson Chunga30f7c92021-06-29 15:42:56 -07002628 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2629 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002630 if (isTrustedOverlay()) {
2631 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2632 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002633
chaviwaf87b3e2019-10-01 16:59:28 -07002634 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2635 // touches from going outside the cloned area.
2636 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002637 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002638 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2639 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002640 info.touchableRegion = info.touchableRegion.intersect(rect);
2641 }
2642 }
2643
Robert Carr720e5062018-07-30 17:45:14 -07002644 return info;
2645}
2646
chaviwaf87b3e2019-10-01 16:59:28 -07002647sp<Layer> Layer::getClonedRoot() {
2648 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002649 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002650 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002651 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002652 return nullptr;
2653 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002654 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002655}
2656
Robert Carredd13602020-04-13 17:24:34 -07002657bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002658 return mDrawingState.inputInfo.token != nullptr ||
2659 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002660}
2661
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002662compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002663 const DisplayDevice* display) const {
2664 if (!display) return nullptr;
Lloyd Piquede196652020-01-22 17:29:58 -08002665 return display->getCompositionDisplay()->getOutputLayerForLayer(getCompositionEngineLayerFE());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002666}
2667
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002668Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2669 const auto outputLayer = findOutputLayerForDisplay(display);
2670 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002671}
2672
chaviwb4c6e582019-08-16 14:35:07 -07002673void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002674 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002675 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002676 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2677 mPotentialCursor = clonedFrom->mPotentialCursor;
2678 mProtectedByApp = clonedFrom->mProtectedByApp;
2679 updateCloneBufferInfo();
2680}
2681
2682void Layer::updateCloneBufferInfo() {
2683 if (!isClone() || !isClonedFromAlive()) {
2684 return;
2685 }
2686
2687 sp<Layer> clonedFrom = getClonedFrom();
2688 mBufferInfo = clonedFrom->mBufferInfo;
2689 mSidebandStream = clonedFrom->mSidebandStream;
2690 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2691 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2692 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2693
2694 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2695 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2696 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2697 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2698 // the cloned drawingState again.
2699 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2700 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2701 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2702 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2703
2704 cloneDrawingState(clonedFrom.get());
2705
2706 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2707 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2708 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2709 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002710}
chaviw74b03172019-08-19 11:09:03 -07002711
2712void Layer::updateMirrorInfo() {
2713 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2714 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2715 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2716 // that case, we want to delete the reference to the clone since we want it to get
2717 // destroyed. The root, this layer, will still be around since the client can continue
2718 // to hold a reference, but no cloned layers will be displayed.
2719 mClonedChild = nullptr;
2720 return;
2721 }
2722
2723 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2724 // If the real layer exists and is in current state, add the clone as a child of the root.
2725 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2726 // copied to drawingState for the root layer. So the clonedChild is always removed from
2727 // drawingState and then needs to be added back each traversal.
2728 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2729 addChildToDrawing(mClonedChild);
2730 }
2731
2732 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002733 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002734 mClonedChild->updateClonedRelatives(clonedLayersMap);
2735}
2736
2737void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2738 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2739 // to the clone. If the real layer is no longer alive, continue traversing the children
2740 // since we may be able to pull out other children that are still alive.
2741 if (isClonedFromAlive()) {
2742 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002743 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002744 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002745 }
2746
2747 // The clone layer may have children in drawingState since they may have been created and
2748 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2749 // that already exist, since we can just re-use them.
2750 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2751 // not updated in the regular traversal. They are skipped since the root will lose the
2752 // reference to them when it copies its currentChildren to drawing.
2753 for (sp<Layer>& child : mDrawingChildren) {
2754 child->updateClonedDrawingState(clonedLayersMap);
2755 }
2756}
2757
2758void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2759 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2760 mDrawingChildren.clear();
2761
2762 if (!isClonedFromAlive()) {
2763 return;
2764 }
2765
2766 sp<Layer> clonedFrom = getClonedFrom();
2767 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2768 if (child == mirrorRoot) {
2769 // This is to avoid cyclical mirroring.
2770 continue;
2771 }
2772 sp<Layer> clonedChild = clonedLayersMap[child];
2773 if (clonedChild == nullptr) {
2774 clonedChild = child->createClone();
2775 clonedLayersMap[child] = clonedChild;
2776 }
2777 addChildToDrawing(clonedChild);
2778 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2779 }
2780}
2781
chaviwaf87b3e2019-10-01 16:59:28 -07002782void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2783 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2784 if (cropLayer != nullptr) {
2785 if (clonedLayersMap.count(cropLayer) == 0) {
2786 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2787 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002788 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002789 } else {
2790 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2791 mDrawingState.touchableRegionCrop = clonedCropLayer;
2792 }
2793 }
2794 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2795 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002796 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002797}
2798
2799void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002800 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002801 mDrawingState.zOrderRelatives.clear();
2802
2803 if (!isClonedFromAlive()) {
2804 return;
2805 }
2806
chaviwaf87b3e2019-10-01 16:59:28 -07002807 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002808 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002809 const sp<Layer>& relative = relativeWeak.promote();
2810 if (clonedLayersMap.count(relative) > 0) {
2811 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002812 mDrawingState.zOrderRelatives.add(clonedRelative);
2813 }
2814 }
2815
2816 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2817 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2818 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2819 // still traverse the children, but the layer with the missing relativeOf will not be shown
2820 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002821 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2822 if (clonedLayersMap.count(relativeOf) > 0) {
2823 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002824 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2825 }
2826
chaviwaf87b3e2019-10-01 16:59:28 -07002827 updateClonedInputInfo(clonedLayersMap);
2828
chaviw74b03172019-08-19 11:09:03 -07002829 for (sp<Layer>& child : mDrawingChildren) {
2830 child->updateClonedRelatives(clonedLayersMap);
2831 }
2832}
2833
2834void Layer::addChildToDrawing(const sp<Layer>& layer) {
2835 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002836 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002837}
2838
Steven Thomas62a4cf82020-01-31 12:04:03 -08002839Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2840 switch (compatibility) {
2841 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2842 return FrameRateCompatibility::Default;
2843 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2844 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002845 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2846 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002847 case ANATIVEWINDOW_FRAME_RATE_MIN:
2848 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002849 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2850 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002851 default:
2852 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2853 return FrameRateCompatibility::Default;
2854 }
2855}
2856
Marin Shalamanovc5986772021-03-16 16:09:49 +01002857scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2858 switch (strategy) {
2859 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2860 return Seamlessness::OnlySeamless;
2861 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2862 return Seamlessness::SeamedAndSeamless;
2863 default:
2864 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2865 return Seamlessness::Default;
2866 }
2867}
2868
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002869bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002870 const State& s(mDrawingState);
2871 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2872 return true;
2873 }
2874
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002875 sp<Layer> parent = mDrawingParent.promote();
2876 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002877}
2878
Robert Carr6a0382d2021-07-01 15:57:17 -07002879void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2880 mClonedChild = clonedChild;
2881 mHadClonedChild = true;
2882 mFlinger->mNumClones++;
2883}
2884
Vishnu Nairf9096652021-07-20 18:49:42 -07002885const String16 Layer::Handle::kDescriptor = String16("android.Layer.Handle");
2886
2887wp<Layer> Layer::fromHandle(const sp<IBinder>& handleBinder) {
2888 if (handleBinder == nullptr) {
2889 return nullptr;
2890 }
2891
2892 BBinder* b = handleBinder->localBinder();
2893 if (b == nullptr || b->getInterfaceDescriptor() != Handle::kDescriptor) {
2894 return nullptr;
2895 }
2896
2897 // We can safely cast this binder since its local and we verified its interface descriptor.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002898 sp<Handle> handle = sp<Handle>::cast(handleBinder);
Vishnu Nairf9096652021-07-20 18:49:42 -07002899 return handle->owner;
2900}
2901
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002902bool Layer::setDropInputMode(gui::DropInputMode mode) {
2903 if (mDrawingState.dropInputMode == mode) {
2904 return false;
2905 }
2906 mDrawingState.dropInputMode = mode;
2907 return true;
2908}
2909
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002910void Layer::cloneDrawingState(const Layer* from) {
2911 mDrawingState = from->mDrawingState;
2912 // Skip callback info since they are not applicable for cloned layers.
2913 mDrawingState.releaseBufferListener = nullptr;
2914 mDrawingState.callbackHandles = {};
2915}
2916
Patrick Williamsbb25f802022-08-30 23:02:34 +00002917void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2918 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
2919 const sp<Fence>& releaseFence,
2920 uint32_t currentMaxAcquiredBufferCount) {
2921 if (!listener) {
2922 return;
2923 }
2924 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
2925 listener->onReleaseBuffer({buffer->getId(), framenumber},
2926 releaseFence ? releaseFence : Fence::NO_FENCE,
2927 currentMaxAcquiredBufferCount);
2928}
2929
2930void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2931 // If we are displayed on multiple displays in a single composition cycle then we would
2932 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2933 // For example we can only use it if all the displays are client comp, and we need
2934 // to merge all the client comp fences. We could do this, but for now we just
2935 // disable the optimization when a layer is composed on multiple displays.
2936 if (mClearClientCompositionFenceOnLayerDisplayed) {
2937 mLastClientCompositionFence = nullptr;
2938 } else {
2939 mClearClientCompositionFenceOnLayerDisplayed = true;
2940 }
2941
2942 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2943 // buffer that was presented on this layer. The first transaction that came in this frame that
2944 // replaced the previous buffer on this layer needs this release fence, because the fence will
2945 // let the client know when that previous buffer is removed from the screen.
2946 //
2947 // Every other transaction on this layer does not need a release fence because no other
2948 // Transactions that were set on this layer this frame are going to have their preceding buffer
2949 // removed from the display this frame.
2950 //
2951 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2952 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2953 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2954 // the previous buffer will be released this frame. The third transaction also contains a
2955 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2956 // transaction will now no longer be presented so it is released immediately and the third
2957 // transaction doesn't need a previous release fence.
2958 sp<CallbackHandle> ch;
2959 for (auto& handle : mDrawingState.callbackHandles) {
2960 if (handle->releasePreviousBuffer &&
2961 mDrawingState.releaseBufferEndpoint == handle->listener) {
2962 ch = handle;
2963 break;
2964 }
2965 }
2966
2967 // Prevent tracing the same release multiple times.
2968 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2969 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2970 }
2971
2972 if (ch != nullptr) {
2973 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2974 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2975 ch->name = mName;
2976 }
2977}
2978
2979void Layer::onSurfaceFrameCreated(
2980 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2981 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2982 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2983 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2984 // leak.
2985 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2986 mName.c_str());
2987 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2988 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2989 mPendingJankClassifications.pop_front();
2990 }
2991 mPendingJankClassifications.emplace_back(surfaceFrame);
2992}
2993
2994void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2995 for (const auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair71fcf912022-10-18 09:14:20 -07002996 handle->transformHint = mSkipReportingTransformHint
2997 ? std::nullopt
2998 : std::make_optional<uint32_t>(mTransformHint);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002999 handle->dequeueReadyTime = dequeueReadyTime;
3000 handle->currentMaxAcquiredBufferCount =
3001 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
3002 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
3003 handle->previousReleaseCallbackId.framenumber);
3004 }
3005
3006 for (auto& handle : mDrawingState.callbackHandles) {
3007 if (handle->releasePreviousBuffer &&
3008 mDrawingState.releaseBufferEndpoint == handle->listener) {
3009 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
3010 break;
3011 }
3012 }
3013
3014 std::vector<JankData> jankData;
3015 jankData.reserve(mPendingJankClassifications.size());
3016 while (!mPendingJankClassifications.empty() &&
3017 mPendingJankClassifications.front()->getJankType()) {
3018 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
3019 mPendingJankClassifications.front();
3020 mPendingJankClassifications.pop_front();
3021 jankData.emplace_back(
3022 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
3023 }
3024
3025 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
3026 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003027 mDrawingState.callbackHandles = {};
3028}
3029
3030bool Layer::willPresentCurrentTransaction() const {
3031 // Returns true if the most recent Transaction applied to CurrentState will be presented.
3032 return (getSidebandStreamChanged() || getAutoRefresh() ||
3033 (mDrawingState.modified &&
3034 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
3035}
3036
3037bool Layer::setTransform(uint32_t transform) {
3038 if (mDrawingState.bufferTransform == transform) return false;
3039 mDrawingState.bufferTransform = transform;
3040 mDrawingState.modified = true;
3041 setTransactionFlags(eTransactionNeeded);
3042 return true;
3043}
3044
3045bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
3046 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
3047 mDrawingState.sequence++;
3048 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
3049 mDrawingState.modified = true;
3050 setTransactionFlags(eTransactionNeeded);
3051 return true;
3052}
3053
3054bool Layer::setBufferCrop(const Rect& bufferCrop) {
3055 if (mDrawingState.bufferCrop == bufferCrop) return false;
3056
3057 mDrawingState.sequence++;
3058 mDrawingState.bufferCrop = bufferCrop;
3059
3060 mDrawingState.modified = true;
3061 setTransactionFlags(eTransactionNeeded);
3062 return true;
3063}
3064
3065bool Layer::setDestinationFrame(const Rect& destinationFrame) {
3066 if (mDrawingState.destinationFrame == destinationFrame) return false;
3067
3068 mDrawingState.sequence++;
3069 mDrawingState.destinationFrame = destinationFrame;
3070
3071 mDrawingState.modified = true;
3072 setTransactionFlags(eTransactionNeeded);
3073 return true;
3074}
3075
3076// Translate destination frame into scale and position. If a destination frame is not set, use the
3077// provided scale and position
3078bool Layer::updateGeometry() {
3079 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
3080 mDrawingState.destinationFrame.isEmpty()) {
3081 // If destination frame is not set, use the requested transform set via
3082 // Layer::setPosition and Layer::setMatrix.
3083 return assignTransform(&mDrawingState.transform, mRequestedTransform);
3084 }
3085
3086 Rect destRect = mDrawingState.destinationFrame;
3087 int32_t destW = destRect.width();
3088 int32_t destH = destRect.height();
3089 if (destRect.left < 0) {
3090 destRect.left = 0;
3091 destRect.right = destW;
3092 }
3093 if (destRect.top < 0) {
3094 destRect.top = 0;
3095 destRect.bottom = destH;
3096 }
3097
3098 if (!mDrawingState.buffer) {
3099 ui::Transform t;
3100 t.set(destRect.left, destRect.top);
3101 return assignTransform(&mDrawingState.transform, t);
3102 }
3103
3104 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3105 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3106 // Undo any transformations on the buffer.
3107 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3108 std::swap(bufferWidth, bufferHeight);
3109 }
3110 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3111 if (mDrawingState.transformToDisplayInverse) {
3112 if (invTransform & ui::Transform::ROT_90) {
3113 std::swap(bufferWidth, bufferHeight);
3114 }
3115 }
3116
3117 float sx = destW / static_cast<float>(bufferWidth);
3118 float sy = destH / static_cast<float>(bufferHeight);
3119 ui::Transform t;
3120 t.set(sx, 0, 0, sy);
3121 t.set(destRect.left, destRect.top);
3122 return assignTransform(&mDrawingState.transform, t);
3123}
3124
3125bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3126 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3127 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3128 return false;
3129 }
3130
3131 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3132
3133 mDrawingState.sequence++;
3134 mDrawingState.modified = true;
3135 setTransactionFlags(eTransactionNeeded);
3136
3137 return true;
3138}
3139
3140bool Layer::setPosition(float x, float y) {
3141 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3142 return false;
3143 }
3144
3145 mRequestedTransform.set(x, y);
3146
3147 mDrawingState.sequence++;
3148 mDrawingState.modified = true;
3149 setTransactionFlags(eTransactionNeeded);
3150
3151 return true;
3152}
3153
3154bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3155 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3156 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
3157 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003158 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003159 if (!buffer) {
3160 return false;
3161 }
3162
3163 const bool frameNumberChanged =
3164 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3165 const uint64_t frameNumber =
3166 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003167 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003168
3169 if (mDrawingState.buffer) {
3170 mReleasePreviousBuffer = true;
3171 if (!mBufferInfo.mBuffer ||
3172 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3173 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3174 // If mDrawingState has a buffer, and we are about to update again
3175 // before swapping to drawing state, then the first buffer will be
3176 // dropped and we should decrement the pending buffer count and
3177 // call any release buffer callbacks if set.
3178 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3179 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3180 mDrawingState.acquireFence,
3181 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
3182 mOwnerUid));
3183 decrementPendingBufferCount();
3184 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3185 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3186 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
3187 mDrawingState.bufferSurfaceFrameTX.reset();
3188 }
3189 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3190 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3191 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3192 mLastClientCompositionFence,
3193 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
3194 mOwnerUid));
3195 mLastClientCompositionFence = nullptr;
3196 }
3197 }
3198
3199 mDrawingState.frameNumber = frameNumber;
3200 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3201 mDrawingState.buffer = std::move(buffer);
3202 mDrawingState.clientCacheId = bufferData.cachedBuffer;
3203
3204 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3205 ? bufferData.acquireFence
3206 : Fence::NO_FENCE;
3207 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3208 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3209 // We latched this buffer unsiganled, so we need to pass the acquire fence
3210 // on the callback instead of just the acquire time, since it's unknown at
3211 // this point.
3212 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3213 } else {
3214 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3215 }
3216
3217 mDrawingState.modified = true;
3218 setTransactionFlags(eTransactionNeeded);
3219
3220 const int32_t layerId = getSequence();
3221 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3222 mOwnerUid, postTime, getGameMode());
3223 mDrawingState.desiredPresentTime = desiredPresentTime;
3224 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3225
3226 const nsecs_t presentTime = [&] {
3227 if (!isAutoTimestamp) return desiredPresentTime;
3228
3229 const auto prediction =
3230 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
3231 if (prediction.has_value()) return prediction->presentTime;
3232
3233 return static_cast<nsecs_t>(0);
3234 }();
3235
3236 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
3237 mFlinger->mScheduler->recordLayerHistory(this, presentTime, LayerUpdateType::Buffer);
3238
3239 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3240
3241 if (dequeueTime && *dequeueTime != 0) {
3242 const uint64_t bufferId = mDrawingState.buffer->getId();
3243 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3244 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3245 FrameTracer::FrameEvent::DEQUEUE);
3246 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3247 FrameTracer::FrameEvent::QUEUE);
3248 }
3249
3250 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3251 return true;
3252}
3253
3254bool Layer::setDataspace(ui::Dataspace dataspace) {
3255 mDrawingState.dataspaceRequested = true;
3256 if (mDrawingState.dataspace == dataspace) return false;
3257 mDrawingState.dataspace = dataspace;
3258 mDrawingState.modified = true;
3259 setTransactionFlags(eTransactionNeeded);
3260 return true;
3261}
3262
3263bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3264 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3265 mDrawingState.hdrMetadata = hdrMetadata;
3266 mDrawingState.modified = true;
3267 setTransactionFlags(eTransactionNeeded);
3268 return true;
3269}
3270
3271bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
3272 mDrawingState.surfaceDamageRegion = surfaceDamage;
3273 mDrawingState.modified = true;
3274 setTransactionFlags(eTransactionNeeded);
3275 return true;
3276}
3277
3278bool Layer::setApi(int32_t api) {
3279 if (mDrawingState.api == api) return false;
3280 mDrawingState.api = api;
3281 mDrawingState.modified = true;
3282 setTransactionFlags(eTransactionNeeded);
3283 return true;
3284}
3285
3286bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3287 if (mDrawingState.sidebandStream == sidebandStream) return false;
3288
3289 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3290 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3291 } else if (sidebandStream != nullptr) {
3292 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3293 }
3294
3295 mDrawingState.sidebandStream = sidebandStream;
3296 mDrawingState.modified = true;
3297 setTransactionFlags(eTransactionNeeded);
3298 if (!mSidebandStreamChanged.exchange(true)) {
3299 // mSidebandStreamChanged was false
3300 mFlinger->onLayerUpdate();
3301 }
3302 return true;
3303}
3304
3305bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles) {
3306 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3307 if (handles.empty()) {
3308 mReleasePreviousBuffer = false;
3309 return false;
3310 }
3311
3312 const bool willPresent = willPresentCurrentTransaction();
3313
3314 for (const auto& handle : handles) {
3315 // If this transaction set a buffer on this layer, release its previous buffer
3316 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3317
3318 // If this layer will be presented in this frame
3319 if (willPresent) {
3320 // If this transaction set an acquire fence on this layer, set its acquire time
3321 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3322 handle->frameNumber = mDrawingState.frameNumber;
3323
3324 // Store so latched time and release fence can be set
3325 mDrawingState.callbackHandles.push_back(handle);
3326
3327 } else { // If this layer will NOT need to be relatched and presented this frame
3328 // Notify the transaction completed thread this handle is done
3329 mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
3330 }
3331 }
3332
3333 mReleasePreviousBuffer = false;
3334 mCallbackHandleAcquireTimeOrFence = -1;
3335
3336 return willPresent;
3337}
3338
3339Rect Layer::getBufferSize(const State& /*s*/) const {
3340 // for buffer state layers we use the display frame size as the buffer size.
3341
3342 if (mBufferInfo.mBuffer == nullptr) {
3343 return Rect::INVALID_RECT;
3344 }
3345
3346 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3347 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3348
3349 // Undo any transformations on the buffer and return the result.
3350 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3351 std::swap(bufWidth, bufHeight);
3352 }
3353
3354 if (getTransformToDisplayInverse()) {
3355 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3356 if (invTransform & ui::Transform::ROT_90) {
3357 std::swap(bufWidth, bufHeight);
3358 }
3359 }
3360
3361 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3362}
3363
3364FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3365 if (mBufferInfo.mBuffer == nullptr) {
3366 return parentBounds;
3367 }
3368
3369 return getBufferSize(getDrawingState()).toFloatRect();
3370}
3371
3372bool Layer::fenceHasSignaled() const {
3373 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3374 return true;
3375 }
3376
3377 const bool fenceSignaled =
3378 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3379 if (!fenceSignaled) {
3380 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3381 TimeStats::LatchSkipReason::LateAcquire);
3382 }
3383
3384 return fenceSignaled;
3385}
3386
Vishnu Nairba354102022-08-01 00:14:18 +00003387bool Layer::onPreComposition(nsecs_t refreshStartTime, bool /* updatingOutputGeometryThisFrame */) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003388 for (const auto& handle : mDrawingState.callbackHandles) {
3389 handle->refreshStartTime = refreshStartTime;
3390 }
3391 return hasReadyFrame();
3392}
3393
3394void Layer::setAutoRefresh(bool autoRefresh) {
3395 mDrawingState.autoRefresh = autoRefresh;
3396}
3397
3398bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3399 // 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 +00003400 auto* snapshot = editLayerSnapshot();
3401 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003402
3403 if (mSidebandStreamChanged.exchange(false)) {
3404 const State& s(getDrawingState());
3405 // mSidebandStreamChanged was true
3406 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003407 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003408 if (mSidebandStream != nullptr) {
3409 setTransactionFlags(eTransactionNeeded);
3410 mFlinger->setTransactionFlags(eTraversalNeeded);
3411 }
3412 recomputeVisibleRegions = true;
3413
3414 return true;
3415 }
3416 return false;
3417}
3418
3419bool Layer::hasFrameUpdate() const {
3420 const State& c(getDrawingState());
3421 return (mDrawingStateModified || mDrawingState.modified) &&
3422 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3423}
3424
3425void Layer::updateTexImage(nsecs_t latchTime) {
3426 const State& s(getDrawingState());
3427
3428 if (!s.buffer) {
3429 if (s.bgColorLayer) {
3430 for (auto& handle : mDrawingState.callbackHandles) {
3431 handle->latchTime = latchTime;
3432 }
3433 }
3434 return;
3435 }
3436
3437 for (auto& handle : mDrawingState.callbackHandles) {
3438 if (handle->frameNumber == mDrawingState.frameNumber) {
3439 handle->latchTime = latchTime;
3440 }
3441 }
3442
3443 const int32_t layerId = getSequence();
3444 const uint64_t bufferId = mDrawingState.buffer->getId();
3445 const uint64_t frameNumber = mDrawingState.frameNumber;
3446 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3447 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3448 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3449
3450 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3451 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3452 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3453 FrameTracer::FrameEvent::LATCH);
3454
3455 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3456 if (bufferSurfaceFrame != nullptr &&
3457 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3458 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3459 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3460 // are processing the next state.
3461 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3462 mDrawingState.acquireFenceTime->getSignalTime(),
3463 latchTime);
3464 mDrawingState.bufferSurfaceFrameTX.reset();
3465 }
3466
3467 std::deque<sp<CallbackHandle>> remainingHandles;
3468 mFlinger->getTransactionCallbackInvoker()
3469 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3470 mDrawingState.callbackHandles = remainingHandles;
3471
3472 mDrawingStateModified = false;
3473}
3474
3475void Layer::gatherBufferInfo() {
3476 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3477 decrementPendingBufferCount();
3478 }
3479
3480 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3481 mBufferInfo.mBuffer = mDrawingState.buffer;
3482 mBufferInfo.mFence = mDrawingState.acquireFence;
3483 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3484 mBufferInfo.mPixelFormat =
3485 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3486 mBufferInfo.mFrameLatencyNeeded = true;
3487 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3488 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3489 mBufferInfo.mFence = mDrawingState.acquireFence;
3490 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3491 auto lastDataspace = mBufferInfo.mDataspace;
3492 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3493 if (lastDataspace != mBufferInfo.mDataspace) {
3494 mFlinger->mSomeDataspaceChanged = true;
3495 }
3496 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3497 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3498 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3499 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3500 mBufferInfo.mApi = mDrawingState.api;
3501 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
3502 mBufferInfo.mBufferSlot = mHwcSlotGenerator->getHwcCacheSlot(mDrawingState.clientCacheId);
3503}
3504
3505Rect Layer::computeBufferCrop(const State& s) {
3506 if (s.buffer && !s.bufferCrop.isEmpty()) {
3507 Rect bufferCrop;
3508 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3509 return bufferCrop;
3510 } else if (s.buffer) {
3511 return s.buffer->getBounds();
3512 } else {
3513 return s.bufferCrop;
3514 }
3515}
3516
3517sp<Layer> Layer::createClone() {
3518 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3519 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003520 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003521 layer->mHwcSlotGenerator = mHwcSlotGenerator;
3522 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3523 return layer;
3524}
3525
3526bool Layer::bufferNeedsFiltering() const {
3527 const State& s(getDrawingState());
3528 if (!s.buffer) {
3529 return false;
3530 }
3531
3532 int32_t bufferWidth = static_cast<int32_t>(s.buffer->getWidth());
3533 int32_t bufferHeight = static_cast<int32_t>(s.buffer->getHeight());
3534
3535 // Undo any transformations on the buffer and return the result.
3536 if (s.bufferTransform & ui::Transform::ROT_90) {
3537 std::swap(bufferWidth, bufferHeight);
3538 }
3539
3540 if (s.transformToDisplayInverse) {
3541 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3542 if (invTransform & ui::Transform::ROT_90) {
3543 std::swap(bufferWidth, bufferHeight);
3544 }
3545 }
3546
3547 const Rect layerSize{getBounds()};
3548 int32_t layerWidth = layerSize.getWidth();
3549 int32_t layerHeight = layerSize.getHeight();
3550
3551 // Align the layer orientation with the buffer before comparism
3552 if (mTransformHint & ui::Transform::ROT_90) {
3553 std::swap(layerWidth, layerHeight);
3554 }
3555
3556 return layerWidth != bufferWidth || layerHeight != bufferHeight;
3557}
3558
3559void Layer::decrementPendingBufferCount() {
3560 int32_t pendingBuffers = --mPendingBufferTransactions;
3561 tracePendingBufferCount(pendingBuffers);
3562}
3563
3564void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3565 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3566}
3567
3568/*
3569 * We don't want to send the layer's transform to input, but rather the
3570 * parent's transform. This is because Layer's transform is
3571 * information about how the buffer is placed on screen. The parent's
3572 * transform makes more sense to send since it's information about how the
3573 * layer is placed on screen. This transform is used by input to determine
3574 * how to go from screen space back to window space.
3575 */
3576ui::Transform Layer::getInputTransform() const {
3577 if (!hasBufferOrSidebandStream()) {
3578 return getTransform();
3579 }
3580 sp<Layer> parent = mDrawingParent.promote();
3581 if (parent == nullptr) {
3582 return ui::Transform();
3583 }
3584
3585 return parent->getTransform();
3586}
3587
3588/**
3589 * Similar to getInputTransform, we need to update the bounds to include the transform.
3590 * This is because bounds don't include the buffer transform, where the input assumes
3591 * that's already included.
3592 */
3593Rect Layer::getInputBounds() const {
3594 if (!hasBufferOrSidebandStream()) {
3595 return getCroppedBufferSize(getDrawingState());
3596 }
3597
3598 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
3599 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
3600 return bufferBounds;
3601 }
3602 return mDrawingState.transform.transform(bufferBounds);
3603}
3604
3605bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3606 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3607
3608 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3609 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3610 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3611 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3612 layer_state_t::eReparent;
3613
3614 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3615 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3616 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3617 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3618 layer_state_t::eInputInfoChanged;
3619
3620 if ((s.what & requiredFlags) != requiredFlags) {
3621 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3622 (s.what | requiredFlags) & ~s.what);
3623 return false;
3624 }
3625
3626 if (s.what & deniedFlags) {
3627 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3628 return false;
3629 }
3630
3631 if (s.what & allowedFlags) {
3632 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3633 }
3634
3635 if (s.what & layer_state_t::ePositionChanged) {
3636 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3637 ALOGV("%s: false [ePositionChanged changed]", __func__);
3638 return false;
3639 }
3640 }
3641
3642 if (s.what & layer_state_t::eAlphaChanged) {
3643 if (mDrawingState.color.a != s.alpha) {
3644 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3645 return false;
3646 }
3647 }
3648
3649 if (s.what & layer_state_t::eColorTransformChanged) {
3650 if (mDrawingState.colorTransform != s.colorTransform) {
3651 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3652 return false;
3653 }
3654 }
3655
3656 if (s.what & layer_state_t::eBackgroundColorChanged) {
3657 if (mDrawingState.bgColorLayer || s.bgColorAlpha != 0) {
3658 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3659 return false;
3660 }
3661 }
3662
3663 if (s.what & layer_state_t::eMatrixChanged) {
3664 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3665 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3666 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3667 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3668 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3669 return false;
3670 }
3671 }
3672
3673 if (s.what & layer_state_t::eCornerRadiusChanged) {
3674 if (mDrawingState.cornerRadius != s.cornerRadius) {
3675 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3676 return false;
3677 }
3678 }
3679
3680 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3681 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3682 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3683 return false;
3684 }
3685 }
3686
3687 if (s.what & layer_state_t::eTransformChanged) {
3688 if (mDrawingState.bufferTransform != s.transform) {
3689 ALOGV("%s: false [eTransformChanged changed]", __func__);
3690 return false;
3691 }
3692 }
3693
3694 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3695 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3696 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3697 return false;
3698 }
3699 }
3700
3701 if (s.what & layer_state_t::eCropChanged) {
3702 if (mDrawingState.crop != s.crop) {
3703 ALOGV("%s: false [eCropChanged changed]", __func__);
3704 return false;
3705 }
3706 }
3707
3708 if (s.what & layer_state_t::eDataspaceChanged) {
3709 if (mDrawingState.dataspace != s.dataspace) {
3710 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3711 return false;
3712 }
3713 }
3714
3715 if (s.what & layer_state_t::eHdrMetadataChanged) {
3716 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3717 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3718 return false;
3719 }
3720 }
3721
3722 if (s.what & layer_state_t::eSidebandStreamChanged) {
3723 if (mDrawingState.sidebandStream != s.sidebandStream) {
3724 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3725 return false;
3726 }
3727 }
3728
3729 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3730 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3731 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3732 return false;
3733 }
3734 }
3735
3736 if (s.what & layer_state_t::eShadowRadiusChanged) {
3737 if (mDrawingState.shadowRadius != s.shadowRadius) {
3738 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3739 return false;
3740 }
3741 }
3742
3743 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3744 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3745 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3746 return false;
3747 }
3748 }
3749
3750 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3751 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3752 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3753 return false;
3754 }
3755 }
3756
3757 if (s.what & layer_state_t::eStretchChanged) {
3758 StretchEffect temp = s.stretchEffect;
3759 temp.sanitize();
3760 if (mDrawingState.stretchEffect != temp) {
3761 ALOGV("%s: false [eStretchChanged changed]", __func__);
3762 return false;
3763 }
3764 }
3765
3766 if (s.what & layer_state_t::eBufferCropChanged) {
3767 if (mDrawingState.bufferCrop != s.bufferCrop) {
3768 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3769 return false;
3770 }
3771 }
3772
3773 if (s.what & layer_state_t::eDestinationFrameChanged) {
3774 if (mDrawingState.destinationFrame != s.destinationFrame) {
3775 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3776 return false;
3777 }
3778 }
3779
3780 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3781 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3782 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3783 return false;
3784 }
3785 }
3786
3787 ALOGV("%s: true", __func__);
3788 return true;
3789}
3790
3791bool Layer::isHdrY410() const {
3792 // pixel format is HDR Y410 masquerading as RGBA_1010102
3793 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3794 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3795 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3796}
3797
3798sp<compositionengine::LayerFE> Layer::getCompositionEngineLayerFE() const {
3799 // There's no need to get a CE Layer if the layer isn't going to draw anything.
3800 if (hasSomethingToDraw()) {
3801 return asLayerFE();
3802 } else {
3803 return nullptr;
3804 }
3805}
3806
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003807const Layer::LayerSnapshot* Layer::getLayerSnapshot() const {
3808 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003809}
3810
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003811Layer::LayerSnapshot* Layer::editLayerSnapshot() {
3812 return mSnapshot.get();
3813}
Patrick Williamsbb25f802022-08-30 23:02:34 +00003814const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003815 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003816}
3817
3818void Layer::useSurfaceDamage() {
3819 if (mFlinger->mForceFullDamage) {
3820 surfaceDamageRegion = Region::INVALID_REGION;
3821 } else {
3822 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3823 }
3824}
3825
3826void Layer::useEmptyDamage() {
3827 surfaceDamageRegion.clear();
3828}
3829
3830bool Layer::isOpaque(const Layer::State& s) const {
3831 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3832 // layer's opaque flag.
3833 if (!hasSomethingToDraw()) {
3834 return false;
3835 }
3836
3837 // if the layer has the opaque flag, then we're always opaque
3838 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3839 return true;
3840 }
3841
3842 // If the buffer has no alpha channel, then we are opaque
3843 if (hasBufferOrSidebandStream() && isOpaqueFormat(getPixelFormat())) {
3844 return true;
3845 }
3846
3847 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3848 return fillsColor() && getAlpha() == 1.0_hf;
3849}
3850
3851bool Layer::canReceiveInput() const {
3852 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3853}
3854
3855bool Layer::isVisible() const {
3856 if (!hasSomethingToDraw()) {
3857 return false;
3858 }
3859
3860 if (isHiddenByPolicy()) {
3861 return false;
3862 }
3863
3864 return getAlpha() > 0.0f || hasBlur();
3865}
3866
3867void Layer::onPostComposition(const DisplayDevice* display,
3868 const std::shared_ptr<FenceTime>& glDoneFence,
3869 const std::shared_ptr<FenceTime>& presentFence,
3870 const CompositorTiming& compositorTiming) {
3871 // mFrameLatencyNeeded is true when a new frame was latched for the
3872 // composition.
3873 if (!mBufferInfo.mFrameLatencyNeeded) return;
3874
3875 for (const auto& handle : mDrawingState.callbackHandles) {
3876 handle->gpuCompositionDoneFence = glDoneFence;
3877 handle->compositorTiming = compositorTiming;
3878 }
3879
3880 // Update mFrameTracker.
3881 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3882 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3883
3884 const int32_t layerId = getSequence();
3885 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3886
3887 const auto outputLayer = findOutputLayerForDisplay(display);
3888 if (outputLayer && outputLayer->requiresClientComposition()) {
3889 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3890 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3891 clientCompositionTimestamp,
3892 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3893 // Update the SurfaceFrames in the drawing state
3894 if (mDrawingState.bufferSurfaceFrameTX) {
3895 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3896 }
3897 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3898 surfaceFrame->setGpuComposition();
3899 }
3900 }
3901
3902 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3903 if (frameReadyFence->isValid()) {
3904 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3905 } else {
3906 // There was no fence for this frame, so assume that it was ready
3907 // to be presented at the desired present time.
3908 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3909 }
3910
3911 if (display) {
Dominik Laskowskif8734e02022-08-26 09:06:59 -07003912 const Fps refreshRate = display->refreshRateConfigs().getActiveModePtr()->getFps();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003913 const std::optional<Fps> renderRate =
3914 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3915
3916 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3917 const auto gameMode = getGameMode();
3918
3919 if (presentFence->isValid()) {
3920 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3921 refreshRate, renderRate, vote, gameMode);
3922 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3923 presentFence,
3924 FrameTracer::FrameEvent::PRESENT_FENCE);
3925 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3926 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3927 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003928 // The HWC doesn't support present fences, so use the present timestamp instead.
3929 const nsecs_t presentTimestamp =
3930 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3931
3932 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3933 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3934 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3935
Patrick Williamsbb25f802022-08-30 23:02:34 +00003936 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3937 refreshRate, renderRate, vote, gameMode);
3938 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3939 mCurrentFrameNumber, actualPresentTime,
3940 FrameTracer::FrameEvent::PRESENT_FENCE);
3941 mFrameTracker.setActualPresentTime(actualPresentTime);
3942 }
3943 }
3944
3945 mFrameTracker.advanceFrame();
3946 mBufferInfo.mFrameLatencyNeeded = false;
3947}
3948
3949bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
3950 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3951 getDrawingState().frameNumber);
3952
3953 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3954
3955 if (refreshRequired) {
3956 return refreshRequired;
3957 }
3958
3959 // If the head buffer's acquire fence hasn't signaled yet, return and
3960 // try again later
3961 if (!fenceHasSignaled()) {
3962 ATRACE_NAME("!fenceHasSignaled()");
3963 mFlinger->onLayerUpdate();
3964 return false;
3965 }
3966
3967 updateTexImage(latchTime);
3968 if (mDrawingState.buffer == nullptr) {
3969 return false;
3970 }
3971
3972 // Capture the old state of the layer for comparisons later
3973 BufferInfo oldBufferInfo = mBufferInfo;
3974 const bool oldOpacity = isOpaque(mDrawingState);
3975 mPreviousFrameNumber = mCurrentFrameNumber;
3976 mCurrentFrameNumber = mDrawingState.frameNumber;
3977 gatherBufferInfo();
3978
3979 if (oldBufferInfo.mBuffer == nullptr) {
3980 // the first time we receive a buffer, we need to trigger a
3981 // geometry invalidation.
3982 recomputeVisibleRegions = true;
3983 }
3984
3985 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3986 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3987 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3988 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3989 recomputeVisibleRegions = true;
3990 }
3991
3992 if (oldBufferInfo.mBuffer != nullptr) {
3993 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3994 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3995 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3996 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3997 recomputeVisibleRegions = true;
3998 }
3999 }
4000
4001 if (oldOpacity != isOpaque(mDrawingState)) {
4002 recomputeVisibleRegions = true;
4003 }
4004
4005 return true;
4006}
4007
4008bool Layer::hasReadyFrame() const {
4009 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4010}
4011
4012bool Layer::isProtected() const {
4013 return (mBufferInfo.mBuffer != nullptr) &&
4014 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4015}
4016
4017// As documented in libhardware header, formats in the range
4018// 0x100 - 0x1FF are specific to the HAL implementation, and
4019// are known to have no alpha channel
4020// TODO: move definition for device-specific range into
4021// hardware.h, instead of using hard-coded values here.
4022#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
4023
4024bool Layer::isOpaqueFormat(PixelFormat format) {
4025 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
4026 return true;
4027 }
4028 switch (format) {
4029 case PIXEL_FORMAT_RGBA_8888:
4030 case PIXEL_FORMAT_BGRA_8888:
4031 case PIXEL_FORMAT_RGBA_FP16:
4032 case PIXEL_FORMAT_RGBA_1010102:
4033 case PIXEL_FORMAT_R_8:
4034 return false;
4035 }
4036 // in all other case, we have no blending (also for unknown formats)
4037 return true;
4038}
4039
4040bool Layer::needsFiltering(const DisplayDevice* display) const {
4041 if (!hasBufferOrSidebandStream()) {
4042 return false;
4043 }
4044 const auto outputLayer = findOutputLayerForDisplay(display);
4045 if (outputLayer == nullptr) {
4046 return false;
4047 }
4048
4049 // We need filtering if the sourceCrop rectangle size does not match the
4050 // displayframe rectangle size (not a 1:1 render)
4051 const auto& compositionState = outputLayer->getState();
4052 const auto displayFrame = compositionState.displayFrame;
4053 const auto sourceCrop = compositionState.sourceCrop;
4054 return sourceCrop.getHeight() != displayFrame.getHeight() ||
4055 sourceCrop.getWidth() != displayFrame.getWidth();
4056}
4057
4058bool Layer::needsFilteringForScreenshots(const DisplayDevice* display,
4059 const ui::Transform& inverseParentTransform) const {
4060 if (!hasBufferOrSidebandStream()) {
4061 return false;
4062 }
4063 const auto outputLayer = findOutputLayerForDisplay(display);
4064 if (outputLayer == nullptr) {
4065 return false;
4066 }
4067
4068 // We need filtering if the sourceCrop rectangle size does not match the
4069 // viewport rectangle size (not a 1:1 render)
4070 const auto& compositionState = outputLayer->getState();
4071 const ui::Transform& displayTransform = display->getTransform();
4072 const ui::Transform inverseTransform = inverseParentTransform * displayTransform.inverse();
4073 // Undo the transformation of the displayFrame so that we're back into
4074 // layer-stack space.
4075 const Rect frame = inverseTransform.transform(compositionState.displayFrame);
4076 const FloatRect sourceCrop = compositionState.sourceCrop;
4077
4078 int32_t frameHeight = frame.getHeight();
4079 int32_t frameWidth = frame.getWidth();
4080 // If the display transform had a rotational component then undo the
4081 // rotation so that the orientation matches the source crop.
4082 if (displayTransform.getOrientation() & ui::Transform::ROT_90) {
4083 std::swap(frameHeight, frameWidth);
4084 }
4085 return sourceCrop.getHeight() != frameHeight || sourceCrop.getWidth() != frameWidth;
4086}
4087
4088void Layer::latchAndReleaseBuffer() {
4089 if (hasReadyFrame()) {
4090 bool ignored = false;
4091 latchBuffer(ignored, systemTime());
4092 }
4093 releasePendingBuffer(systemTime());
4094}
4095
4096PixelFormat Layer::getPixelFormat() const {
4097 return mBufferInfo.mPixelFormat;
4098}
4099
4100bool Layer::getTransformToDisplayInverse() const {
4101 return mBufferInfo.mTransformToDisplayInverse;
4102}
4103
4104Rect Layer::getBufferCrop() const {
4105 // this is the crop rectangle that applies to the buffer
4106 // itself (as opposed to the window)
4107 if (!mBufferInfo.mCrop.isEmpty()) {
4108 // if the buffer crop is defined, we use that
4109 return mBufferInfo.mCrop;
4110 } else if (mBufferInfo.mBuffer != nullptr) {
4111 // otherwise we use the whole buffer
4112 return mBufferInfo.mBuffer->getBounds();
4113 } else {
4114 // if we don't have a buffer yet, we use an empty/invalid crop
4115 return Rect();
4116 }
4117}
4118
4119uint32_t Layer::getBufferTransform() const {
4120 return mBufferInfo.mTransform;
4121}
4122
4123ui::Dataspace Layer::getDataSpace() const {
4124 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
4125}
4126
4127ui::Dataspace Layer::getRequestedDataSpace() const {
4128 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4129}
4130
4131ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4132 ui::Dataspace updatedDataspace = dataspace;
4133 // translate legacy dataspaces to modern dataspaces
4134 switch (dataspace) {
4135 case ui::Dataspace::SRGB:
4136 updatedDataspace = ui::Dataspace::V0_SRGB;
4137 break;
4138 case ui::Dataspace::SRGB_LINEAR:
4139 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4140 break;
4141 case ui::Dataspace::JFIF:
4142 updatedDataspace = ui::Dataspace::V0_JFIF;
4143 break;
4144 case ui::Dataspace::BT601_625:
4145 updatedDataspace = ui::Dataspace::V0_BT601_625;
4146 break;
4147 case ui::Dataspace::BT601_525:
4148 updatedDataspace = ui::Dataspace::V0_BT601_525;
4149 break;
4150 case ui::Dataspace::BT709:
4151 updatedDataspace = ui::Dataspace::V0_BT709;
4152 break;
4153 default:
4154 break;
4155 }
4156
4157 return updatedDataspace;
4158}
4159
4160sp<GraphicBuffer> Layer::getBuffer() const {
4161 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4162}
4163
4164void Layer::getDrawingTransformMatrix(bool filteringEnabled, float outMatrix[16]) const {
4165 sp<GraphicBuffer> buffer = getBuffer();
4166 if (!buffer) {
4167 ALOGE("Buffer should not be null!");
4168 return;
4169 }
4170 GLConsumer::computeTransformMatrix(outMatrix, buffer->getWidth(), buffer->getHeight(),
4171 buffer->getPixelFormat(), mBufferInfo.mCrop,
4172 mBufferInfo.mTransform, filteringEnabled);
4173}
4174
4175void Layer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
4176 mTransformHint = getFixedTransformHint();
4177 if (mTransformHint == ui::Transform::ROT_INVALID) {
4178 mTransformHint = displayTransformHint;
4179 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004180 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004181}
4182
4183const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4184 return mBufferInfo.mBuffer;
4185}
4186
4187bool Layer::setColor(const half3& color) {
4188 if (mDrawingState.color.r == color.r && mDrawingState.color.g == color.g &&
4189 mDrawingState.color.b == color.b) {
4190 return false;
4191 }
4192
4193 mDrawingState.sequence++;
4194 mDrawingState.color.r = color.r;
4195 mDrawingState.color.g = color.g;
4196 mDrawingState.color.b = color.b;
4197 mDrawingState.modified = true;
4198 setTransactionFlags(eTransactionNeeded);
4199 return true;
4200}
4201
4202bool Layer::fillsColor() const {
4203 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4204 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4205}
4206
4207bool Layer::hasBlur() const {
4208 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4209}
4210
Vishnu Nairba354102022-08-01 00:14:18 +00004211void Layer::updateSnapshot(bool updateGeometry) {
4212 if (!getCompositionEngineLayerFE()) {
4213 return;
4214 }
4215
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004216 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004217 if (updateGeometry) {
4218 prepareBasicGeometryCompositionState();
4219 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004220 snapshot->roundedCorner = getRoundedCornerState();
4221 snapshot->stretchEffect = getStretchEffect();
4222 snapshot->transformedBounds = mScreenBounds;
4223 if (mEffectiveShadowRadius > 0.f) {
4224 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4225
4226 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4227 // it if transparent regions are present. This may not be necessary since shadows are
4228 // typically cast by layers without transparent regions.
4229 snapshot->shadowSettings.boundaries = mBounds;
4230
4231 const float casterAlpha = snapshot->alpha;
4232 const bool casterIsOpaque =
4233 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4234
4235 // If the casting layer is translucent, we need to fill in the shadow underneath the
4236 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4237 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4238 snapshot->shadowSettings.ambientColor *= casterAlpha;
4239 snapshot->shadowSettings.spotColor *= casterAlpha;
4240 }
4241 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004242 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004243 snapshot->contentOpaque = isOpaque(mDrawingState);
4244 snapshot->isHdrY410 = isHdrY410();
4245 snapshot->bufferNeedsFiltering = bufferNeedsFiltering();
4246 sp<Layer> p = mDrawingParent.promote();
4247 if (p != nullptr) {
4248 snapshot->transform = p->getTransform();
4249 } else {
4250 snapshot->transform.reset();
4251 }
4252 snapshot->bufferSize = getBufferSize(mDrawingState);
4253 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Nairba354102022-08-01 00:14:18 +00004254 preparePerFrameCompositionState();
4255}
4256
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004257void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4258 mSnapshot->layerMetadata = parentMetadata;
4259 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4260 for (const sp<Layer>& child : mDrawingChildren) {
4261 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4262 }
4263}
4264
4265void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4266 std::unordered_set<Layer*>& visited) {
4267 if (visited.find(this) != visited.end()) {
4268 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4269 return;
4270 }
4271 visited.insert(this);
4272
4273 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4274
4275 if (mDrawingState.zOrderRelatives.empty()) {
4276 return;
4277 }
4278 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4279 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4280 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4281 sp<Layer> relative = weakRelative.promote();
4282 if (!relative) {
4283 continue;
4284 }
4285 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4286 }
4287}
4288
Mathias Agopian13127d82013-03-05 17:47:11 -08004289// ---------------------------------------------------------------------------
4290
Marin Shalamanov46084422020-10-13 12:33:42 +02004291std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004292 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4293 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004294}
4295
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004296} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004297
4298#if defined(__gl_h_)
4299#error "don't include gl/gl.h in this file"
4300#endif
4301
4302#if defined(__gl2_h_)
4303#error "don't include gl2/gl2.h in this file"
4304#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004305
4306// TODO(b/129481165): remove the #pragma below and fix conversion issues
4307#pragma clang diagnostic pop // ignored "-Wconversion"