blob: 539f2fe353ad0b639051b1e769baee00c4f2891f [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Dan Stoza9e56aa02015-11-02 13:00:03 -080021//#define LOG_NDEBUG 0
22#undef LOG_TAG
23#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080024#define ATRACE_TAG ATRACE_TAG_GRAPHICS
25
Alec Mourie60041e2019-06-14 18:59:51 -070026#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080027
[1;3C2b9fc252021-02-04 16:16:50 -080028#include <android-base/properties.h>
Yiwei Zhang5434a782018-12-05 18:06:32 -080029#include <android-base/stringprintf.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080030#include <android/native_window.h>
Vishnu Nair0f085c62019-08-30 08:49:12 -070031#include <binder/IPCThreadState.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000032#include <compositionengine/CompositionEngine.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080033#include <compositionengine/Display.h>
Lloyd Piquea83776c2019-01-29 18:42:32 -080034#include <compositionengine/LayerFECompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080035#include <compositionengine/OutputLayer.h>
36#include <compositionengine/impl/OutputLayerCompositionState.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070037#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070038#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070039#include <cutils/properties.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070040#include <ftl/enum.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080041#include <ftl/fake_guard.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080042#include <gui/BufferItem.h>
43#include <gui/LayerDebugInfo.h>
44#include <gui/Surface.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000045#include <gui/TraceUtils.h>
Alec Mourie60041e2019-06-14 18:59:51 -070046#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070047#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070049#include <stdint.h>
50#include <stdlib.h>
51#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000052#include <system/graphics-base-v1.0.h>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070053#include <ui/DataspaceUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080054#include <ui/DebugUtils.h>
55#include <ui/GraphicBuffer.h>
56#include <ui/PixelFormat.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#include <utils/Errors.h>
58#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080059#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080061#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Alec Mourie60041e2019-06-14 18:59:51 -070063#include <algorithm>
64#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070065#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070066#include <sstream>
67
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070068#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080069#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070070#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070071#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +000072#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000073#include "FrontEnd/LayerHandle.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080074#include "LayerProtoHelper.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080076#include "TimeStats/TimeStats.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070077#include "TunnelModeEnabledReporter.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070078
David Sodman41fdfc92017-11-06 16:09:56 -080079#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000080#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082namespace android {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010083namespace {
84constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000085
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000086const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000087
Patrick Williamsbb25f802022-08-30 23:02:34 +000088bool assignTransform(ui::Transform* dst, ui::Transform& from) {
89 if (*dst == from) {
90 return false;
91 }
92 *dst = from;
93 return true;
94}
95
96TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
97 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
98 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
99 const auto frameRateCompatibility = [frameRate] {
100 switch (frameRate.type) {
101 case Layer::FrameRateCompatibility::Default:
102 return FrameRateCompatibility::Default;
103 case Layer::FrameRateCompatibility::ExactOrMultiple:
104 return FrameRateCompatibility::ExactOrMultiple;
105 default:
106 return FrameRateCompatibility::Undefined;
107 }
108 }();
109
110 const auto seamlessness = [frameRate] {
111 switch (frameRate.seamlessness) {
112 case scheduler::Seamlessness::OnlySeamless:
113 return Seamlessness::ShouldBeSeamless;
114 case scheduler::Seamlessness::SeamedAndSeamless:
115 return Seamlessness::NotRequired;
116 default:
117 return Seamlessness::Undefined;
118 }
119 }();
120
121 return TimeStats::SetFrameRateVote{.frameRate = frameRate.rate.getValue(),
122 .frameRateCompatibility = frameRateCompatibility,
123 .seamlessness = seamlessness};
124}
125
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100126} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700128using namespace ftl::flag_operators;
129
Yiwei Zhang5434a782018-12-05 18:06:32 -0800130using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000131using frontend::LayerSnapshot;
132using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800133using gui::GameMode;
134using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500135using gui::WindowInfo;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800136
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700137using PresentState = frametimeline::SurfaceFrame::PresentState;
138
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700139Layer::Layer(const LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000140 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700141 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000142 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700143 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800144 mWindowType(static_cast<WindowInfo::Type>(
145 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000146 mLayerCreationFlags(args.flags),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000147 mBorderEnabled(false),
148 mTextureName(args.textureName),
Vishnu Naire14c6b32022-08-06 04:20:15 +0000149 mLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000150 ALOGV("Creating Layer %s", getDebugName());
151
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700152 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700153 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
154 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
155 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700156 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
157 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700158 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700159 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700160 mDrawingState.z = 0;
161 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700162 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700163 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700164 mDrawingState.transform.set(0, 0);
165 mDrawingState.frameNumber = 0;
166 mDrawingState.bufferTransform = 0;
167 mDrawingState.transformToDisplayInverse = false;
168 mDrawingState.crop.makeInvalid();
169 mDrawingState.acquireFence = sp<Fence>::make(-1);
170 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
171 mDrawingState.dataspace = ui::Dataspace::UNKNOWN;
Vishnu Nairbc4ee5c2022-08-16 03:19:37 +0000172 mDrawingState.dataspaceRequested = false;
Robert Carr6a160312021-05-17 12:08:20 -0700173 mDrawingState.hdrMetadata.validTypes = 0;
174 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
175 mDrawingState.cornerRadius = 0.0f;
176 mDrawingState.backgroundBlurRadius = 0;
177 mDrawingState.api = -1;
178 mDrawingState.hasColorTransform = false;
179 mDrawingState.colorSpaceAgnostic = false;
180 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
181 mDrawingState.metadata = args.metadata;
182 mDrawingState.shadowRadius = 0.f;
183 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
184 mDrawingState.frameTimelineInfo = {};
185 mDrawingState.postTime = -1;
186 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000187 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700188 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700189 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000190 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700191
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700192 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
193 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700194 mDrawingState.color.r = -1.0_hf;
195 mDrawingState.color.g = -1.0_hf;
196 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700197 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700198
Dominik Laskowski596a2562022-10-28 11:26:12 -0400199 mFrameTracker.setDisplayRefreshPeriod(args.flinger->mScheduler->getLeaderVsyncPeriod());
Robert Carr2e102c92018-10-23 12:11:15 -0700200
Vishnu Naircb8be502022-10-12 19:03:23 +0000201 mOwnerUid = args.ownerUid;
202 mOwnerPid = args.ownerPid;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000203
204 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
205 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
206 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
207 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000208
209 mSnapshot->sequence = sequence;
210 mSnapshot->name = getDebugName();
211 mSnapshot->textureName = mTextureName;
212 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000213 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800214}
215
216void Layer::onFirstRef() {
217 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700218}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700219
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700220Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000221 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
222 "Layer destructor called off the main thread.");
223
Patrick Williamsbb25f802022-08-30 23:02:34 +0000224 // The original layer and the clone layer share the same texture and buffer. Therefore, only
225 // one of the layers, in this case the original layer, needs to handle the deletion. The
226 // original layer and the clone should be removed at the same time so there shouldn't be any
227 // issue with the clone layer trying to use the texture.
228 if (mBufferInfo.mBuffer != nullptr) {
229 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
230 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
231 mBufferInfo.mFence,
232 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
233 mOwnerUid));
234 }
235 if (!isClone()) {
236 // The original layer and the clone layer share the same texture. Therefore, only one of
237 // the layers, in this case the original layer, needs to handle the deletion. The original
238 // layer and the clone should be removed at the same time so there shouldn't be any issue
239 // with the clone layer trying to use the deleted texture.
240 mFlinger->deleteTextureAsync(mTextureName);
241 }
242 const int32_t layerId = getSequence();
243 mFlinger->mTimeStats->onDestroy(layerId);
244 mFlinger->mFrameTracer->onDestroy(layerId);
245
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000246 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700247 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700248
249 if (mDrawingState.sidebandStream != nullptr) {
250 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
251 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700252 if (mHadClonedChild) {
253 mFlinger->mNumClones--;
254 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000255 if (hasTrustedPresentationListener()) {
256 mFlinger->mNumTrustedPresentationListeners--;
257 updateTrustedPresentationState(nullptr, -1 /* time_in_ms */, true /* leaveState*/);
258 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700259}
260
Mathias Agopian13127d82013-03-05 17:47:11 -0800261// ---------------------------------------------------------------------------
262// callbacks
263// ---------------------------------------------------------------------------
264
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700265void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700266 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700267 return;
268 }
Robert Carr2e102c92018-10-23 12:11:15 -0700269
Robert Carr6a160312021-05-17 12:08:20 -0700270 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700271 if (strongRelative == nullptr) {
272 setZOrderRelativeOf(nullptr);
273 return;
274 }
275
276 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700277 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700278 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800279 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700280 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700281}
282
283void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700284 if (!mRemovedFromDrawingState) {
285 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700286 mFlinger->mScheduler->deregisterLayer(this);
287 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000288 updateTrustedPresentationState(nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000289
Ady Abrahamd11bade2022-08-01 16:18:03 -0700290 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700291}
Chia-I Wu38512252017-05-17 14:36:16 -0700292
chaviw68d4dab2020-06-08 15:07:32 -0700293sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000294 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700295 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700296 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700297 }
298 return parent->getRootLayer();
299}
300
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700301void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700302 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
303 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700304 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700305
306 traverse(LayerVector::StateSet::Current, [&](Layer* layer) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700307 layer->removeFromCurrentState();
308 layer->removeRelativeZ(layersInTree);
chaviw68d4dab2020-06-08 15:07:32 -0700309 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700310}
311
chaviw61626f22018-11-15 16:26:27 -0800312void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700313 if (mRemovedFromDrawingState) {
314 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700315 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700316 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700317 }
chaviw61626f22018-11-15 16:26:27 -0800318
319 for (const auto& child : mCurrentChildren) {
320 child->addToCurrentState();
321 }
322}
323
Mathias Agopian13127d82013-03-05 17:47:11 -0800324// ---------------------------------------------------------------------------
325// set-up
326// ---------------------------------------------------------------------------
327
chaviw13fdc492017-06-27 12:40:18 -0700328bool Layer::getPremultipledAlpha() const {
329 return mPremultipliedAlpha;
330}
331
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700332sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800333 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700334 if (mGetHandleCalled) {
335 ALOGE("Get handle called twice" );
336 return nullptr;
337 }
338 mGetHandleCalled = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000339 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800340}
341
342// ---------------------------------------------------------------------------
343// h/w composer set-up
344// ---------------------------------------------------------------------------
345
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700346static Rect reduce(const Rect& win, const Region& exclude) {
347 if (CC_LIKELY(exclude.isEmpty())) {
348 return win;
349 }
350 if (exclude.isRect()) {
351 return win.reduce(exclude.getBounds());
352 }
353 return Region(win).subtract(exclude).getBounds();
354}
355
Dan Stoza80d61162017-12-20 15:57:52 -0800356static FloatRect reduce(const FloatRect& win, const Region& exclude) {
357 if (CC_LIKELY(exclude.isEmpty())) {
358 return win;
359 }
360 // Convert through Rect (by rounding) for lack of FloatRegion
361 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
362}
363
Vishnu Nair4351ad52019-02-11 14:13:02 -0800364Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800365 if (!reduceTransparentRegion) {
366 return Rect{mScreenBounds};
367 }
368
369 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800370 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800371 // Transform to screen space.
372 bounds = t.transform(bounds);
373 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700374}
375
Vishnu Nair4351ad52019-02-11 14:13:02 -0800376FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000377 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800378 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700379}
380
Vishnu Nairf0c28512019-02-08 12:40:28 -0800381FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
382 // Subtract the transparent region and snap to the bounds.
383 return reduce(mBounds, activeTransparentRegion);
384}
385
Chavi Weingarten076acac2023-01-19 17:20:43 +0000386// No early returns.
387void Layer::updateTrustedPresentationState(const DisplayDevice* display, int64_t time_in_ms,
388 bool leaveState) {
389 if (!hasTrustedPresentationListener()) {
390 return;
391 }
392 const bool lastState = mLastComputedTrustedPresentationState;
393 mLastComputedTrustedPresentationState = false;
394
395 if (!leaveState) {
396 const auto outputLayer = findOutputLayerForDisplay(display);
397 if (outputLayer != nullptr) {
398 mLastComputedTrustedPresentationState =
399 computeTrustedPresentationState(mBounds, mSourceBounds,
400 outputLayer->getState().coveredRegion,
401 mScreenBounds, getCompositionState()->alpha,
402 getCompositionState()->geomLayerTransform,
403 mTrustedPresentationThresholds);
404 }
405 }
406 const bool newState = mLastComputedTrustedPresentationState;
407 if (lastState && !newState) {
408 // We were in the trusted presentation state, but now we left it,
409 // emit the callback if needed
410 if (mLastReportedTrustedPresentationState) {
411 mLastReportedTrustedPresentationState = false;
412 mTrustedPresentationListener.invoke(false);
413 }
414 // Reset the timer
415 mEnteredTrustedPresentationStateTime = -1;
416 } else if (!lastState && newState) {
417 // We were not in the trusted presentation state, but we entered it, begin the timer
418 // and make sure this gets called at least once more!
419 mEnteredTrustedPresentationStateTime = time_in_ms;
420 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
421 }
422
423 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
424 if (!mLastReportedTrustedPresentationState && newState &&
425 (time_in_ms - mEnteredTrustedPresentationStateTime >
426 mTrustedPresentationThresholds.stabilityRequirementMs)) {
427 mLastReportedTrustedPresentationState = true;
428 mTrustedPresentationListener.invoke(true);
429 }
430}
431
432/**
433 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
434 * of how the parameters and thresholds are interpreted. The general spirit is
435 * to produce an upper bound on the amount of the buffer which was presented.
436 */
437bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
438 const Region& coveredRegion,
439 const FloatRect& screenBounds, float alpha,
440 const ui::Transform& effectiveTransform,
441 const TrustedPresentationThresholds& thresholds) {
442 if (alpha < thresholds.minAlpha) {
443 return false;
444 }
445 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
446 return false;
447 }
448 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
449 return false;
450 }
451
452 const float sx = effectiveTransform.dsdx();
453 const float sy = effectiveTransform.dsdy();
454 float fractionRendered = std::min(sx * sy, 1.0f);
455
456 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
457 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
458 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
459
460 Rect coveredBounds = coveredRegion.bounds();
461 fractionRendered *= (1 -
462 ((coveredBounds.width() / (float)screenBounds.getWidth()) *
463 coveredBounds.height() / (float)screenBounds.getHeight()));
464
465 if (fractionRendered < thresholds.minFractionRendered) {
466 return false;
467 }
468
469 return true;
470}
471
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700472void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
473 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800474 const State& s(getDrawingState());
475
476 // Calculate effective layer transform
477 mEffectiveTransform = parentTransform * getActiveTransform(s);
478
Garfield Tan2c1782c2022-02-16 15:25:05 -0800479 if (CC_UNLIKELY(!isTransformValid())) {
480 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
481 getDebugName());
482 return;
483 }
484
Vishnu Nair4351ad52019-02-11 14:13:02 -0800485 // Transform parent bounds to layer space
486 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
487
Vishnu Nairc652ff82019-03-15 12:48:54 -0700488 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800489 mSourceBounds = computeSourceBounds(parentBounds);
490
491 // Calculate bounds by croping diplay frame with layer crop and parent bounds
492 FloatRect bounds = mSourceBounds;
493 const Rect layerCrop = getCrop(s);
494 if (!layerCrop.isEmpty()) {
495 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
496 }
497 bounds = bounds.intersect(parentBounds);
498
499 mBounds = bounds;
500 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700501
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700502 // Use the layer's own shadow radius if set. Otherwise get the radius from
503 // parent.
504 if (s.shadowRadius > 0.f) {
505 mEffectiveShadowRadius = s.shadowRadius;
506 } else {
507 mEffectiveShadowRadius = parentShadowRadius;
508 }
509
510 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
511 // don't pass it to its children.
512 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
513
Vishnu Nair4351ad52019-02-11 14:13:02 -0800514 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700515 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800516 }
Vishnu Nairba354102022-08-01 00:14:18 +0000517
518 if (mPotentialCursor) {
519 prepareCursorCompositionState();
520 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800521}
522
Vishnu Nair60356342018-11-13 13:00:45 -0800523Rect Layer::getCroppedBufferSize(const State& s) const {
524 Rect size = getBufferSize(s);
525 Rect crop = getCrop(s);
526 if (!crop.isEmpty() && size.isValid()) {
527 size.intersect(crop, &size);
528 } else if (!crop.isEmpty()) {
529 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700530 }
Vishnu Nair60356342018-11-13 13:00:45 -0800531 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800532}
533
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700534void Layer::setupRoundedCornersCropCoordinates(Rect win,
535 const FloatRect& roundedCornersCrop) const {
536 // Translate win by the rounded corners rect coordinates, to have all values in
537 // layer coordinate space.
538 win.left -= roundedCornersCrop.left;
539 win.right -= roundedCornersCrop.left;
540 win.top -= roundedCornersCrop.top;
541 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700542}
543
Lloyd Piquede196652020-01-22 17:29:58 -0800544void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800545 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800546 const auto alpha = static_cast<float>(getAlpha());
547 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700548 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800549
550 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
551 if (!opaque || alpha != 1.0f) {
552 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
553 : Hwc2::IComposerClient::BlendMode::COVERAGE;
554 }
555
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000556 auto* snapshot = editLayerSnapshot();
557 snapshot->outputFilter = getOutputFilter();
558 snapshot->isVisible = isVisible();
559 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
560 snapshot->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800561
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000562 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800563 contentDirty = false;
564
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000565 snapshot->geomLayerBounds = mBounds;
566 snapshot->geomLayerTransform = getTransform();
567 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
568 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000569 snapshot->localTransform = getActiveTransform(drawingState);
570 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000571 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
572 snapshot->alpha = alpha;
573 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
574 snapshot->blurRegions = drawingState.blurRegions;
575 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800576}
577
Lloyd Piquede196652020-01-22 17:29:58 -0800578void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800579 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000580 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700581
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000582 snapshot->geomBufferSize = getBufferSize(drawingState);
583 snapshot->geomContentCrop = getBufferCrop();
584 snapshot->geomCrop = getCrop(drawingState);
585 snapshot->geomBufferTransform = getBufferTransform();
586 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
587 snapshot->geomUsesSourceCrop = usesSourceCrop();
588 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800589
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000590 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800591 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
592 for (const auto& [key, mandatory] : supportedMetadata) {
593 const auto& genericLayerMetadataCompatibilityMap =
594 mFlinger->getGenericLayerMetadataKeyMap();
595 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
596 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
597 continue;
598 }
599 const uint32_t id = compatIter->second;
600
601 auto it = drawingState.metadata.mMap.find(id);
602 if (it == std::end(drawingState.metadata.mMap)) {
603 continue;
604 }
605
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000606 snapshot->metadata.emplace(key,
607 compositionengine::GenericLayerMetadataEntry{mandatory,
608 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800609 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800610}
David Sodmanba340492018-08-05 21:51:33 -0700611
Lloyd Piquede196652020-01-22 17:29:58 -0800612void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800613 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000614 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800615
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000616 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800617
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000618 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
619 snapshot->dataspace = getDataSpace();
620 snapshot->colorTransform = getColorTransform();
621 snapshot->colorTransformIsIdentity = !hasColorTransform();
622 snapshot->surfaceDamage = surfaceDamageRegion;
623 snapshot->hasProtectedContent = isProtected();
624 snapshot->dimmingEnabled = isDimmingEnabled();
Lloyd Pique688abd42019-02-15 15:42:24 -0800625
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700626 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700627
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000628 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800629
630 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400631 // Rounded corners no longer force client composition, since we may use a
632 // hole punch so that the layer will appear to have rounded corners.
633 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000634 snapshot->stretchEffect.hasEffect()) {
635 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800636 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700637 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000638 snapshot->blurRegions = drawingState.blurRegions;
639 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400640
641 // Layer framerate is used in caching decisions.
642 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
643 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000644 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000645
646 if (hasBufferOrSidebandStream()) {
647 preparePerFrameBufferCompositionState();
648 } else {
649 preparePerFrameEffectsCompositionState();
650 }
651}
652
653void Layer::preparePerFrameBufferCompositionState() {
654 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000655 auto* snapshot = editLayerSnapshot();
656 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
657 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000658 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
659 return;
660 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000661 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000662 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
663 } else {
664 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000665 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
666 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000667 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
668 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
669 }
670
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000671 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000672 snapshot->acquireFence = mBufferInfo.mFence;
673 snapshot->frameNumber = mBufferInfo.mFrameNumber;
674 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000675}
676
677void Layer::preparePerFrameEffectsCompositionState() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000678 auto* snapshot = editLayerSnapshot();
679 snapshot->color = getColor();
680 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000681 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800682}
683
Lloyd Piquede196652020-01-22 17:29:58 -0800684void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800685 const State& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000686 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800687
688 // Apply the layer's transform, followed by the display's global transform
689 // Here we're guaranteed that the layer's transform preserves rects
690 Rect win = getCroppedBufferSize(drawingState);
691 // Subtract the transparent region and snap to the bounds
692 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
693 Rect frame(getTransform().transform(bounds));
694
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000695 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800696}
697
Lloyd Piquea83776c2019-01-29 18:42:32 -0800698const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700699 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800700}
701
Mathias Agopian13127d82013-03-05 17:47:11 -0800702// ---------------------------------------------------------------------------
703// drawing...
704// ---------------------------------------------------------------------------
705
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500706aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
707 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700708 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800709 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500710 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800711 }
712 if (outputLayer->getState().hwc) {
713 return (*outputLayer->getState().hwc).hwcCompositionType;
714 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500715 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800716 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800717}
718
Mathias Agopian13127d82013-03-05 17:47:11 -0800719// ----------------------------------------------------------------------------
720// local state
721// ----------------------------------------------------------------------------
722
David Sodman41fdfc92017-11-06 16:09:56 -0800723bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800724 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700725 if (s.flags & layer_state_t::eLayerSecure) {
726 return true;
727 }
728
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000729 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700730 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700731}
732
Mathias Agopian13127d82013-03-05 17:47:11 -0800733// ----------------------------------------------------------------------------
734// transaction
735// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800736
Marissa Wall61c58622018-07-18 10:12:20 -0700737uint32_t Layer::doTransaction(uint32_t flags) {
738 ATRACE_CALL();
739
Robert Carr0758e5d2021-03-11 22:15:04 -0800740 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700741 mDrawingStateModified = mDrawingState.modified;
742 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700743
Alec Mourib416efd2018-09-06 21:01:59 +0000744 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700745
Robert Carr6a160312021-05-17 12:08:20 -0700746 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800747 // invalidate and recompute the visible regions if needed
748 flags |= Layer::eVisibleRegion;
749 }
750
Robert Carr6a160312021-05-17 12:08:20 -0700751 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800752 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000753 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800754 flags |= eVisibleRegion;
755 this->contentDirty = true;
756
757 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700758 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800759 }
760
Arthur Hung9ed43392022-05-27 06:31:57 +0000761 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
762 mFlinger->mUpdateInputInfo = true;
763 }
764
Robert Carr6a160312021-05-17 12:08:20 -0700765 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800766
Mathias Agopian13127d82013-03-05 17:47:11 -0800767 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800768}
769
Robert Carr6a160312021-05-17 12:08:20 -0700770void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000771 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
772 // bufferSurfaceFrameTX will be presented in latchBuffer.
773 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
774 if (surfaceFrame->getPresentState() != PresentState::Presented) {
775 // With applyPendingStates, we could end up having presented surfaceframes from previous
776 // states
777 surfaceFrame->setPresentState(PresentState::Presented);
778 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
779 }
780 }
Robert Carr6a160312021-05-17 12:08:20 -0700781 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700782}
783
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700784uint32_t Layer::clearTransactionFlags(uint32_t mask) {
785 const auto flags = mTransactionFlags & mask;
786 mTransactionFlags &= ~mask;
787 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800788}
789
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700790void Layer::setTransactionFlags(uint32_t mask) {
791 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800792}
793
Robert Carr1f0a16a2016-10-24 16:27:39 -0700794bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
795 ssize_t idx = mCurrentChildren.indexOf(childLayer);
796 if (idx < 0) {
797 return false;
798 }
799 if (childLayer->setLayer(z)) {
800 mCurrentChildren.removeAt(idx);
801 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800802 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700803 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800804 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700805}
806
Robert Carr503c7042017-09-27 15:06:08 -0700807bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
808 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
809 ssize_t idx = mCurrentChildren.indexOf(childLayer);
810 if (idx < 0) {
811 return false;
812 }
813 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
814 mCurrentChildren.removeAt(idx);
815 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800816 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700817 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800818 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700819}
820
Robert Carrae060832016-11-28 10:51:00 -0800821bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700822 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
823 mDrawingState.sequence++;
824 mDrawingState.z = z;
825 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700826
Robert Carra70e91c2021-06-11 13:59:52 -0700827 mFlinger->mSomeChildrenChanged = true;
828
Robert Carrdb66e622017-04-10 16:55:57 -0700829 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700830 if (mDrawingState.zOrderRelativeOf != nullptr) {
831 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700832 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700833 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700834 }
chaviw606e5cf2019-03-01 10:12:10 -0800835 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700836 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800837 setTransactionFlags(eTransactionNeeded);
838 return true;
839}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700840
Robert Carrdb66e622017-04-10 16:55:57 -0700841void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700842 mDrawingState.zOrderRelatives.remove(relative);
843 mDrawingState.sequence++;
844 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700845 setTransactionFlags(eTransactionNeeded);
846}
847
848void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700849 mDrawingState.zOrderRelatives.add(relative);
850 mDrawingState.modified = true;
851 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700852 setTransactionFlags(eTransactionNeeded);
853}
854
chaviw606e5cf2019-03-01 10:12:10 -0800855void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700856 mDrawingState.zOrderRelativeOf = relativeOf;
857 mDrawingState.sequence++;
858 mDrawingState.modified = true;
859 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700860
chaviw606e5cf2019-03-01 10:12:10 -0800861 setTransactionFlags(eTransactionNeeded);
862}
863
Robert Carr503d2bd2017-12-04 15:49:47 -0800864bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000865 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700866 if (relative == nullptr) {
867 return false;
868 }
869
Robert Carr6a160312021-05-17 12:08:20 -0700870 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
871 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800872 return false;
873 }
874
Robert Carr88b85e12022-03-21 15:47:35 -0700875 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
876 (relative->mDrawingState.zOrderRelativeOf == this)) {
877 ALOGE("Detected relative layer loop between %s and %s",
878 mName.c_str(), relative->mName.c_str());
879 ALOGE("Ignoring new call to set relative layer");
880 return false;
881 }
882
Robert Carra70e91c2021-06-11 13:59:52 -0700883 mFlinger->mSomeChildrenChanged = true;
884
Robert Carr6a160312021-05-17 12:08:20 -0700885 mDrawingState.sequence++;
886 mDrawingState.modified = true;
887 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700888
Robert Carr6a160312021-05-17 12:08:20 -0700889 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700890 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700891 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700892 }
chaviw606e5cf2019-03-01 10:12:10 -0800893 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700894 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700895
896 setTransactionFlags(eTransactionNeeded);
897
898 return true;
899}
900
Winson Chunga30f7c92021-06-29 15:42:56 -0700901bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
902 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
903 mDrawingState.isTrustedOverlay = isTrustedOverlay;
904 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000905 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700906 setTransactionFlags(eTransactionNeeded);
907 return true;
908}
909
910bool Layer::isTrustedOverlay() const {
911 if (getDrawingState().isTrustedOverlay) {
912 return true;
913 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000914 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700915 return (p != nullptr) && p->isTrustedOverlay();
916}
917
Dan Stoza9e56aa02015-11-02 13:00:03 -0800918bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700919 if (mDrawingState.color.a == alpha) return false;
920 mDrawingState.sequence++;
921 mDrawingState.color.a = alpha;
922 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800923 setTransactionFlags(eTransactionNeeded);
924 return true;
925}
chaviw13fdc492017-06-27 12:40:18 -0700926
Valerie Haudd0b7572019-01-29 14:59:27 -0800927bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700928 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700929 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800930 }
Robert Carr6a160312021-05-17 12:08:20 -0700931 mDrawingState.sequence++;
932 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800933 setTransactionFlags(eTransactionNeeded);
934
Robert Carr6a160312021-05-17 12:08:20 -0700935 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -0800936 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -0800937 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700938 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -0700939 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800940 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700941 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -0700942
Valerie Haudd0b7572019-01-29 14:59:27 -0800943 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -0700944 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -0800945 mFlinger->mLayersAdded = true;
946 // set up SF to handle added color layer
947 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -0700948 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -0800949 }
950 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -0700951 } else if (mDrawingState.bgColorLayer && alpha == 0) {
952 mDrawingState.bgColorLayer->reparent(nullptr);
953 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -0800954 return true;
955 }
956
Robert Carr6a160312021-05-17 12:08:20 -0700957 mDrawingState.bgColorLayer->setColor(color);
958 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
959 mDrawingState.bgColorLayer->setAlpha(alpha);
960 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -0800961
chaviw13fdc492017-06-27 12:40:18 -0700962 return true;
963}
964
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700965bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -0700966 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700967
Robert Carr6a160312021-05-17 12:08:20 -0700968 mDrawingState.sequence++;
969 mDrawingState.cornerRadius = cornerRadius;
970 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700971 setTransactionFlags(eTransactionNeeded);
972 return true;
973}
974
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800975bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -0700976 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -0700977 // If we start or stop drawing blur then the layer's visibility state may change so increment
978 // the magic sequence number.
979 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
980 mDrawingState.sequence++;
981 }
Robert Carr6a160312021-05-17 12:08:20 -0700982 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
983 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800984 setTransactionFlags(eTransactionNeeded);
985 return true;
986}
Marissa Wall61c58622018-07-18 10:12:20 -0700987
Mathias Agopian13127d82013-03-05 17:47:11 -0800988bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +0000989 mDrawingState.sequence++;
990 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -0700991 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800992 setTransactionFlags(eTransactionNeeded);
993 return true;
994}
Ana Krulecc84d09b2019-11-02 23:10:29 +0100995
Lucas Dupinc3800b82020-10-02 16:24:48 -0700996bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -0700997 // If we start or stop drawing blur then the layer's visibility state may change so increment
998 // the magic sequence number.
999 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1000 mDrawingState.sequence++;
1001 }
Robert Carr6a160312021-05-17 12:08:20 -07001002 mDrawingState.blurRegions = blurRegions;
1003 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001004 setTransactionFlags(eTransactionNeeded);
1005 return true;
1006}
1007
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001008bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001009 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1010 if (mDrawingState.flags == newFlags) return false;
1011 mDrawingState.sequence++;
1012 mDrawingState.flags = newFlags;
1013 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001014 setTransactionFlags(eTransactionNeeded);
1015 return true;
1016}
Robert Carr99e27f02016-06-16 15:18:02 -07001017
chaviw25714502021-02-11 10:01:08 -08001018bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001019 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001020 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001021 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001022
Robert Carr6a160312021-05-17 12:08:20 -07001023 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001024 setTransactionFlags(eTransactionNeeded);
1025 return true;
1026}
Robert Carr8d5227b2017-03-16 15:41:03 -07001027
Evan Roskyef876c92019-01-25 17:46:06 -08001028bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001029 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1030 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001031 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001032 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001033}
1034
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001035bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001036 if (mDrawingState.layerStack == layerStack) return false;
1037 mDrawingState.sequence++;
1038 mDrawingState.layerStack = layerStack;
1039 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001040 setTransactionFlags(eTransactionNeeded);
1041 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001042}
1043
Peiyong Linc502cb72019-03-01 15:00:23 -08001044bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001045 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001046 return false;
1047 }
Robert Carr6a160312021-05-17 12:08:20 -07001048 mDrawingState.sequence++;
1049 mDrawingState.colorSpaceAgnostic = agnostic;
1050 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001051 setTransactionFlags(eTransactionNeeded);
1052 return true;
1053}
1054
Sally Qi81d95e62022-03-21 19:41:33 -07001055bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1056 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1057
1058 mDrawingState.sequence++;
1059 mDrawingState.dimmingEnabled = dimmingEnabled;
1060 mDrawingState.modified = true;
1061 setTransactionFlags(eTransactionNeeded);
1062 return true;
1063}
1064
Ana Krulecc84d09b2019-11-02 23:10:29 +01001065bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001066 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1067 mDrawingState.frameRateSelectionPriority = priority;
1068 mDrawingState.sequence++;
1069 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001070 setTransactionFlags(eTransactionNeeded);
1071 return true;
1072}
1073
1074int32_t Layer::getFrameRateSelectionPriority() const {
1075 // Check if layer has priority set.
1076 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1077 return mDrawingState.frameRateSelectionPriority;
1078 }
1079 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001080 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001081 if (parent != nullptr) {
1082 return parent->getFrameRateSelectionPriority();
1083 }
1084
1085 return Layer::PRIORITY_UNSET;
1086}
1087
Andy Labrada096227e2022-06-15 16:58:11 +00001088bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1089 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1090 mDrawingState.defaultFrameRateCompatibility = compatibility;
1091 mDrawingState.modified = true;
1092 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1093 setTransactionFlags(eTransactionNeeded);
1094 return true;
1095}
1096
1097scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1098 return mDrawingState.defaultFrameRateCompatibility;
1099}
1100
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001101bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1102 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1103};
1104
Vishnu Nair73908d12022-10-24 21:46:42 -07001105ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1106 bool useDrawing = state == LayerVector::StateSet::Drawing;
1107 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1108 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001109 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001110 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001111 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001112}
1113
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001114bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001115 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001116 return false;
1117 }
1118
Robert Carr6a160312021-05-17 12:08:20 -07001119 mDrawingState.sequence++;
1120 mDrawingState.shadowRadius = shadowRadius;
1121 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001122 setTransactionFlags(eTransactionNeeded);
1123 return true;
1124}
1125
Vishnu Nair6213bd92020-05-08 17:42:25 -07001126bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001127 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001128 return false;
1129 }
1130
Robert Carr6a160312021-05-17 12:08:20 -07001131 mDrawingState.sequence++;
1132 mDrawingState.fixedTransformHint = fixedTransformHint;
1133 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001134 setTransactionFlags(eTransactionNeeded);
1135 return true;
1136}
1137
John Reckcdb4ed72021-02-04 13:39:33 -05001138bool Layer::setStretchEffect(const StretchEffect& effect) {
1139 StretchEffect temp = effect;
1140 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001141 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001142 return false;
1143 }
Robert Carr6a160312021-05-17 12:08:20 -07001144 mDrawingState.sequence++;
1145 mDrawingState.stretchEffect = temp;
1146 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001147 setTransactionFlags(eTransactionNeeded);
1148 return true;
1149}
1150
John Reckc00c6692021-02-16 11:37:33 -05001151StretchEffect Layer::getStretchEffect() const {
1152 if (mDrawingState.stretchEffect.hasEffect()) {
1153 return mDrawingState.stretchEffect;
1154 }
1155
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001156 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001157 if (parent != nullptr) {
1158 auto effect = parent->getStretchEffect();
1159 if (effect.hasEffect()) {
1160 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1161 return effect;
1162 }
1163 }
1164 return StretchEffect{};
1165}
1166
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001167bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1168 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001169 return false;
1170 }
1171 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001172 mBorderWidth = width;
1173 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001174 return true;
1175}
1176
1177bool Layer::isBorderEnabled() {
1178 return mBorderEnabled;
1179}
1180
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001181float Layer::getBorderWidth() {
1182 return mBorderWidth;
1183}
1184
1185const half4& Layer::getBorderColor() {
1186 return mBorderColor;
1187}
1188
Ady Abrahama850c182021-08-04 13:04:37 -07001189bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1190 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1191 const auto frameRate = [&] {
1192 if (mDrawingState.frameRate.rate.isValid() ||
1193 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1194 return mDrawingState.frameRate;
1195 }
1196
1197 return parentFrameRate;
1198 }();
1199
1200 *transactionNeeded |= setFrameRateForLayerTree(frameRate);
1201
1202 // The frame rate is propagated to the children
1203 bool childrenHaveFrameRate = false;
1204 for (const sp<Layer>& child : mCurrentChildren) {
1205 childrenHaveFrameRate |=
1206 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1207 }
1208
1209 // If we don't have a valid frame rate, but the children do, we set this
1210 // layer as NoVote to allow the children to control the refresh rate
1211 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1212 childrenHaveFrameRate) {
1213 *transactionNeeded |=
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001214 setFrameRateForLayerTree(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001215 }
1216
1217 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1218 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001219 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001220 const auto layerVotedWithDefaultCompatibility =
1221 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1222 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1223 const auto layerVotedWithExactCompatibility =
1224 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1225 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1226 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1227}
1228
Ady Abraham60e42ea2020-03-09 19:17:31 -07001229void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001230 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001231 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001232 while (auto parent = layer->getParent()) {
1233 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001234 }
Ady Abrahama850c182021-08-04 13:04:37 -07001235 return layer;
1236 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001237
Ady Abraham60e42ea2020-03-09 19:17:31 -07001238 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001239 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001240
Ady Abrahama850c182021-08-04 13:04:37 -07001241 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001242 if (transactionNeeded) {
1243 mFlinger->setTransactionFlags(eTraversalNeeded);
1244 }
1245}
1246
Ady Abraham71c437d2020-01-31 15:56:57 -08001247bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001248 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001249 return false;
1250 }
1251
Robert Carr6a160312021-05-17 12:08:20 -07001252 mDrawingState.sequence++;
1253 mDrawingState.frameRate = frameRate;
1254 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001255
1256 updateTreeHasFrameRateVote();
1257
Steven Thomas3172e202020-01-06 19:25:30 -08001258 setTransactionFlags(eTransactionNeeded);
1259 return true;
1260}
1261
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001262void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1263 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001264 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001265
1266 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1267 // there are two transactions with the same token, the first one without a buffer and the
1268 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1269 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001270 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1271 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001272 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001273 mDrawingState.bufferSurfaceFrameTX = it->second;
1274 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1275 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1276 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001277 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001278 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001279 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1280 }
1281}
1282
1283void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1284 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001285 mDrawingState.frameTimelineInfo = info;
1286 mDrawingState.postTime = postTime;
1287 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001288 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001289
Robert Carr6a160312021-05-17 12:08:20 -07001290 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001291 bufferSurfaceFrameTX != nullptr) {
1292 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1293 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1294 // being used for BufferSurfaceFrame, don't create a new one.
1295 return;
1296 }
1297 }
1298 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1299 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1300 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001301 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1302 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001303 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001304 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001305 } else {
1306 if (it->second->getPresentState() == PresentState::Presented) {
1307 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1308 // have been from previous vsync.
1309 it->second = createSurfaceFrameForTransaction(info, postTime);
1310 }
1311 }
1312}
1313
1314void Layer::addSurfaceFrameDroppedForBuffer(
1315 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001316 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001317 surfaceFrame->setPresentState(PresentState::Dropped);
1318 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1319}
1320
1321void Layer::addSurfaceFramePresentedForBuffer(
1322 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1323 nsecs_t currentLatchTime) {
1324 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1325 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1326 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1327 mLastLatchTime = currentLatchTime;
1328}
1329
1330std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1331 const FrameTimelineInfo& info, nsecs_t postTime) {
1332 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001333 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1334 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001335 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001336 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001337 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001338 // For Transactions, the post time is considered to be both queue and acquire fence time.
1339 surfaceFrame->setActualQueueTime(postTime);
1340 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001341 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1342 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001343 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001344 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001345 onSurfaceFrameCreated(surfaceFrame);
1346 return surfaceFrame;
1347}
1348
1349std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1350 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1351 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001352 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001353 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001354 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001355 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001356 // For buffers, acquire fence time will set during latch.
1357 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001358 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1359 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001360 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001361 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001362 onSurfaceFrameCreated(surfaceFrame);
1363 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001364}
1365
Ady Abrahama850c182021-08-04 13:04:37 -07001366bool Layer::setFrameRateForLayerTree(FrameRate frameRate) {
1367 if (mDrawingState.frameRateForLayerTree == frameRate) {
1368 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001369 }
1370
Ady Abrahama850c182021-08-04 13:04:37 -07001371 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001372
Ady Abrahama850c182021-08-04 13:04:37 -07001373 // TODO(b/195668952): we probably don't need to dirty visible regions here
1374 // or even store frameRateForLayerTree in mDrawingState
1375 mDrawingState.sequence++;
1376 mDrawingState.modified = true;
1377 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001378
Dominik Laskowski068173d2021-08-11 17:22:59 -07001379 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
1380 mFlinger->mScheduler->recordLayerHistory(this, systemTime(), LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001381
1382 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001383}
1384
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001385Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1386 return getDrawingState().frameRateForLayerTree;
1387}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001388
Robert Carr1f0a16a2016-10-24 16:27:39 -07001389bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001390 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001391 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001392 if (parent != nullptr && parent->isHiddenByPolicy()) {
1393 return true;
1394 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001395 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1396 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1397 if (zOrderRelativeOf != nullptr) {
1398 if (zOrderRelativeOf->isHiddenByPolicy()) {
1399 return true;
1400 }
1401 }
1402 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001403 if (CC_UNLIKELY(!isTransformValid())) {
1404 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1405 return true;
1406 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001407 return s.flags & layer_state_t::eLayerHidden;
1408}
1409
David Sodman41fdfc92017-11-06 16:09:56 -08001410uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001411 // TODO: should we do something special if mSecure is set?
1412 if (mProtectedByApp) {
1413 // need a hardware-protected path to external video sink
1414 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001415 }
Riley Andrews03414a12014-07-01 14:22:59 -07001416 if (mPotentialCursor) {
1417 usage |= GraphicBuffer::USAGE_CURSOR;
1418 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001419 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001420 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001421}
1422
Vishnu Nair71fcf912022-10-18 09:14:20 -07001423void Layer::skipReportingTransformHint() {
1424 mSkipReportingTransformHint = true;
1425}
1426
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001427void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1428 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1429 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001430 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001431
Vishnu Nair6213bd92020-05-08 17:42:25 -07001432 setTransformHint(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001433}
1434
Mathias Agopian13127d82013-03-05 17:47:11 -08001435// ----------------------------------------------------------------------------
1436// debugging
1437// ----------------------------------------------------------------------------
1438
Marissa Wall61c58622018-07-18 10:12:20 -07001439// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001440gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001441 using namespace std::string_literals;
1442
Huihong Luo05539a12022-02-23 10:29:40 -08001443 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001444 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001445 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001446 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001447 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001448 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001449
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001450 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001451 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001452 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001453 info.mX = ds.transform.tx();
1454 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001455 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001456 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001457 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001458 info.mFlags = ds.flags;
1459 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001460 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001461 info.mMatrix[0][0] = ds.transform[0][0];
1462 info.mMatrix[0][1] = ds.transform[0][1];
1463 info.mMatrix[1][0] = ds.transform[1][0];
1464 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001465 {
chaviwd62d3062019-09-04 14:48:02 -07001466 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001467 if (buffer != 0) {
1468 info.mActiveBufferWidth = buffer->getWidth();
1469 info.mActiveBufferHeight = buffer->getHeight();
1470 info.mActiveBufferStride = buffer->getStride();
1471 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001472 } else {
1473 info.mActiveBufferWidth = 0;
1474 info.mActiveBufferHeight = 0;
1475 info.mActiveBufferStride = 0;
1476 info.mActiveBufferFormat = 0;
1477 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001478 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001479 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001480 info.mIsOpaque = isOpaque(ds);
1481 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001482 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001483 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001484}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001485
Yiwei Zhang5434a782018-12-05 18:06:32 -08001486void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001487 result.append(kDumpTableRowLength, '-');
1488 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001489 result.append(" Layer name\n");
1490 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001491 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001492 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001493 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001494 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001495 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001496 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1497 result.append(kDumpTableRowLength, '-');
1498 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001499}
1500
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001501void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1502 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001503 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001504 return;
1505 }
1506
Yiwei Zhang5434a782018-12-05 18:06:32 -08001507 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001508 if (mName.length() > 77) {
1509 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001510 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001511 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001512 shortened.append(mName, mName.length() - 36);
1513 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001514 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001515 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001516 }
1517
Yiwei Zhang5434a782018-12-05 18:06:32 -08001518 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001519
Alec Mourib416efd2018-09-06 21:01:59 +00001520 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001521 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001522
Chia-I Wu1e043612018-03-01 09:45:09 -08001523 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001524 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001525 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001526 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001527 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001528 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001529 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001530 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1531 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001532 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001533 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001534 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001535 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001536 const auto frameRate = getFrameRateForLayerTree();
1537 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1538 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001539 ftl::enum_string(frameRate.type).c_str(),
1540 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001541 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001542 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001543 }
Dan Stozae22aec72016-08-01 13:20:59 -07001544
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001545 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1546 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1547
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001548 result.append(kDumpTableRowLength, '-');
1549 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001550}
Dan Stozae22aec72016-08-01 13:20:59 -07001551
Yiwei Zhang5434a782018-12-05 18:06:32 -08001552void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001553 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001554}
1555
Svetoslavd85084b2014-03-20 10:28:31 -07001556void Layer::clearFrameStats() {
1557 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001558}
1559
Jamie Gennis6547ff42013-07-16 20:12:42 -07001560void Layer::logFrameStats() {
1561 mFrameTracker.logAndResetStats(mName);
1562}
1563
Svetoslavd85084b2014-03-20 10:28:31 -07001564void Layer::getFrameStats(FrameStats* outStats) const {
1565 mFrameTracker.getStats(outStats);
1566}
1567
Vishnu Nair76554eb2022-12-09 03:38:36 +00001568void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1569 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
1570 StringAppendF(&result, "Layer %s%s pid:%d uid:%d\n", getName().c_str(), hasBuffer.c_str(),
Vishnu Naircb8be502022-10-12 19:03:23 +00001571 mOwnerPid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001572}
1573
Brian Anderson5ea5e592016-12-01 16:54:33 -08001574void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001575 const int32_t layerId = getSequence();
1576 mFlinger->mTimeStats->onDestroy(layerId);
1577 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001578}
1579
Chia-I Wu98f1c102017-05-30 14:54:08 -07001580size_t Layer::getChildrenCount() const {
1581 size_t count = 0;
1582 for (const sp<Layer>& child : mCurrentChildren) {
1583 count += 1 + child->getChildrenCount();
1584 }
1585 return count;
1586}
1587
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001588void Layer::setGameModeForTree(GameMode gameMode) {
1589 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001590 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1591 gameMode =
1592 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001593 }
1594 setGameMode(gameMode);
1595 for (const sp<Layer>& child : mCurrentChildren) {
1596 child->setGameModeForTree(gameMode);
1597 }
1598}
1599
Robert Carr1f0a16a2016-10-24 16:27:39 -07001600void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001601 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001602 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001603
Robert Carr1f0a16a2016-10-24 16:27:39 -07001604 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001605 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001606 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001607 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001608}
1609
1610ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001611 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001612 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001613
Robert Carr1323c952019-01-28 18:13:27 -08001614 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001615 const auto removeResult = mCurrentChildren.remove(layer);
1616
1617 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001618 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001619 layer->updateTreeHasFrameRateVote();
1620
1621 return removeResult;
1622}
1623
Robert Carr15eae092018-03-23 13:43:53 -07001624void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001625 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001626 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001627 const float parentShadowRadius =
1628 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001629 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001630 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001631 }
1632}
1633
chaviwf1961f72017-09-18 16:41:07 -07001634bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001635 sp<Layer> newParent;
1636 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001637 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001638 if (newParent == nullptr) {
1639 ALOGE("Unable to promote Layer handle");
1640 return false;
1641 }
1642 if (newParent == this) {
1643 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1644 return false;
1645 }
1646 }
1647
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001648 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001649 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001650 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001651 }
1652
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001653 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001654 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001655 if (!newParent->isRemovedFromCurrentState()) {
1656 addToCurrentState();
1657 } else {
1658 onRemovedFromCurrentState();
1659 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001660 } else {
1661 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001662 }
1663
chaviw06178942017-07-27 10:25:59 -07001664 return true;
1665}
1666
Peiyong Lind3788632018-09-18 16:01:31 -07001667bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001668 static const mat4 identityMatrix = mat4();
1669
Robert Carr6a160312021-05-17 12:08:20 -07001670 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001671 return false;
1672 }
Robert Carr6a160312021-05-17 12:08:20 -07001673 ++mDrawingState.sequence;
1674 mDrawingState.colorTransform = matrix;
1675 mDrawingState.hasColorTransform = matrix != identityMatrix;
1676 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001677 setTransactionFlags(eTransactionNeeded);
1678 return true;
1679}
1680
chaviwf66724d2018-11-28 16:35:21 -08001681mat4 Layer::getColorTransform() const {
1682 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001683 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001684 colorTransform = parent->getColorTransform() * colorTransform;
1685 }
1686 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001687}
1688
1689bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001690 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001691 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001692 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1693 }
1694 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001695}
1696
Chia-I Wu11481472018-05-04 10:43:19 -07001697bool Layer::isLegacyDataSpace() const {
1698 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001699 return !(getDataSpace() &
1700 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1701 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001702}
1703
Robert Carr1f0a16a2016-10-24 16:27:39 -07001704void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001705 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001706}
1707
Robert Carr6a160312021-05-17 12:08:20 -07001708int32_t Layer::getZ(LayerVector::StateSet) const {
1709 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001710}
1711
Robert Carr1c5481e2019-07-01 14:42:27 -07001712bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001713 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001714 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001715 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001716}
1717
David Sodman41fdfc92017-11-06 16:09:56 -08001718__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001719 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001720 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1721 "makeTraversalList received invalid stateSet");
1722 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1723 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001724 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001725
Robert Carr29abff82017-12-04 13:51:20 -08001726 if (state.zOrderRelatives.size() == 0) {
1727 *outSkipRelativeZUsers = true;
1728 return children;
1729 }
1730
chaviwfd462612018-05-31 16:11:27 -07001731 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001732 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001733 sp<Layer> strongRelative = weakRelative.promote();
1734 if (strongRelative != nullptr) {
1735 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001736 }
1737 }
1738
Dan Stoza412903f2017-04-27 13:42:17 -07001739 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001740 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001741 continue;
1742 }
Robert Carrdb66e622017-04-10 16:55:57 -07001743 traverse.add(child);
1744 }
1745
1746 return traverse;
1747}
1748
Robert Carr1f0a16a2016-10-24 16:27:39 -07001749/**
Robert Carrdb66e622017-04-10 16:55:57 -07001750 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001751 */
Dan Stoza412903f2017-04-27 13:42:17 -07001752void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001753 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1754 // produce a new list for traversing, including our relatives, and not including our children
1755 // who are relatives of another surface. In the case that there are no relative Z,
1756 // makeTraversalList returns our children directly to avoid significant overhead.
1757 // However in this case we need to take the responsibility for filtering children which
1758 // are relatives of another surface here.
1759 bool skipRelativeZUsers = false;
1760 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001761
Robert Carr1f0a16a2016-10-24 16:27:39 -07001762 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001763 for (; i < list.size(); i++) {
1764 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001765 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1766 continue;
1767 }
1768
chaviw301b1d82019-11-06 13:15:09 -08001769 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001770 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001771 }
Dan Stoza412903f2017-04-27 13:42:17 -07001772 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001773 }
Robert Carr29abff82017-12-04 13:51:20 -08001774
Dan Stoza412903f2017-04-27 13:42:17 -07001775 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001776 for (; i < list.size(); i++) {
1777 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001778
Robert Carr29abff82017-12-04 13:51:20 -08001779 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1780 continue;
1781 }
Dan Stoza412903f2017-04-27 13:42:17 -07001782 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001783 }
1784}
1785
1786/**
Robert Carrdb66e622017-04-10 16:55:57 -07001787 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001788 */
Dan Stoza412903f2017-04-27 13:42:17 -07001789void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1790 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001791 // See traverseInZOrder for documentation.
1792 bool skipRelativeZUsers = false;
1793 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001794
Robert Carr1f0a16a2016-10-24 16:27:39 -07001795 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001796 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001797 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001798
1799 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1800 continue;
1801 }
1802
chaviw301b1d82019-11-06 13:15:09 -08001803 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001804 break;
1805 }
Dan Stoza412903f2017-04-27 13:42:17 -07001806 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001807 }
Dan Stoza412903f2017-04-27 13:42:17 -07001808 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001809 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001810 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001811
1812 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1813 continue;
1814 }
1815
Dan Stoza412903f2017-04-27 13:42:17 -07001816 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001817 }
1818}
1819
Edgar Arriaga844fa672020-01-16 14:21:42 -08001820void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1821 visitor(this);
1822 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001823 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001824 for (const sp<Layer>& child : children) {
1825 child->traverse(state, visitor);
1826 }
1827}
1828
chaviw4b129c22018-04-09 16:19:43 -07001829LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1830 const std::vector<Layer*>& layersInTree) {
1831 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1832 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001833 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1834 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001835 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001836
chaviwfd462612018-05-31 16:11:27 -07001837 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001838 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1839 sp<Layer> strongRelative = weakRelative.promote();
1840 // Only add relative layers that are also descendents of the top most parent of the tree.
1841 // If a relative layer is not a descendent, then it should be ignored.
1842 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1843 traverse.add(strongRelative);
1844 }
1845 }
1846
1847 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001848 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001849 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1850 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1851 // the child here since it won't be added later as a relative.
1852 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1853 childState.zOrderRelativeOf.promote().get())) {
1854 continue;
1855 }
1856 traverse.add(child);
1857 }
1858
1859 return traverse;
1860}
1861
1862void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1863 LayerVector::StateSet stateSet,
1864 const LayerVector::Visitor& visitor) {
1865 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001866
1867 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001868 for (; i < list.size(); i++) {
1869 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001870 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001871 break;
1872 }
chaviw4b129c22018-04-09 16:19:43 -07001873 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001874 }
chaviw4b129c22018-04-09 16:19:43 -07001875
chaviwa76b2712017-09-20 12:02:26 -07001876 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001877 for (; i < list.size(); i++) {
1878 const auto& relative = list[i];
1879 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001880 }
1881}
1882
chaviw4b129c22018-04-09 16:19:43 -07001883std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1884 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1885 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1886
1887 std::vector<Layer*> layersInTree = {this};
1888 for (size_t i = 0; i < children.size(); i++) {
1889 const auto& child = children[i];
1890 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1891 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1892 }
1893
1894 return layersInTree;
1895}
1896
1897void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1898 const LayerVector::Visitor& visitor) {
1899 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1900 std::sort(layersInTree.begin(), layersInTree.end());
1901 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1902}
1903
Peiyong Linefefaac2018-08-17 12:27:51 -07001904ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001905 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001906}
1907
Garfield Tan2c1782c2022-02-16 15:25:05 -08001908bool Layer::isTransformValid() const {
1909 float transformDet = getTransform().det();
1910 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1911}
1912
chaviw13fdc492017-06-27 12:40:18 -07001913half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001914 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001915
chaviw13fdc492017-06-27 12:40:18 -07001916 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1917 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07001918}
Robert Carr6452f122017-03-21 10:41:29 -07001919
Vishnu Nair6213bd92020-05-08 17:42:25 -07001920ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07001921 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001922 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
1923 return fixedTransformHint;
1924 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001925 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07001926 if (!p) return fixedTransformHint;
1927 return p->getFixedTransformHint();
1928}
1929
chaviw13fdc492017-06-27 12:40:18 -07001930half4 Layer::getColor() const {
1931 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001932 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07001933}
Robert Carr6452f122017-03-21 10:41:29 -07001934
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001935int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00001936 if (getDrawingState().backgroundBlurRadius == 0) {
1937 return 0;
1938 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01001939
Vishnu Nair29810f72022-07-01 16:38:41 +00001940 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01001941 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1942 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001943}
1944
Galia Peychevae0acf382021-04-12 21:22:34 +02001945const std::vector<BlurRegion> Layer::getBlurRegions() const {
1946 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02001947 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02001948 for (auto& region : regionsCopy) {
1949 region.alpha = region.alpha * layerAlpha;
1950 }
1951 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001952}
1953
Vishnu Naire14c6b32022-08-06 04:20:15 +00001954RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001955 // Get parent settings
1956 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001957 const auto& parent = mDrawingParent.promote();
1958 if (parent != nullptr) {
1959 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001960 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001961 ui::Transform t = getActiveTransform(getDrawingState());
1962 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001963 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001964 parentSettings.radius.x *= t.getScaleX();
1965 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001966 }
1967 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001968
1969 // Get layer settings
1970 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001971 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001972 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001973 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001974
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001975 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001976 // If the parent and the layer have rounded corner settings, use the parent settings if the
1977 // parent crop is entirely inside the layer crop.
1978 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
1979 if (parentSettings.cropRect.left > layerCropRect.left &&
1980 parentSettings.cropRect.top > layerCropRect.top &&
1981 parentSettings.cropRect.right < layerCropRect.right &&
1982 parentSettings.cropRect.bottom < layerCropRect.bottom) {
1983 return parentSettings;
1984 } else {
1985 return layerSettings;
1986 }
Vishnu Nairb1845592021-10-07 12:17:57 -07001987 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001988 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001989 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001990 return parentSettings;
1991 }
1992 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001993}
1994
Robert Carr88b85e12022-03-21 15:47:35 -07001995bool Layer::findInHierarchy(const sp<Layer>& l) {
1996 if (l == this) {
1997 return true;
1998 }
1999 for (auto& child : mDrawingChildren) {
2000 if (child->findInHierarchy(l)) {
2001 return true;
2002 }
2003 }
2004 return false;
2005}
2006
Robert Carr1f0a16a2016-10-24 16:27:39 -07002007void Layer::commitChildList() {
2008 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2009 const auto& child = mCurrentChildren[i];
2010 child->commitChildList();
2011 }
2012 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002013 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002014 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2015 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2016 if (zOrderRelativeOf == nullptr) return;
2017 if (findInHierarchy(zOrderRelativeOf)) {
2018 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2019 zOrderRelativeOf->mName.c_str());
2020 ALOGE("Severing rel Z loop, potentially dangerous");
2021 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002022 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002023 }
2024 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002025}
2026
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002027
chaviw3277faf2021-05-19 16:45:23 -05002028void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002029 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002030 mDrawingState.touchableRegionCrop =
2031 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002032 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002033 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002034 setTransactionFlags(eTransactionNeeded);
2035}
2036
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002037LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002038 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002039 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002040 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2041
Vishnu Nair00b90132021-11-05 14:03:40 -07002042 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002043 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2044
Vishnu Nair60db8c02020-04-02 11:55:16 -07002045 // Only populate for the primary display.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002046 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -05002047 const auto compositionType = getCompositionType(*display);
Vishnu Nair60db8c02020-04-02 11:55:16 -07002048 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002049 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2050 [&]() { return layerProto->mutable_visible_region(); });
Vishnu Nair60db8c02020-04-02 11:55:16 -07002051 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08002052 }
2053
chaviw08f3cb22020-01-13 13:17:21 -08002054 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002055 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002056 }
chaviw6d89e2d2020-01-14 14:42:01 -08002057
2058 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002059}
2060
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002061void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002062 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002063 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002064 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002065 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002066 [&]() { return layerInfo->mutable_active_buffer(); });
2067 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2068 layerInfo->mutable_buffer_transform());
2069 }
2070 layerInfo->set_invalidate(contentDirty);
2071 layerInfo->set_is_protected(isProtected());
2072 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2073 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002074 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002075 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002076 layerInfo->set_corner_radius(
2077 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002078 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2079 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2080 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2081 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2082 [&]() { return layerInfo->mutable_position(); });
2083 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002084 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2085 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002086
Vishnu Nair00b90132021-11-05 14:03:40 -07002087 if (hasColorTransform()) {
2088 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002089 }
2090
Vishnu Nair60db8c02020-04-02 11:55:16 -07002091 LayerProtoHelper::writeToProto(mSourceBounds,
2092 [&]() { return layerInfo->mutable_source_bounds(); });
2093 LayerProtoHelper::writeToProto(mScreenBounds,
2094 [&]() { return layerInfo->mutable_screen_bounds(); });
2095 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2096 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2097 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002098}
2099
2100void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002101 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002102 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2103 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002104 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002105
chaviw766c9c52021-02-10 17:36:47 -08002106 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002107
Vishnu Nair00b90132021-11-05 14:03:40 -07002108 layerInfo->set_id(sequence);
2109 layerInfo->set_name(getName().c_str());
2110 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002111
Vishnu Nair00b90132021-11-05 14:03:40 -07002112 for (const auto& child : children) {
2113 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002114 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002115
Vishnu Nair00b90132021-11-05 14:03:40 -07002116 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2117 sp<Layer> strongRelative = weakRelative.promote();
2118 if (strongRelative != nullptr) {
2119 layerInfo->add_relatives(strongRelative->sequence);
2120 }
2121 }
2122
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002123 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002124 [&]() { return layerInfo->mutable_transparent_region(); });
2125
2126 layerInfo->set_layer_stack(getLayerStack().id);
2127 layerInfo->set_z(state.z);
2128
2129 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2130 return layerInfo->mutable_requested_position();
2131 });
2132
Vishnu Nair00b90132021-11-05 14:03:40 -07002133 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2134
2135 layerInfo->set_is_opaque(isOpaque(state));
2136
2137 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2138 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2139 LayerProtoHelper::writeToProto(state.color,
2140 [&]() { return layerInfo->mutable_requested_color(); });
2141 layerInfo->set_flags(state.flags);
2142
2143 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2144 layerInfo->mutable_requested_transform());
2145
2146 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2147 if (parent != nullptr) {
2148 layerInfo->set_parent(parent->sequence);
2149 } else {
2150 layerInfo->set_parent(-1);
2151 }
2152
2153 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2154 if (zOrderRelativeOf != nullptr) {
2155 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2156 } else {
2157 layerInfo->set_z_order_relative_of(-1);
2158 }
2159
2160 layerInfo->set_is_relative_of(state.isRelativeOf);
2161
2162 layerInfo->set_owner_uid(mOwnerUid);
2163
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002164 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002165 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002166 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002167 info = fillInputInfo(
2168 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002169 } else {
2170 info = state.inputInfo;
2171 }
2172
2173 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002174 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002175 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002176
Vishnu Nair00b90132021-11-05 14:03:40 -07002177 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002178 auto protoMap = layerInfo->mutable_metadata();
2179 for (const auto& entry : state.metadata.mMap) {
2180 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2181 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002182 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002183
2184 LayerProtoHelper::writeToProto(state.destinationFrame,
2185 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002186}
2187
Robert Carr2e102c92018-10-23 12:11:15 -07002188bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002189 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002190}
2191
Prabir Pradhan33da9462022-06-14 14:55:57 +00002192// Applies the given transform to the region, while protecting against overflows caused by any
2193// offsets. If applying the offset in the transform to any of the Rects in the region would result
2194// in an overflow, they are not added to the output Region.
2195static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2196 const std::string& debugWindowName) {
2197 // Round the translation using the same rounding strategy used by ui::Transform.
2198 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2199 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2200
2201 ui::Transform transformWithoutOffset = t;
2202 transformWithoutOffset.set(0.f, 0.f);
2203
2204 const Region transformed = transformWithoutOffset.transform(r);
2205
2206 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2207 Region ret;
2208 for (const auto& rect : transformed) {
2209 Rect newRect;
2210 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2211 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2212 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2213 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2214 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2215 debugWindowName.c_str());
2216 continue;
2217 }
2218 ret.orSelf(newRect);
2219 }
2220 return ret;
2221}
2222
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002223void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
2224 Rect tmpBounds = getInputBounds();
2225 if (!tmpBounds.isValid()) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002226 info.touchableRegion.clear();
2227 // A layer could have invalid input bounds and still expect to receive touch input if it has
2228 // replaceTouchableRegionWithCrop. For that case, the input transform needs to be calculated
2229 // correctly to determine the coordinate space for input events. Use an empty rect so that
2230 // the layer will receive input in its own layer space.
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002231 tmpBounds = Rect::EMPTY_RECT;
chaviw7e72caf2020-12-02 16:50:43 -08002232 }
2233
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002234 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2235 // frame and transform used for the layer, which determines the bounds and the coordinate space
2236 // within which the layer will receive input.
2237 //
2238 // The coordinate space within which each of the bounds are specified is explicitly documented
2239 // in the variable name. For example "inputBoundsInLayer" is specified in layer space. A
2240 // Transform converts one coordinate space to another, which is apparent in its naming. For
2241 // example, "layerToDisplay" transforms layer space to display space.
2242 //
2243 // Coordinate space definitions:
2244 // - display: The display device's coordinate space. Correlates to pixels on the display.
2245 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2246 // - layer: The coordinate space of this layer.
2247 // - input: The coordinate space in which this layer will receive input events. This could be
2248 // different than layer space if a surfaceInset is used, which changes the origin
2249 // of the input space.
2250 const FloatRect inputBoundsInLayer = tmpBounds.toFloatRect();
chaviw7e72caf2020-12-02 16:50:43 -08002251
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002252 // Clamp surface inset to the input bounds.
2253 const auto surfaceInset = static_cast<float>(info.surfaceInset);
2254 const float xSurfaceInset =
2255 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getWidth() / 2.f));
2256 const float ySurfaceInset =
2257 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getHeight() / 2.f));
chaviw1ff3d1e2020-07-01 15:53:47 -07002258
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002259 // Apply the insets to the input bounds.
2260 const FloatRect insetBoundsInLayer(inputBoundsInLayer.left + xSurfaceInset,
2261 inputBoundsInLayer.top + ySurfaceInset,
2262 inputBoundsInLayer.right - xSurfaceInset,
2263 inputBoundsInLayer.bottom - ySurfaceInset);
Ady Abraham282f1d72019-07-24 18:05:56 -07002264
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002265 // Crop the input bounds to ensure it is within the parent's bounds.
2266 const FloatRect croppedInsetBoundsInLayer = mBounds.intersect(insetBoundsInLayer);
Ady Abraham282f1d72019-07-24 18:05:56 -07002267
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002268 const ui::Transform layerToScreen = getInputTransform();
2269 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
Vishnu Nair8033a492018-12-05 07:27:23 -08002270
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002271 const Rect roundedFrameInDisplay{layerToDisplay.transform(croppedInsetBoundsInLayer)};
2272 info.frameLeft = roundedFrameInDisplay.left;
2273 info.frameTop = roundedFrameInDisplay.top;
2274 info.frameRight = roundedFrameInDisplay.right;
2275 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002276
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002277 ui::Transform inputToLayer;
2278 inputToLayer.set(insetBoundsInLayer.left, insetBoundsInLayer.top);
2279 const ui::Transform inputToDisplay = layerToDisplay * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002280
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002281 // InputDispatcher expects a display-to-input transform.
2282 info.transform = inputToDisplay.inverse();
2283
2284 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002285 info.touchableRegion =
2286 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002287}
2288
chaviw3277faf2021-05-19 16:45:23 -05002289void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002290 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002291 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002292 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002293 }
2294 if (p != nullptr) {
2295 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2296 }
2297}
2298
Vishnu Naira066d902021-09-13 18:40:17 -07002299gui::DropInputMode Layer::getDropInputMode() const {
2300 gui::DropInputMode mode = mDrawingState.dropInputMode;
2301 if (mode == gui::DropInputMode::ALL) {
2302 return mode;
2303 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002304 sp<Layer> parent = mDrawingParent.promote();
2305 if (parent) {
2306 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002307 if (parentMode != gui::DropInputMode::NONE) {
2308 return parentMode;
2309 }
2310 }
2311 return mode;
2312}
2313
2314void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002315 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002316 return;
2317 }
2318
2319 // Check if we need to drop input unconditionally
2320 gui::DropInputMode dropInputMode = getDropInputMode();
2321 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002322 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002323 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2324 return;
2325 }
2326
2327 // Check if we need to check if the window is obscured by parent
2328 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2329 return;
2330 }
2331
2332 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002333 sp<Layer> parent = mDrawingParent.promote();
2334 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002335 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002336 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2337 static_cast<float>(getAlpha()));
2338 }
2339
2340 // Check if the parent has cropped the buffer
2341 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2342 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002343 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002344 return;
2345 }
2346
2347 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2348 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2349 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2350 // match then the layer has not been cropped by its parents.
2351 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2352 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2353
2354 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002355 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002356 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2357 getDebugName());
2358 } else {
2359 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2360 // input if the window is obscured. This check should be done in surfaceflinger but the
2361 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2362 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002363 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002364 }
2365}
2366
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002367WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002368 if (!hasInputInfo()) {
2369 mDrawingState.inputInfo.name = getName();
2370 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2371 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002372 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002373 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002374 }
2375
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002376 const ui::Transform& displayTransform =
2377 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2378
chaviw3277faf2021-05-19 16:45:23 -05002379 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002380 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002381 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002382
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002383 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002384
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002385 if (displayArgs.transform == nullptr) {
2386 // Do not let the window receive touches if it is not associated with a valid display
2387 // transform. We still allow the window to receive keys and prevent ANRs.
2388 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2389 }
2390
Robert Carr5dc426e2020-06-10 14:29:14 -07002391 // For compatibility reasons we let layers which can receive input
2392 // receive input before they have actually submitted a buffer. Because
2393 // of this we use canReceiveInput instead of isVisible to check the
2394 // policy-visibility, ignoring the buffer state. However for layers with
2395 // hasInputInfo()==false we can use the real visibility state.
2396 // We are just using these layers for occlusion detection in
2397 // InputDispatcher, and obviously if they aren't visible they can't occlude
2398 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002399 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2400 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2401
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002402 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002403 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002404 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002405
Vishnu Nair16a938f2021-09-24 07:14:54 -07002406 // If the window will be blacked out on a display because the display does not have the secure
2407 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002408 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002409 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002410 }
2411
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002412 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2413 if (info.replaceTouchableRegionWithCrop) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002414 const Rect bounds(cropLayer ? cropLayer->mScreenBounds : mScreenBounds);
2415 info.touchableRegion = Region(displayTransform.transform(bounds));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002416 } else if (cropLayer != nullptr) {
[1;3C2b9fc252021-02-04 16:16:50 -08002417 info.touchableRegion = info.touchableRegion.intersect(
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002418 displayTransform.transform(Rect{cropLayer->mScreenBounds}));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002419 }
2420
Winson Chunga30f7c92021-06-29 15:42:56 -07002421 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2422 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002423 if (isTrustedOverlay()) {
2424 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2425 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002426
chaviwaf87b3e2019-10-01 16:59:28 -07002427 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2428 // touches from going outside the cloned area.
2429 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002430 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002431 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2432 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002433 info.touchableRegion = info.touchableRegion.intersect(rect);
2434 }
2435 }
2436
Robert Carr720e5062018-07-30 17:45:14 -07002437 return info;
2438}
2439
chaviwaf87b3e2019-10-01 16:59:28 -07002440sp<Layer> Layer::getClonedRoot() {
2441 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002442 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002443 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002444 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002445 return nullptr;
2446 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002447 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002448}
2449
Robert Carredd13602020-04-13 17:24:34 -07002450bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002451 return mDrawingState.inputInfo.token != nullptr ||
2452 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002453}
2454
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002455compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002456 const DisplayDevice* display) const {
2457 if (!display) return nullptr;
Lloyd Piquede196652020-01-22 17:29:58 -08002458 return display->getCompositionDisplay()->getOutputLayerForLayer(getCompositionEngineLayerFE());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002459}
2460
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002461Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2462 const auto outputLayer = findOutputLayerForDisplay(display);
2463 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002464}
2465
chaviwb4c6e582019-08-16 14:35:07 -07002466void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002467 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002468 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002469 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2470 mPotentialCursor = clonedFrom->mPotentialCursor;
2471 mProtectedByApp = clonedFrom->mProtectedByApp;
2472 updateCloneBufferInfo();
2473}
2474
2475void Layer::updateCloneBufferInfo() {
2476 if (!isClone() || !isClonedFromAlive()) {
2477 return;
2478 }
2479
2480 sp<Layer> clonedFrom = getClonedFrom();
2481 mBufferInfo = clonedFrom->mBufferInfo;
2482 mSidebandStream = clonedFrom->mSidebandStream;
2483 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2484 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2485 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2486
2487 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2488 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2489 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2490 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2491 // the cloned drawingState again.
2492 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2493 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2494 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2495 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2496
2497 cloneDrawingState(clonedFrom.get());
2498
2499 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2500 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2501 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2502 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002503}
chaviw74b03172019-08-19 11:09:03 -07002504
2505void Layer::updateMirrorInfo() {
2506 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2507 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2508 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2509 // that case, we want to delete the reference to the clone since we want it to get
2510 // destroyed. The root, this layer, will still be around since the client can continue
2511 // to hold a reference, but no cloned layers will be displayed.
2512 mClonedChild = nullptr;
2513 return;
2514 }
2515
2516 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2517 // If the real layer exists and is in current state, add the clone as a child of the root.
2518 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2519 // copied to drawingState for the root layer. So the clonedChild is always removed from
2520 // drawingState and then needs to be added back each traversal.
2521 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2522 addChildToDrawing(mClonedChild);
2523 }
2524
2525 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002526 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002527 mClonedChild->updateClonedRelatives(clonedLayersMap);
2528}
2529
2530void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2531 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2532 // to the clone. If the real layer is no longer alive, continue traversing the children
2533 // since we may be able to pull out other children that are still alive.
2534 if (isClonedFromAlive()) {
2535 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002536 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002537 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002538 }
2539
2540 // The clone layer may have children in drawingState since they may have been created and
2541 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2542 // that already exist, since we can just re-use them.
2543 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2544 // not updated in the regular traversal. They are skipped since the root will lose the
2545 // reference to them when it copies its currentChildren to drawing.
2546 for (sp<Layer>& child : mDrawingChildren) {
2547 child->updateClonedDrawingState(clonedLayersMap);
2548 }
2549}
2550
2551void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2552 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2553 mDrawingChildren.clear();
2554
2555 if (!isClonedFromAlive()) {
2556 return;
2557 }
2558
2559 sp<Layer> clonedFrom = getClonedFrom();
2560 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2561 if (child == mirrorRoot) {
2562 // This is to avoid cyclical mirroring.
2563 continue;
2564 }
2565 sp<Layer> clonedChild = clonedLayersMap[child];
2566 if (clonedChild == nullptr) {
2567 clonedChild = child->createClone();
2568 clonedLayersMap[child] = clonedChild;
2569 }
2570 addChildToDrawing(clonedChild);
2571 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2572 }
2573}
2574
chaviwaf87b3e2019-10-01 16:59:28 -07002575void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2576 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2577 if (cropLayer != nullptr) {
2578 if (clonedLayersMap.count(cropLayer) == 0) {
2579 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2580 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002581 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002582 } else {
2583 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2584 mDrawingState.touchableRegionCrop = clonedCropLayer;
2585 }
2586 }
2587 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2588 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002589 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002590}
2591
2592void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002593 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002594 mDrawingState.zOrderRelatives.clear();
2595
2596 if (!isClonedFromAlive()) {
2597 return;
2598 }
2599
chaviwaf87b3e2019-10-01 16:59:28 -07002600 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002601 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002602 const sp<Layer>& relative = relativeWeak.promote();
2603 if (clonedLayersMap.count(relative) > 0) {
2604 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002605 mDrawingState.zOrderRelatives.add(clonedRelative);
2606 }
2607 }
2608
2609 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2610 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2611 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2612 // still traverse the children, but the layer with the missing relativeOf will not be shown
2613 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002614 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2615 if (clonedLayersMap.count(relativeOf) > 0) {
2616 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002617 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2618 }
2619
chaviwaf87b3e2019-10-01 16:59:28 -07002620 updateClonedInputInfo(clonedLayersMap);
2621
chaviw74b03172019-08-19 11:09:03 -07002622 for (sp<Layer>& child : mDrawingChildren) {
2623 child->updateClonedRelatives(clonedLayersMap);
2624 }
2625}
2626
2627void Layer::addChildToDrawing(const sp<Layer>& layer) {
2628 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002629 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002630}
2631
Steven Thomas62a4cf82020-01-31 12:04:03 -08002632Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2633 switch (compatibility) {
2634 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2635 return FrameRateCompatibility::Default;
2636 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2637 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002638 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2639 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002640 case ANATIVEWINDOW_FRAME_RATE_MIN:
2641 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002642 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2643 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002644 default:
2645 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2646 return FrameRateCompatibility::Default;
2647 }
2648}
2649
Marin Shalamanovc5986772021-03-16 16:09:49 +01002650scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2651 switch (strategy) {
2652 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2653 return Seamlessness::OnlySeamless;
2654 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2655 return Seamlessness::SeamedAndSeamless;
2656 default:
2657 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2658 return Seamlessness::Default;
2659 }
2660}
2661
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002662bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002663 const State& s(mDrawingState);
2664 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2665 return true;
2666 }
2667
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002668 sp<Layer> parent = mDrawingParent.promote();
2669 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002670}
2671
Robert Carr6a0382d2021-07-01 15:57:17 -07002672void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2673 mClonedChild = clonedChild;
2674 mHadClonedChild = true;
2675 mFlinger->mNumClones++;
2676}
2677
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002678bool Layer::setDropInputMode(gui::DropInputMode mode) {
2679 if (mDrawingState.dropInputMode == mode) {
2680 return false;
2681 }
2682 mDrawingState.dropInputMode = mode;
2683 return true;
2684}
2685
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002686void Layer::cloneDrawingState(const Layer* from) {
2687 mDrawingState = from->mDrawingState;
2688 // Skip callback info since they are not applicable for cloned layers.
2689 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002690 // TODO (b/238781169) currently broken for mirror layers because we do not
2691 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002692 mDrawingState.callbackHandles = {};
2693}
2694
Patrick Williamsbb25f802022-08-30 23:02:34 +00002695void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2696 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
2697 const sp<Fence>& releaseFence,
2698 uint32_t currentMaxAcquiredBufferCount) {
2699 if (!listener) {
2700 return;
2701 }
2702 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002703 listener->onReleaseBuffer({buffer->getId(), framenumber},
2704 releaseFence ? releaseFence : Fence::NO_FENCE,
2705 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002706}
2707
2708void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2709 // If we are displayed on multiple displays in a single composition cycle then we would
2710 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2711 // For example we can only use it if all the displays are client comp, and we need
2712 // to merge all the client comp fences. We could do this, but for now we just
2713 // disable the optimization when a layer is composed on multiple displays.
2714 if (mClearClientCompositionFenceOnLayerDisplayed) {
2715 mLastClientCompositionFence = nullptr;
2716 } else {
2717 mClearClientCompositionFenceOnLayerDisplayed = true;
2718 }
2719
2720 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2721 // buffer that was presented on this layer. The first transaction that came in this frame that
2722 // replaced the previous buffer on this layer needs this release fence, because the fence will
2723 // let the client know when that previous buffer is removed from the screen.
2724 //
2725 // Every other transaction on this layer does not need a release fence because no other
2726 // Transactions that were set on this layer this frame are going to have their preceding buffer
2727 // removed from the display this frame.
2728 //
2729 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2730 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2731 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2732 // the previous buffer will be released this frame. The third transaction also contains a
2733 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2734 // transaction will now no longer be presented so it is released immediately and the third
2735 // transaction doesn't need a previous release fence.
2736 sp<CallbackHandle> ch;
2737 for (auto& handle : mDrawingState.callbackHandles) {
2738 if (handle->releasePreviousBuffer &&
2739 mDrawingState.releaseBufferEndpoint == handle->listener) {
2740 ch = handle;
2741 break;
2742 }
2743 }
2744
2745 // Prevent tracing the same release multiple times.
2746 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2747 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2748 }
2749
2750 if (ch != nullptr) {
2751 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2752 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2753 ch->name = mName;
2754 }
2755}
2756
2757void Layer::onSurfaceFrameCreated(
2758 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2759 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2760 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2761 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2762 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002763 if (hasBufferOrSidebandStreamInDrawing()) {
2764 // Only log for layers with a buffer, since we expect the jank data to be drained for
2765 // these, while there may be no jank listeners for bufferless layers.
2766 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2767 mName.c_str());
2768 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2769 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2770 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002771 mPendingJankClassifications.pop_front();
2772 }
2773 mPendingJankClassifications.emplace_back(surfaceFrame);
2774}
2775
2776void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2777 for (const auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair71fcf912022-10-18 09:14:20 -07002778 handle->transformHint = mSkipReportingTransformHint
2779 ? std::nullopt
2780 : std::make_optional<uint32_t>(mTransformHint);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002781 handle->dequeueReadyTime = dequeueReadyTime;
2782 handle->currentMaxAcquiredBufferCount =
2783 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2784 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2785 handle->previousReleaseCallbackId.framenumber);
2786 }
2787
2788 for (auto& handle : mDrawingState.callbackHandles) {
2789 if (handle->releasePreviousBuffer &&
2790 mDrawingState.releaseBufferEndpoint == handle->listener) {
2791 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2792 break;
2793 }
2794 }
2795
2796 std::vector<JankData> jankData;
2797 jankData.reserve(mPendingJankClassifications.size());
2798 while (!mPendingJankClassifications.empty() &&
2799 mPendingJankClassifications.front()->getJankType()) {
2800 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
2801 mPendingJankClassifications.front();
2802 mPendingJankClassifications.pop_front();
2803 jankData.emplace_back(
2804 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
2805 }
2806
2807 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2808 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002809 mDrawingState.callbackHandles = {};
2810}
2811
2812bool Layer::willPresentCurrentTransaction() const {
2813 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2814 return (getSidebandStreamChanged() || getAutoRefresh() ||
2815 (mDrawingState.modified &&
2816 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2817}
2818
2819bool Layer::setTransform(uint32_t transform) {
2820 if (mDrawingState.bufferTransform == transform) return false;
2821 mDrawingState.bufferTransform = transform;
2822 mDrawingState.modified = true;
2823 setTransactionFlags(eTransactionNeeded);
2824 return true;
2825}
2826
2827bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2828 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2829 mDrawingState.sequence++;
2830 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2831 mDrawingState.modified = true;
2832 setTransactionFlags(eTransactionNeeded);
2833 return true;
2834}
2835
2836bool Layer::setBufferCrop(const Rect& bufferCrop) {
2837 if (mDrawingState.bufferCrop == bufferCrop) return false;
2838
2839 mDrawingState.sequence++;
2840 mDrawingState.bufferCrop = bufferCrop;
2841
2842 mDrawingState.modified = true;
2843 setTransactionFlags(eTransactionNeeded);
2844 return true;
2845}
2846
2847bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2848 if (mDrawingState.destinationFrame == destinationFrame) return false;
2849
2850 mDrawingState.sequence++;
2851 mDrawingState.destinationFrame = destinationFrame;
2852
2853 mDrawingState.modified = true;
2854 setTransactionFlags(eTransactionNeeded);
2855 return true;
2856}
2857
2858// Translate destination frame into scale and position. If a destination frame is not set, use the
2859// provided scale and position
2860bool Layer::updateGeometry() {
2861 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2862 mDrawingState.destinationFrame.isEmpty()) {
2863 // If destination frame is not set, use the requested transform set via
2864 // Layer::setPosition and Layer::setMatrix.
2865 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2866 }
2867
2868 Rect destRect = mDrawingState.destinationFrame;
2869 int32_t destW = destRect.width();
2870 int32_t destH = destRect.height();
2871 if (destRect.left < 0) {
2872 destRect.left = 0;
2873 destRect.right = destW;
2874 }
2875 if (destRect.top < 0) {
2876 destRect.top = 0;
2877 destRect.bottom = destH;
2878 }
2879
2880 if (!mDrawingState.buffer) {
2881 ui::Transform t;
2882 t.set(destRect.left, destRect.top);
2883 return assignTransform(&mDrawingState.transform, t);
2884 }
2885
2886 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2887 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2888 // Undo any transformations on the buffer.
2889 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2890 std::swap(bufferWidth, bufferHeight);
2891 }
2892 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
2893 if (mDrawingState.transformToDisplayInverse) {
2894 if (invTransform & ui::Transform::ROT_90) {
2895 std::swap(bufferWidth, bufferHeight);
2896 }
2897 }
2898
2899 float sx = destW / static_cast<float>(bufferWidth);
2900 float sy = destH / static_cast<float>(bufferHeight);
2901 ui::Transform t;
2902 t.set(sx, 0, 0, sy);
2903 t.set(destRect.left, destRect.top);
2904 return assignTransform(&mDrawingState.transform, t);
2905}
2906
2907bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
2908 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
2909 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
2910 return false;
2911 }
2912
2913 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
2914
2915 mDrawingState.sequence++;
2916 mDrawingState.modified = true;
2917 setTransactionFlags(eTransactionNeeded);
2918
2919 return true;
2920}
2921
2922bool Layer::setPosition(float x, float y) {
2923 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
2924 return false;
2925 }
2926
2927 mRequestedTransform.set(x, y);
2928
2929 mDrawingState.sequence++;
2930 mDrawingState.modified = true;
2931 setTransactionFlags(eTransactionNeeded);
2932
2933 return true;
2934}
2935
2936bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
2937 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
2938 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07002939 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00002940 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00002941 if (!buffer) {
2942 return false;
2943 }
2944
2945 const bool frameNumberChanged =
2946 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
2947 const uint64_t frameNumber =
2948 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00002949 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002950
2951 if (mDrawingState.buffer) {
2952 mReleasePreviousBuffer = true;
2953 if (!mBufferInfo.mBuffer ||
2954 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
2955 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
2956 // If mDrawingState has a buffer, and we are about to update again
2957 // before swapping to drawing state, then the first buffer will be
2958 // dropped and we should decrement the pending buffer count and
2959 // call any release buffer callbacks if set.
2960 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
2961 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
2962 mDrawingState.acquireFence,
2963 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
2964 mOwnerUid));
2965 decrementPendingBufferCount();
2966 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
2967 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
2968 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
2969 mDrawingState.bufferSurfaceFrameTX.reset();
2970 }
2971 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
2972 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
2973 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
2974 mLastClientCompositionFence,
2975 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
2976 mOwnerUid));
2977 mLastClientCompositionFence = nullptr;
2978 }
2979 }
2980
2981 mDrawingState.frameNumber = frameNumber;
2982 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
2983 mDrawingState.buffer = std::move(buffer);
2984 mDrawingState.clientCacheId = bufferData.cachedBuffer;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002985 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
2986 ? bufferData.acquireFence
2987 : Fence::NO_FENCE;
2988 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
2989 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
2990 // We latched this buffer unsiganled, so we need to pass the acquire fence
2991 // on the callback instead of just the acquire time, since it's unknown at
2992 // this point.
2993 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
2994 } else {
2995 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
2996 }
2997
2998 mDrawingState.modified = true;
2999 setTransactionFlags(eTransactionNeeded);
3000
3001 const int32_t layerId = getSequence();
3002 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3003 mOwnerUid, postTime, getGameMode());
3004 mDrawingState.desiredPresentTime = desiredPresentTime;
3005 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3006
3007 const nsecs_t presentTime = [&] {
3008 if (!isAutoTimestamp) return desiredPresentTime;
3009
3010 const auto prediction =
3011 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
3012 if (prediction.has_value()) return prediction->presentTime;
3013
3014 return static_cast<nsecs_t>(0);
3015 }();
3016
3017 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
3018 mFlinger->mScheduler->recordLayerHistory(this, presentTime, LayerUpdateType::Buffer);
3019
3020 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3021
3022 if (dequeueTime && *dequeueTime != 0) {
3023 const uint64_t bufferId = mDrawingState.buffer->getId();
3024 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3025 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3026 FrameTracer::FrameEvent::DEQUEUE);
3027 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3028 FrameTracer::FrameEvent::QUEUE);
3029 }
3030
3031 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3032 return true;
3033}
3034
3035bool Layer::setDataspace(ui::Dataspace dataspace) {
3036 mDrawingState.dataspaceRequested = true;
3037 if (mDrawingState.dataspace == dataspace) return false;
3038 mDrawingState.dataspace = dataspace;
3039 mDrawingState.modified = true;
3040 setTransactionFlags(eTransactionNeeded);
3041 return true;
3042}
3043
3044bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3045 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3046 mDrawingState.hdrMetadata = hdrMetadata;
3047 mDrawingState.modified = true;
3048 setTransactionFlags(eTransactionNeeded);
3049 return true;
3050}
3051
3052bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
3053 mDrawingState.surfaceDamageRegion = surfaceDamage;
3054 mDrawingState.modified = true;
3055 setTransactionFlags(eTransactionNeeded);
3056 return true;
3057}
3058
3059bool Layer::setApi(int32_t api) {
3060 if (mDrawingState.api == api) return false;
3061 mDrawingState.api = api;
3062 mDrawingState.modified = true;
3063 setTransactionFlags(eTransactionNeeded);
3064 return true;
3065}
3066
3067bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3068 if (mDrawingState.sidebandStream == sidebandStream) return false;
3069
3070 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3071 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3072 } else if (sidebandStream != nullptr) {
3073 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3074 }
3075
3076 mDrawingState.sidebandStream = sidebandStream;
3077 mDrawingState.modified = true;
3078 setTransactionFlags(eTransactionNeeded);
3079 if (!mSidebandStreamChanged.exchange(true)) {
3080 // mSidebandStreamChanged was false
3081 mFlinger->onLayerUpdate();
3082 }
3083 return true;
3084}
3085
3086bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles) {
3087 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3088 if (handles.empty()) {
3089 mReleasePreviousBuffer = false;
3090 return false;
3091 }
3092
3093 const bool willPresent = willPresentCurrentTransaction();
3094
3095 for (const auto& handle : handles) {
3096 // If this transaction set a buffer on this layer, release its previous buffer
3097 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3098
3099 // If this layer will be presented in this frame
3100 if (willPresent) {
3101 // If this transaction set an acquire fence on this layer, set its acquire time
3102 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3103 handle->frameNumber = mDrawingState.frameNumber;
3104
3105 // Store so latched time and release fence can be set
3106 mDrawingState.callbackHandles.push_back(handle);
3107
3108 } else { // If this layer will NOT need to be relatched and presented this frame
3109 // Notify the transaction completed thread this handle is done
3110 mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
3111 }
3112 }
3113
3114 mReleasePreviousBuffer = false;
3115 mCallbackHandleAcquireTimeOrFence = -1;
3116
3117 return willPresent;
3118}
3119
3120Rect Layer::getBufferSize(const State& /*s*/) const {
3121 // for buffer state layers we use the display frame size as the buffer size.
3122
3123 if (mBufferInfo.mBuffer == nullptr) {
3124 return Rect::INVALID_RECT;
3125 }
3126
3127 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3128 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3129
3130 // Undo any transformations on the buffer and return the result.
3131 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3132 std::swap(bufWidth, bufHeight);
3133 }
3134
3135 if (getTransformToDisplayInverse()) {
3136 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3137 if (invTransform & ui::Transform::ROT_90) {
3138 std::swap(bufWidth, bufHeight);
3139 }
3140 }
3141
3142 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3143}
3144
3145FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3146 if (mBufferInfo.mBuffer == nullptr) {
3147 return parentBounds;
3148 }
3149
3150 return getBufferSize(getDrawingState()).toFloatRect();
3151}
3152
3153bool Layer::fenceHasSignaled() const {
3154 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3155 return true;
3156 }
3157
3158 const bool fenceSignaled =
3159 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3160 if (!fenceSignaled) {
3161 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3162 TimeStats::LatchSkipReason::LateAcquire);
3163 }
3164
3165 return fenceSignaled;
3166}
3167
Vishnu Naire14c6b32022-08-06 04:20:15 +00003168bool Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003169 for (const auto& handle : mDrawingState.callbackHandles) {
3170 handle->refreshStartTime = refreshStartTime;
3171 }
3172 return hasReadyFrame();
3173}
3174
3175void Layer::setAutoRefresh(bool autoRefresh) {
3176 mDrawingState.autoRefresh = autoRefresh;
3177}
3178
3179bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3180 // 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 +00003181 auto* snapshot = editLayerSnapshot();
3182 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003183
3184 if (mSidebandStreamChanged.exchange(false)) {
3185 const State& s(getDrawingState());
3186 // mSidebandStreamChanged was true
3187 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003188 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003189 if (mSidebandStream != nullptr) {
3190 setTransactionFlags(eTransactionNeeded);
3191 mFlinger->setTransactionFlags(eTraversalNeeded);
3192 }
3193 recomputeVisibleRegions = true;
3194
3195 return true;
3196 }
3197 return false;
3198}
3199
3200bool Layer::hasFrameUpdate() const {
3201 const State& c(getDrawingState());
3202 return (mDrawingStateModified || mDrawingState.modified) &&
3203 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3204}
3205
3206void Layer::updateTexImage(nsecs_t latchTime) {
3207 const State& s(getDrawingState());
3208
3209 if (!s.buffer) {
3210 if (s.bgColorLayer) {
3211 for (auto& handle : mDrawingState.callbackHandles) {
3212 handle->latchTime = latchTime;
3213 }
3214 }
3215 return;
3216 }
3217
3218 for (auto& handle : mDrawingState.callbackHandles) {
3219 if (handle->frameNumber == mDrawingState.frameNumber) {
3220 handle->latchTime = latchTime;
3221 }
3222 }
3223
3224 const int32_t layerId = getSequence();
3225 const uint64_t bufferId = mDrawingState.buffer->getId();
3226 const uint64_t frameNumber = mDrawingState.frameNumber;
3227 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3228 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3229 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3230
3231 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3232 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3233 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3234 FrameTracer::FrameEvent::LATCH);
3235
3236 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3237 if (bufferSurfaceFrame != nullptr &&
3238 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3239 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3240 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3241 // are processing the next state.
3242 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3243 mDrawingState.acquireFenceTime->getSignalTime(),
3244 latchTime);
3245 mDrawingState.bufferSurfaceFrameTX.reset();
3246 }
3247
3248 std::deque<sp<CallbackHandle>> remainingHandles;
3249 mFlinger->getTransactionCallbackInvoker()
3250 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3251 mDrawingState.callbackHandles = remainingHandles;
3252
3253 mDrawingStateModified = false;
3254}
3255
3256void Layer::gatherBufferInfo() {
3257 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3258 decrementPendingBufferCount();
3259 }
3260
3261 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3262 mBufferInfo.mBuffer = mDrawingState.buffer;
3263 mBufferInfo.mFence = mDrawingState.acquireFence;
3264 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3265 mBufferInfo.mPixelFormat =
3266 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3267 mBufferInfo.mFrameLatencyNeeded = true;
3268 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3269 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3270 mBufferInfo.mFence = mDrawingState.acquireFence;
3271 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3272 auto lastDataspace = mBufferInfo.mDataspace;
3273 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3274 if (lastDataspace != mBufferInfo.mDataspace) {
3275 mFlinger->mSomeDataspaceChanged = true;
3276 }
3277 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3278 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3279 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3280 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3281 mBufferInfo.mApi = mDrawingState.api;
3282 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003283}
3284
3285Rect Layer::computeBufferCrop(const State& s) {
3286 if (s.buffer && !s.bufferCrop.isEmpty()) {
3287 Rect bufferCrop;
3288 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3289 return bufferCrop;
3290 } else if (s.buffer) {
3291 return s.buffer->getBounds();
3292 } else {
3293 return s.bufferCrop;
3294 }
3295}
3296
3297sp<Layer> Layer::createClone() {
3298 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3299 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003300 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003301 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3302 return layer;
3303}
3304
3305bool Layer::bufferNeedsFiltering() const {
3306 const State& s(getDrawingState());
3307 if (!s.buffer) {
3308 return false;
3309 }
3310
3311 int32_t bufferWidth = static_cast<int32_t>(s.buffer->getWidth());
3312 int32_t bufferHeight = static_cast<int32_t>(s.buffer->getHeight());
3313
3314 // Undo any transformations on the buffer and return the result.
3315 if (s.bufferTransform & ui::Transform::ROT_90) {
3316 std::swap(bufferWidth, bufferHeight);
3317 }
3318
3319 if (s.transformToDisplayInverse) {
3320 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3321 if (invTransform & ui::Transform::ROT_90) {
3322 std::swap(bufferWidth, bufferHeight);
3323 }
3324 }
3325
3326 const Rect layerSize{getBounds()};
3327 int32_t layerWidth = layerSize.getWidth();
3328 int32_t layerHeight = layerSize.getHeight();
3329
3330 // Align the layer orientation with the buffer before comparism
3331 if (mTransformHint & ui::Transform::ROT_90) {
3332 std::swap(layerWidth, layerHeight);
3333 }
3334
3335 return layerWidth != bufferWidth || layerHeight != bufferHeight;
3336}
3337
3338void Layer::decrementPendingBufferCount() {
3339 int32_t pendingBuffers = --mPendingBufferTransactions;
3340 tracePendingBufferCount(pendingBuffers);
3341}
3342
3343void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3344 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3345}
3346
3347/*
3348 * We don't want to send the layer's transform to input, but rather the
3349 * parent's transform. This is because Layer's transform is
3350 * information about how the buffer is placed on screen. The parent's
3351 * transform makes more sense to send since it's information about how the
3352 * layer is placed on screen. This transform is used by input to determine
3353 * how to go from screen space back to window space.
3354 */
3355ui::Transform Layer::getInputTransform() const {
3356 if (!hasBufferOrSidebandStream()) {
3357 return getTransform();
3358 }
3359 sp<Layer> parent = mDrawingParent.promote();
3360 if (parent == nullptr) {
3361 return ui::Transform();
3362 }
3363
3364 return parent->getTransform();
3365}
3366
3367/**
3368 * Similar to getInputTransform, we need to update the bounds to include the transform.
3369 * This is because bounds don't include the buffer transform, where the input assumes
3370 * that's already included.
3371 */
3372Rect Layer::getInputBounds() const {
3373 if (!hasBufferOrSidebandStream()) {
3374 return getCroppedBufferSize(getDrawingState());
3375 }
3376
3377 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
3378 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
3379 return bufferBounds;
3380 }
3381 return mDrawingState.transform.transform(bufferBounds);
3382}
3383
3384bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3385 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3386
3387 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3388 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3389 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3390 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3391 layer_state_t::eReparent;
3392
3393 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3394 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3395 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3396 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3397 layer_state_t::eInputInfoChanged;
3398
3399 if ((s.what & requiredFlags) != requiredFlags) {
3400 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3401 (s.what | requiredFlags) & ~s.what);
3402 return false;
3403 }
3404
3405 if (s.what & deniedFlags) {
3406 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3407 return false;
3408 }
3409
3410 if (s.what & allowedFlags) {
3411 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3412 }
3413
3414 if (s.what & layer_state_t::ePositionChanged) {
3415 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3416 ALOGV("%s: false [ePositionChanged changed]", __func__);
3417 return false;
3418 }
3419 }
3420
3421 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003422 if (mDrawingState.color.a != s.color.a) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003423 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3424 return false;
3425 }
3426 }
3427
3428 if (s.what & layer_state_t::eColorTransformChanged) {
3429 if (mDrawingState.colorTransform != s.colorTransform) {
3430 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3431 return false;
3432 }
3433 }
3434
3435 if (s.what & layer_state_t::eBackgroundColorChanged) {
3436 if (mDrawingState.bgColorLayer || s.bgColorAlpha != 0) {
3437 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3438 return false;
3439 }
3440 }
3441
3442 if (s.what & layer_state_t::eMatrixChanged) {
3443 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3444 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3445 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3446 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3447 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3448 return false;
3449 }
3450 }
3451
3452 if (s.what & layer_state_t::eCornerRadiusChanged) {
3453 if (mDrawingState.cornerRadius != s.cornerRadius) {
3454 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3455 return false;
3456 }
3457 }
3458
3459 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3460 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3461 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3462 return false;
3463 }
3464 }
3465
Vishnu Nairbbceb462022-10-10 04:52:13 +00003466 if (s.what & layer_state_t::eBufferTransformChanged) {
3467 if (mDrawingState.bufferTransform != s.bufferTransform) {
3468 ALOGV("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003469 return false;
3470 }
3471 }
3472
3473 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3474 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3475 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3476 return false;
3477 }
3478 }
3479
3480 if (s.what & layer_state_t::eCropChanged) {
3481 if (mDrawingState.crop != s.crop) {
3482 ALOGV("%s: false [eCropChanged changed]", __func__);
3483 return false;
3484 }
3485 }
3486
3487 if (s.what & layer_state_t::eDataspaceChanged) {
3488 if (mDrawingState.dataspace != s.dataspace) {
3489 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3490 return false;
3491 }
3492 }
3493
3494 if (s.what & layer_state_t::eHdrMetadataChanged) {
3495 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3496 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3497 return false;
3498 }
3499 }
3500
3501 if (s.what & layer_state_t::eSidebandStreamChanged) {
3502 if (mDrawingState.sidebandStream != s.sidebandStream) {
3503 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3504 return false;
3505 }
3506 }
3507
3508 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3509 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3510 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3511 return false;
3512 }
3513 }
3514
3515 if (s.what & layer_state_t::eShadowRadiusChanged) {
3516 if (mDrawingState.shadowRadius != s.shadowRadius) {
3517 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3518 return false;
3519 }
3520 }
3521
3522 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3523 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3524 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3525 return false;
3526 }
3527 }
3528
3529 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3530 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3531 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3532 return false;
3533 }
3534 }
3535
3536 if (s.what & layer_state_t::eStretchChanged) {
3537 StretchEffect temp = s.stretchEffect;
3538 temp.sanitize();
3539 if (mDrawingState.stretchEffect != temp) {
3540 ALOGV("%s: false [eStretchChanged changed]", __func__);
3541 return false;
3542 }
3543 }
3544
3545 if (s.what & layer_state_t::eBufferCropChanged) {
3546 if (mDrawingState.bufferCrop != s.bufferCrop) {
3547 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3548 return false;
3549 }
3550 }
3551
3552 if (s.what & layer_state_t::eDestinationFrameChanged) {
3553 if (mDrawingState.destinationFrame != s.destinationFrame) {
3554 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3555 return false;
3556 }
3557 }
3558
3559 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3560 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3561 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3562 return false;
3563 }
3564 }
3565
3566 ALOGV("%s: true", __func__);
3567 return true;
3568}
3569
3570bool Layer::isHdrY410() const {
3571 // pixel format is HDR Y410 masquerading as RGBA_1010102
3572 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3573 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3574 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3575}
3576
Vishnu Naire14c6b32022-08-06 04:20:15 +00003577sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003578 // There's no need to get a CE Layer if the layer isn't going to draw anything.
Vishnu Naire14c6b32022-08-06 04:20:15 +00003579 return hasSomethingToDraw() ? mLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003580}
3581
Vishnu Naire14c6b32022-08-06 04:20:15 +00003582const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003583 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003584}
3585
Vishnu Naire14c6b32022-08-06 04:20:15 +00003586LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003587 return mSnapshot.get();
3588}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003589
Patrick Williamsbb25f802022-08-30 23:02:34 +00003590const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003591 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003592}
3593
Patrick Williams7584c6a2022-10-29 02:10:58 +00003594sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
3595 auto result = mFlinger->getFactory().createLayerFE(mLayerFE->getDebugName());
3596 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3597 return result;
3598}
3599
Patrick Williamsbb25f802022-08-30 23:02:34 +00003600void Layer::useSurfaceDamage() {
3601 if (mFlinger->mForceFullDamage) {
3602 surfaceDamageRegion = Region::INVALID_REGION;
3603 } else {
3604 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3605 }
3606}
3607
3608void Layer::useEmptyDamage() {
3609 surfaceDamageRegion.clear();
3610}
3611
3612bool Layer::isOpaque(const Layer::State& s) const {
3613 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3614 // layer's opaque flag.
3615 if (!hasSomethingToDraw()) {
3616 return false;
3617 }
3618
3619 // if the layer has the opaque flag, then we're always opaque
3620 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3621 return true;
3622 }
3623
3624 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003625 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003626 return true;
3627 }
3628
3629 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3630 return fillsColor() && getAlpha() == 1.0_hf;
3631}
3632
3633bool Layer::canReceiveInput() const {
3634 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3635}
3636
3637bool Layer::isVisible() const {
3638 if (!hasSomethingToDraw()) {
3639 return false;
3640 }
3641
3642 if (isHiddenByPolicy()) {
3643 return false;
3644 }
3645
3646 return getAlpha() > 0.0f || hasBlur();
3647}
3648
3649void Layer::onPostComposition(const DisplayDevice* display,
3650 const std::shared_ptr<FenceTime>& glDoneFence,
3651 const std::shared_ptr<FenceTime>& presentFence,
3652 const CompositorTiming& compositorTiming) {
3653 // mFrameLatencyNeeded is true when a new frame was latched for the
3654 // composition.
3655 if (!mBufferInfo.mFrameLatencyNeeded) return;
3656
3657 for (const auto& handle : mDrawingState.callbackHandles) {
3658 handle->gpuCompositionDoneFence = glDoneFence;
3659 handle->compositorTiming = compositorTiming;
3660 }
3661
3662 // Update mFrameTracker.
3663 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3664 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3665
3666 const int32_t layerId = getSequence();
3667 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3668
3669 const auto outputLayer = findOutputLayerForDisplay(display);
3670 if (outputLayer && outputLayer->requiresClientComposition()) {
3671 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3672 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3673 clientCompositionTimestamp,
3674 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3675 // Update the SurfaceFrames in the drawing state
3676 if (mDrawingState.bufferSurfaceFrameTX) {
3677 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3678 }
3679 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3680 surfaceFrame->setGpuComposition();
3681 }
3682 }
3683
3684 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3685 if (frameReadyFence->isValid()) {
3686 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3687 } else {
3688 // There was no fence for this frame, so assume that it was ready
3689 // to be presented at the desired present time.
3690 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3691 }
3692
3693 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08003694 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003695 const std::optional<Fps> renderRate =
3696 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3697
3698 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3699 const auto gameMode = getGameMode();
3700
3701 if (presentFence->isValid()) {
3702 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3703 refreshRate, renderRate, vote, gameMode);
3704 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3705 presentFence,
3706 FrameTracer::FrameEvent::PRESENT_FENCE);
3707 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3708 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3709 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003710 // The HWC doesn't support present fences, so use the present timestamp instead.
3711 const nsecs_t presentTimestamp =
3712 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3713
3714 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3715 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3716 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3717
Patrick Williamsbb25f802022-08-30 23:02:34 +00003718 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3719 refreshRate, renderRate, vote, gameMode);
3720 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3721 mCurrentFrameNumber, actualPresentTime,
3722 FrameTracer::FrameEvent::PRESENT_FENCE);
3723 mFrameTracker.setActualPresentTime(actualPresentTime);
3724 }
3725 }
3726
3727 mFrameTracker.advanceFrame();
3728 mBufferInfo.mFrameLatencyNeeded = false;
3729}
3730
3731bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
3732 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3733 getDrawingState().frameNumber);
3734
3735 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3736
3737 if (refreshRequired) {
3738 return refreshRequired;
3739 }
3740
3741 // If the head buffer's acquire fence hasn't signaled yet, return and
3742 // try again later
3743 if (!fenceHasSignaled()) {
3744 ATRACE_NAME("!fenceHasSignaled()");
3745 mFlinger->onLayerUpdate();
3746 return false;
3747 }
3748
3749 updateTexImage(latchTime);
3750 if (mDrawingState.buffer == nullptr) {
3751 return false;
3752 }
3753
3754 // Capture the old state of the layer for comparisons later
3755 BufferInfo oldBufferInfo = mBufferInfo;
3756 const bool oldOpacity = isOpaque(mDrawingState);
3757 mPreviousFrameNumber = mCurrentFrameNumber;
3758 mCurrentFrameNumber = mDrawingState.frameNumber;
3759 gatherBufferInfo();
3760
3761 if (oldBufferInfo.mBuffer == nullptr) {
3762 // the first time we receive a buffer, we need to trigger a
3763 // geometry invalidation.
3764 recomputeVisibleRegions = true;
3765 }
3766
3767 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3768 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3769 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3770 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3771 recomputeVisibleRegions = true;
3772 }
3773
3774 if (oldBufferInfo.mBuffer != nullptr) {
3775 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3776 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3777 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3778 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3779 recomputeVisibleRegions = true;
3780 }
3781 }
3782
3783 if (oldOpacity != isOpaque(mDrawingState)) {
3784 recomputeVisibleRegions = true;
3785 }
3786
3787 return true;
3788}
3789
3790bool Layer::hasReadyFrame() const {
3791 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
3792}
3793
3794bool Layer::isProtected() const {
3795 return (mBufferInfo.mBuffer != nullptr) &&
3796 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
3797}
3798
Patrick Williamsbb25f802022-08-30 23:02:34 +00003799bool Layer::needsFiltering(const DisplayDevice* display) const {
3800 if (!hasBufferOrSidebandStream()) {
3801 return false;
3802 }
3803 const auto outputLayer = findOutputLayerForDisplay(display);
3804 if (outputLayer == nullptr) {
3805 return false;
3806 }
3807
3808 // We need filtering if the sourceCrop rectangle size does not match the
3809 // displayframe rectangle size (not a 1:1 render)
3810 const auto& compositionState = outputLayer->getState();
3811 const auto displayFrame = compositionState.displayFrame;
3812 const auto sourceCrop = compositionState.sourceCrop;
3813 return sourceCrop.getHeight() != displayFrame.getHeight() ||
3814 sourceCrop.getWidth() != displayFrame.getWidth();
3815}
3816
3817bool Layer::needsFilteringForScreenshots(const DisplayDevice* display,
3818 const ui::Transform& inverseParentTransform) const {
3819 if (!hasBufferOrSidebandStream()) {
3820 return false;
3821 }
3822 const auto outputLayer = findOutputLayerForDisplay(display);
3823 if (outputLayer == nullptr) {
3824 return false;
3825 }
3826
3827 // We need filtering if the sourceCrop rectangle size does not match the
3828 // viewport rectangle size (not a 1:1 render)
3829 const auto& compositionState = outputLayer->getState();
3830 const ui::Transform& displayTransform = display->getTransform();
3831 const ui::Transform inverseTransform = inverseParentTransform * displayTransform.inverse();
3832 // Undo the transformation of the displayFrame so that we're back into
3833 // layer-stack space.
3834 const Rect frame = inverseTransform.transform(compositionState.displayFrame);
3835 const FloatRect sourceCrop = compositionState.sourceCrop;
3836
3837 int32_t frameHeight = frame.getHeight();
3838 int32_t frameWidth = frame.getWidth();
3839 // If the display transform had a rotational component then undo the
3840 // rotation so that the orientation matches the source crop.
3841 if (displayTransform.getOrientation() & ui::Transform::ROT_90) {
3842 std::swap(frameHeight, frameWidth);
3843 }
3844 return sourceCrop.getHeight() != frameHeight || sourceCrop.getWidth() != frameWidth;
3845}
3846
3847void Layer::latchAndReleaseBuffer() {
3848 if (hasReadyFrame()) {
3849 bool ignored = false;
3850 latchBuffer(ignored, systemTime());
3851 }
3852 releasePendingBuffer(systemTime());
3853}
3854
3855PixelFormat Layer::getPixelFormat() const {
3856 return mBufferInfo.mPixelFormat;
3857}
3858
3859bool Layer::getTransformToDisplayInverse() const {
3860 return mBufferInfo.mTransformToDisplayInverse;
3861}
3862
3863Rect Layer::getBufferCrop() const {
3864 // this is the crop rectangle that applies to the buffer
3865 // itself (as opposed to the window)
3866 if (!mBufferInfo.mCrop.isEmpty()) {
3867 // if the buffer crop is defined, we use that
3868 return mBufferInfo.mCrop;
3869 } else if (mBufferInfo.mBuffer != nullptr) {
3870 // otherwise we use the whole buffer
3871 return mBufferInfo.mBuffer->getBounds();
3872 } else {
3873 // if we don't have a buffer yet, we use an empty/invalid crop
3874 return Rect();
3875 }
3876}
3877
3878uint32_t Layer::getBufferTransform() const {
3879 return mBufferInfo.mTransform;
3880}
3881
3882ui::Dataspace Layer::getDataSpace() const {
3883 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
3884}
3885
3886ui::Dataspace Layer::getRequestedDataSpace() const {
3887 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
3888}
3889
3890ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
3891 ui::Dataspace updatedDataspace = dataspace;
3892 // translate legacy dataspaces to modern dataspaces
3893 switch (dataspace) {
3894 case ui::Dataspace::SRGB:
3895 updatedDataspace = ui::Dataspace::V0_SRGB;
3896 break;
3897 case ui::Dataspace::SRGB_LINEAR:
3898 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
3899 break;
3900 case ui::Dataspace::JFIF:
3901 updatedDataspace = ui::Dataspace::V0_JFIF;
3902 break;
3903 case ui::Dataspace::BT601_625:
3904 updatedDataspace = ui::Dataspace::V0_BT601_625;
3905 break;
3906 case ui::Dataspace::BT601_525:
3907 updatedDataspace = ui::Dataspace::V0_BT601_525;
3908 break;
3909 case ui::Dataspace::BT709:
3910 updatedDataspace = ui::Dataspace::V0_BT709;
3911 break;
3912 default:
3913 break;
3914 }
3915
3916 return updatedDataspace;
3917}
3918
3919sp<GraphicBuffer> Layer::getBuffer() const {
3920 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
3921}
3922
Patrick Williamsbb25f802022-08-30 23:02:34 +00003923void Layer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
3924 mTransformHint = getFixedTransformHint();
3925 if (mTransformHint == ui::Transform::ROT_INVALID) {
3926 mTransformHint = displayTransformHint;
3927 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07003928 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003929}
3930
3931const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
3932 return mBufferInfo.mBuffer;
3933}
3934
3935bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003936 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003937 return false;
3938 }
3939
3940 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00003941 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003942 mDrawingState.modified = true;
3943 setTransactionFlags(eTransactionNeeded);
3944 return true;
3945}
3946
3947bool Layer::fillsColor() const {
3948 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
3949 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
3950}
3951
3952bool Layer::hasBlur() const {
3953 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
3954}
3955
Vishnu Nairba354102022-08-01 00:14:18 +00003956void Layer::updateSnapshot(bool updateGeometry) {
3957 if (!getCompositionEngineLayerFE()) {
3958 return;
3959 }
3960
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003961 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00003962 if (updateGeometry) {
3963 prepareBasicGeometryCompositionState();
3964 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003965 snapshot->roundedCorner = getRoundedCornerState();
3966 snapshot->stretchEffect = getStretchEffect();
3967 snapshot->transformedBounds = mScreenBounds;
3968 if (mEffectiveShadowRadius > 0.f) {
3969 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
3970
3971 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
3972 // it if transparent regions are present. This may not be necessary since shadows are
3973 // typically cast by layers without transparent regions.
3974 snapshot->shadowSettings.boundaries = mBounds;
3975
3976 const float casterAlpha = snapshot->alpha;
3977 const bool casterIsOpaque =
3978 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
3979
3980 // If the casting layer is translucent, we need to fill in the shadow underneath the
3981 // layer. Otherwise the generated shadow will only be shown around the casting layer.
3982 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
3983 snapshot->shadowSettings.ambientColor *= casterAlpha;
3984 snapshot->shadowSettings.spotColor *= casterAlpha;
3985 }
3986 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00003987 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003988 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003989 snapshot->layerOpaqueFlagSet =
3990 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003991 snapshot->isHdrY410 = isHdrY410();
3992 snapshot->bufferNeedsFiltering = bufferNeedsFiltering();
3993 sp<Layer> p = mDrawingParent.promote();
3994 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003995 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003996 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003997 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003998 }
3999 snapshot->bufferSize = getBufferSize(mDrawingState);
4000 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004001 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004002 preparePerFrameCompositionState();
4003}
4004
Vishnu Naire14c6b32022-08-06 04:20:15 +00004005void Layer::updateChildrenSnapshots(bool updateGeometry) {
4006 for (const sp<Layer>& child : mDrawingChildren) {
4007 child->updateSnapshot(updateGeometry);
4008 child->updateChildrenSnapshots(updateGeometry);
4009 }
4010}
4011
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004012void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4013 mSnapshot->layerMetadata = parentMetadata;
4014 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4015 for (const sp<Layer>& child : mDrawingChildren) {
4016 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4017 }
4018}
4019
4020void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4021 std::unordered_set<Layer*>& visited) {
4022 if (visited.find(this) != visited.end()) {
4023 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4024 return;
4025 }
4026 visited.insert(this);
4027
4028 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4029
4030 if (mDrawingState.zOrderRelatives.empty()) {
4031 return;
4032 }
4033 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4034 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4035 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4036 sp<Layer> relative = weakRelative.promote();
4037 if (!relative) {
4038 continue;
4039 }
4040 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4041 }
4042}
4043
Patrick Williams377c0142022-10-13 17:33:38 +00004044LayerSnapshotGuard::LayerSnapshotGuard(Layer* layer) : mLayer(layer) {
Patrick Williams4da60852022-11-17 17:19:38 +00004045 if (mLayer) {
4046 mLayer->mLayerFE->mSnapshot = std::move(mLayer->mSnapshot);
4047 }
Patrick Williams377c0142022-10-13 17:33:38 +00004048}
4049
4050LayerSnapshotGuard::~LayerSnapshotGuard() {
4051 if (mLayer) {
4052 mLayer->mSnapshot = std::move(mLayer->mLayerFE->mSnapshot);
4053 }
4054}
4055
4056LayerSnapshotGuard::LayerSnapshotGuard(LayerSnapshotGuard&& other) : mLayer(other.mLayer) {
4057 other.mLayer = nullptr;
4058}
4059
4060LayerSnapshotGuard& LayerSnapshotGuard::operator=(LayerSnapshotGuard&& other) {
4061 mLayer = other.mLayer;
4062 other.mLayer = nullptr;
4063 return *this;
4064}
4065
Chavi Weingarten076acac2023-01-19 17:20:43 +00004066void Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
4067 TrustedPresentationListener const& listener) {
4068 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4069 mTrustedPresentationListener = listener;
4070 mTrustedPresentationThresholds = thresholds;
4071 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4072 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4073 mFlinger->mNumTrustedPresentationListeners++;
4074 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4075 mFlinger->mNumTrustedPresentationListeners--;
4076 }
4077}
4078
Mathias Agopian13127d82013-03-05 17:47:11 -08004079// ---------------------------------------------------------------------------
4080
Marin Shalamanov46084422020-10-13 12:33:42 +02004081std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004082 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4083 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004084}
4085
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004086} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004087
4088#if defined(__gl_h_)
4089#error "don't include gl/gl.h in this file"
4090#endif
4091
4092#if defined(__gl2_h_)
4093#error "don't include gl2/gl2.h in this file"
4094#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004095
4096// TODO(b/129481165): remove the #pragma below and fix conversion issues
4097#pragma clang diagnostic pop // ignored "-Wconversion"