blob: df76ed02c71750f937dda35b54966c94804a11fe [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 Nair8fc721b2022-12-22 20:06:32 +0000569 snapshot->localTransformInverse = getActiveTransform(drawingState).inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000570 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
571 snapshot->alpha = alpha;
572 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
573 snapshot->blurRegions = drawingState.blurRegions;
574 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800575}
576
Lloyd Piquede196652020-01-22 17:29:58 -0800577void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800578 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000579 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700580
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000581 snapshot->geomBufferSize = getBufferSize(drawingState);
582 snapshot->geomContentCrop = getBufferCrop();
583 snapshot->geomCrop = getCrop(drawingState);
584 snapshot->geomBufferTransform = getBufferTransform();
585 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
586 snapshot->geomUsesSourceCrop = usesSourceCrop();
587 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800588
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000589 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800590 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
591 for (const auto& [key, mandatory] : supportedMetadata) {
592 const auto& genericLayerMetadataCompatibilityMap =
593 mFlinger->getGenericLayerMetadataKeyMap();
594 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
595 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
596 continue;
597 }
598 const uint32_t id = compatIter->second;
599
600 auto it = drawingState.metadata.mMap.find(id);
601 if (it == std::end(drawingState.metadata.mMap)) {
602 continue;
603 }
604
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000605 snapshot->metadata.emplace(key,
606 compositionengine::GenericLayerMetadataEntry{mandatory,
607 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800608 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800609}
David Sodmanba340492018-08-05 21:51:33 -0700610
Lloyd Piquede196652020-01-22 17:29:58 -0800611void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800612 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000613 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800614
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000615 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800616
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000617 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
618 snapshot->dataspace = getDataSpace();
619 snapshot->colorTransform = getColorTransform();
620 snapshot->colorTransformIsIdentity = !hasColorTransform();
621 snapshot->surfaceDamage = surfaceDamageRegion;
622 snapshot->hasProtectedContent = isProtected();
623 snapshot->dimmingEnabled = isDimmingEnabled();
Lloyd Pique688abd42019-02-15 15:42:24 -0800624
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700625 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700626
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000627 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800628
629 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400630 // Rounded corners no longer force client composition, since we may use a
631 // hole punch so that the layer will appear to have rounded corners.
632 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000633 snapshot->stretchEffect.hasEffect()) {
634 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800635 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700636 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000637 snapshot->blurRegions = drawingState.blurRegions;
638 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400639
640 // Layer framerate is used in caching decisions.
641 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
642 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000643 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000644
645 if (hasBufferOrSidebandStream()) {
646 preparePerFrameBufferCompositionState();
647 } else {
648 preparePerFrameEffectsCompositionState();
649 }
650}
651
652void Layer::preparePerFrameBufferCompositionState() {
653 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000654 auto* snapshot = editLayerSnapshot();
655 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
656 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000657 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
658 return;
659 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000660 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000661 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
662 } else {
663 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000664 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
665 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000666 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
667 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
668 }
669
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000670 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000671 snapshot->acquireFence = mBufferInfo.mFence;
672 snapshot->frameNumber = mBufferInfo.mFrameNumber;
673 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000674}
675
676void Layer::preparePerFrameEffectsCompositionState() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000677 auto* snapshot = editLayerSnapshot();
678 snapshot->color = getColor();
679 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000680 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800681}
682
Lloyd Piquede196652020-01-22 17:29:58 -0800683void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800684 const State& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000685 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800686
687 // Apply the layer's transform, followed by the display's global transform
688 // Here we're guaranteed that the layer's transform preserves rects
689 Rect win = getCroppedBufferSize(drawingState);
690 // Subtract the transparent region and snap to the bounds
691 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
692 Rect frame(getTransform().transform(bounds));
693
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000694 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800695}
696
Lloyd Piquea83776c2019-01-29 18:42:32 -0800697const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700698 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800699}
700
Mathias Agopian13127d82013-03-05 17:47:11 -0800701// ---------------------------------------------------------------------------
702// drawing...
703// ---------------------------------------------------------------------------
704
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500705aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
706 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700707 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800708 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500709 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800710 }
711 if (outputLayer->getState().hwc) {
712 return (*outputLayer->getState().hwc).hwcCompositionType;
713 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500714 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800715 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800716}
717
Mathias Agopian13127d82013-03-05 17:47:11 -0800718// ----------------------------------------------------------------------------
719// local state
720// ----------------------------------------------------------------------------
721
David Sodman41fdfc92017-11-06 16:09:56 -0800722bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800723 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700724 if (s.flags & layer_state_t::eLayerSecure) {
725 return true;
726 }
727
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000728 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700729 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700730}
731
Mathias Agopian13127d82013-03-05 17:47:11 -0800732// ----------------------------------------------------------------------------
733// transaction
734// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800735
Marissa Wall61c58622018-07-18 10:12:20 -0700736uint32_t Layer::doTransaction(uint32_t flags) {
737 ATRACE_CALL();
738
Robert Carr0758e5d2021-03-11 22:15:04 -0800739 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700740 mDrawingStateModified = mDrawingState.modified;
741 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700742
Alec Mourib416efd2018-09-06 21:01:59 +0000743 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700744
Robert Carr6a160312021-05-17 12:08:20 -0700745 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800746 // invalidate and recompute the visible regions if needed
747 flags |= Layer::eVisibleRegion;
748 }
749
Robert Carr6a160312021-05-17 12:08:20 -0700750 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800751 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000752 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800753 flags |= eVisibleRegion;
754 this->contentDirty = true;
755
756 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700757 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800758 }
759
Arthur Hung9ed43392022-05-27 06:31:57 +0000760 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
761 mFlinger->mUpdateInputInfo = true;
762 }
763
Robert Carr6a160312021-05-17 12:08:20 -0700764 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800765
Mathias Agopian13127d82013-03-05 17:47:11 -0800766 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800767}
768
Robert Carr6a160312021-05-17 12:08:20 -0700769void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000770 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
771 // bufferSurfaceFrameTX will be presented in latchBuffer.
772 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
773 if (surfaceFrame->getPresentState() != PresentState::Presented) {
774 // With applyPendingStates, we could end up having presented surfaceframes from previous
775 // states
776 surfaceFrame->setPresentState(PresentState::Presented);
777 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
778 }
779 }
Robert Carr6a160312021-05-17 12:08:20 -0700780 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700781}
782
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700783uint32_t Layer::clearTransactionFlags(uint32_t mask) {
784 const auto flags = mTransactionFlags & mask;
785 mTransactionFlags &= ~mask;
786 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800787}
788
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700789void Layer::setTransactionFlags(uint32_t mask) {
790 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800791}
792
Robert Carr1f0a16a2016-10-24 16:27:39 -0700793bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
794 ssize_t idx = mCurrentChildren.indexOf(childLayer);
795 if (idx < 0) {
796 return false;
797 }
798 if (childLayer->setLayer(z)) {
799 mCurrentChildren.removeAt(idx);
800 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800801 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700802 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800803 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700804}
805
Robert Carr503c7042017-09-27 15:06:08 -0700806bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
807 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
808 ssize_t idx = mCurrentChildren.indexOf(childLayer);
809 if (idx < 0) {
810 return false;
811 }
812 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
813 mCurrentChildren.removeAt(idx);
814 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800815 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700816 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800817 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700818}
819
Robert Carrae060832016-11-28 10:51:00 -0800820bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700821 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
822 mDrawingState.sequence++;
823 mDrawingState.z = z;
824 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700825
Robert Carra70e91c2021-06-11 13:59:52 -0700826 mFlinger->mSomeChildrenChanged = true;
827
Robert Carrdb66e622017-04-10 16:55:57 -0700828 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700829 if (mDrawingState.zOrderRelativeOf != nullptr) {
830 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700831 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700832 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700833 }
chaviw606e5cf2019-03-01 10:12:10 -0800834 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700835 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800836 setTransactionFlags(eTransactionNeeded);
837 return true;
838}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700839
Robert Carrdb66e622017-04-10 16:55:57 -0700840void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700841 mDrawingState.zOrderRelatives.remove(relative);
842 mDrawingState.sequence++;
843 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700844 setTransactionFlags(eTransactionNeeded);
845}
846
847void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700848 mDrawingState.zOrderRelatives.add(relative);
849 mDrawingState.modified = true;
850 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700851 setTransactionFlags(eTransactionNeeded);
852}
853
chaviw606e5cf2019-03-01 10:12:10 -0800854void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700855 mDrawingState.zOrderRelativeOf = relativeOf;
856 mDrawingState.sequence++;
857 mDrawingState.modified = true;
858 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700859
chaviw606e5cf2019-03-01 10:12:10 -0800860 setTransactionFlags(eTransactionNeeded);
861}
862
Robert Carr503d2bd2017-12-04 15:49:47 -0800863bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000864 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700865 if (relative == nullptr) {
866 return false;
867 }
868
Robert Carr6a160312021-05-17 12:08:20 -0700869 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
870 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800871 return false;
872 }
873
Robert Carr88b85e12022-03-21 15:47:35 -0700874 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
875 (relative->mDrawingState.zOrderRelativeOf == this)) {
876 ALOGE("Detected relative layer loop between %s and %s",
877 mName.c_str(), relative->mName.c_str());
878 ALOGE("Ignoring new call to set relative layer");
879 return false;
880 }
881
Robert Carra70e91c2021-06-11 13:59:52 -0700882 mFlinger->mSomeChildrenChanged = true;
883
Robert Carr6a160312021-05-17 12:08:20 -0700884 mDrawingState.sequence++;
885 mDrawingState.modified = true;
886 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700887
Robert Carr6a160312021-05-17 12:08:20 -0700888 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700889 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700890 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700891 }
chaviw606e5cf2019-03-01 10:12:10 -0800892 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700893 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700894
895 setTransactionFlags(eTransactionNeeded);
896
897 return true;
898}
899
Winson Chunga30f7c92021-06-29 15:42:56 -0700900bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
901 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
902 mDrawingState.isTrustedOverlay = isTrustedOverlay;
903 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000904 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700905 setTransactionFlags(eTransactionNeeded);
906 return true;
907}
908
909bool Layer::isTrustedOverlay() const {
910 if (getDrawingState().isTrustedOverlay) {
911 return true;
912 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000913 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700914 return (p != nullptr) && p->isTrustedOverlay();
915}
916
Dan Stoza9e56aa02015-11-02 13:00:03 -0800917bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700918 if (mDrawingState.color.a == alpha) return false;
919 mDrawingState.sequence++;
920 mDrawingState.color.a = alpha;
921 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800922 setTransactionFlags(eTransactionNeeded);
923 return true;
924}
chaviw13fdc492017-06-27 12:40:18 -0700925
Valerie Haudd0b7572019-01-29 14:59:27 -0800926bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700927 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700928 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800929 }
Robert Carr6a160312021-05-17 12:08:20 -0700930 mDrawingState.sequence++;
931 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800932 setTransactionFlags(eTransactionNeeded);
933
Robert Carr6a160312021-05-17 12:08:20 -0700934 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -0800935 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -0800936 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700937 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -0700938 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800939 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700940 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -0700941
Valerie Haudd0b7572019-01-29 14:59:27 -0800942 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -0700943 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -0800944 mFlinger->mLayersAdded = true;
945 // set up SF to handle added color layer
946 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -0700947 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -0800948 }
949 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -0700950 } else if (mDrawingState.bgColorLayer && alpha == 0) {
951 mDrawingState.bgColorLayer->reparent(nullptr);
952 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -0800953 return true;
954 }
955
Robert Carr6a160312021-05-17 12:08:20 -0700956 mDrawingState.bgColorLayer->setColor(color);
957 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
958 mDrawingState.bgColorLayer->setAlpha(alpha);
959 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -0800960
chaviw13fdc492017-06-27 12:40:18 -0700961 return true;
962}
963
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700964bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -0700965 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700966
Robert Carr6a160312021-05-17 12:08:20 -0700967 mDrawingState.sequence++;
968 mDrawingState.cornerRadius = cornerRadius;
969 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700970 setTransactionFlags(eTransactionNeeded);
971 return true;
972}
973
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800974bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -0700975 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -0700976 // If we start or stop drawing blur then the layer's visibility state may change so increment
977 // the magic sequence number.
978 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
979 mDrawingState.sequence++;
980 }
Robert Carr6a160312021-05-17 12:08:20 -0700981 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
982 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800983 setTransactionFlags(eTransactionNeeded);
984 return true;
985}
Marissa Wall61c58622018-07-18 10:12:20 -0700986
Mathias Agopian13127d82013-03-05 17:47:11 -0800987bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +0000988 mDrawingState.sequence++;
989 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -0700990 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800991 setTransactionFlags(eTransactionNeeded);
992 return true;
993}
Ana Krulecc84d09b2019-11-02 23:10:29 +0100994
Lucas Dupinc3800b82020-10-02 16:24:48 -0700995bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -0700996 // If we start or stop drawing blur then the layer's visibility state may change so increment
997 // the magic sequence number.
998 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
999 mDrawingState.sequence++;
1000 }
Robert Carr6a160312021-05-17 12:08:20 -07001001 mDrawingState.blurRegions = blurRegions;
1002 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001003 setTransactionFlags(eTransactionNeeded);
1004 return true;
1005}
1006
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001007bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001008 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1009 if (mDrawingState.flags == newFlags) return false;
1010 mDrawingState.sequence++;
1011 mDrawingState.flags = newFlags;
1012 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001013 setTransactionFlags(eTransactionNeeded);
1014 return true;
1015}
Robert Carr99e27f02016-06-16 15:18:02 -07001016
chaviw25714502021-02-11 10:01:08 -08001017bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001018 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001019 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001020 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001021
Robert Carr6a160312021-05-17 12:08:20 -07001022 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001023 setTransactionFlags(eTransactionNeeded);
1024 return true;
1025}
Robert Carr8d5227b2017-03-16 15:41:03 -07001026
Evan Roskyef876c92019-01-25 17:46:06 -08001027bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001028 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1029 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001030 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001031 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001032}
1033
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001034bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001035 if (mDrawingState.layerStack == layerStack) return false;
1036 mDrawingState.sequence++;
1037 mDrawingState.layerStack = layerStack;
1038 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001039 setTransactionFlags(eTransactionNeeded);
1040 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001041}
1042
Peiyong Linc502cb72019-03-01 15:00:23 -08001043bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001044 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001045 return false;
1046 }
Robert Carr6a160312021-05-17 12:08:20 -07001047 mDrawingState.sequence++;
1048 mDrawingState.colorSpaceAgnostic = agnostic;
1049 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001050 setTransactionFlags(eTransactionNeeded);
1051 return true;
1052}
1053
Sally Qi81d95e62022-03-21 19:41:33 -07001054bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1055 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1056
1057 mDrawingState.sequence++;
1058 mDrawingState.dimmingEnabled = dimmingEnabled;
1059 mDrawingState.modified = true;
1060 setTransactionFlags(eTransactionNeeded);
1061 return true;
1062}
1063
Ana Krulecc84d09b2019-11-02 23:10:29 +01001064bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001065 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1066 mDrawingState.frameRateSelectionPriority = priority;
1067 mDrawingState.sequence++;
1068 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001069 setTransactionFlags(eTransactionNeeded);
1070 return true;
1071}
1072
1073int32_t Layer::getFrameRateSelectionPriority() const {
1074 // Check if layer has priority set.
1075 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1076 return mDrawingState.frameRateSelectionPriority;
1077 }
1078 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001079 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001080 if (parent != nullptr) {
1081 return parent->getFrameRateSelectionPriority();
1082 }
1083
1084 return Layer::PRIORITY_UNSET;
1085}
1086
Andy Labrada096227e2022-06-15 16:58:11 +00001087bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1088 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1089 mDrawingState.defaultFrameRateCompatibility = compatibility;
1090 mDrawingState.modified = true;
1091 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1092 setTransactionFlags(eTransactionNeeded);
1093 return true;
1094}
1095
1096scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1097 return mDrawingState.defaultFrameRateCompatibility;
1098}
1099
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001100bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1101 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1102};
1103
Vishnu Nair73908d12022-10-24 21:46:42 -07001104ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1105 bool useDrawing = state == LayerVector::StateSet::Drawing;
1106 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1107 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001108 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001109 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001110 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001111}
1112
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001113bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001114 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001115 return false;
1116 }
1117
Robert Carr6a160312021-05-17 12:08:20 -07001118 mDrawingState.sequence++;
1119 mDrawingState.shadowRadius = shadowRadius;
1120 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001121 setTransactionFlags(eTransactionNeeded);
1122 return true;
1123}
1124
Vishnu Nair6213bd92020-05-08 17:42:25 -07001125bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001126 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001127 return false;
1128 }
1129
Robert Carr6a160312021-05-17 12:08:20 -07001130 mDrawingState.sequence++;
1131 mDrawingState.fixedTransformHint = fixedTransformHint;
1132 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001133 setTransactionFlags(eTransactionNeeded);
1134 return true;
1135}
1136
John Reckcdb4ed72021-02-04 13:39:33 -05001137bool Layer::setStretchEffect(const StretchEffect& effect) {
1138 StretchEffect temp = effect;
1139 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001140 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001141 return false;
1142 }
Robert Carr6a160312021-05-17 12:08:20 -07001143 mDrawingState.sequence++;
1144 mDrawingState.stretchEffect = temp;
1145 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001146 setTransactionFlags(eTransactionNeeded);
1147 return true;
1148}
1149
John Reckc00c6692021-02-16 11:37:33 -05001150StretchEffect Layer::getStretchEffect() const {
1151 if (mDrawingState.stretchEffect.hasEffect()) {
1152 return mDrawingState.stretchEffect;
1153 }
1154
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001155 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001156 if (parent != nullptr) {
1157 auto effect = parent->getStretchEffect();
1158 if (effect.hasEffect()) {
1159 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1160 return effect;
1161 }
1162 }
1163 return StretchEffect{};
1164}
1165
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001166bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1167 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001168 return false;
1169 }
1170 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001171 mBorderWidth = width;
1172 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001173 return true;
1174}
1175
1176bool Layer::isBorderEnabled() {
1177 return mBorderEnabled;
1178}
1179
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001180float Layer::getBorderWidth() {
1181 return mBorderWidth;
1182}
1183
1184const half4& Layer::getBorderColor() {
1185 return mBorderColor;
1186}
1187
Ady Abrahama850c182021-08-04 13:04:37 -07001188bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1189 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1190 const auto frameRate = [&] {
1191 if (mDrawingState.frameRate.rate.isValid() ||
1192 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1193 return mDrawingState.frameRate;
1194 }
1195
1196 return parentFrameRate;
1197 }();
1198
1199 *transactionNeeded |= setFrameRateForLayerTree(frameRate);
1200
1201 // The frame rate is propagated to the children
1202 bool childrenHaveFrameRate = false;
1203 for (const sp<Layer>& child : mCurrentChildren) {
1204 childrenHaveFrameRate |=
1205 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1206 }
1207
1208 // If we don't have a valid frame rate, but the children do, we set this
1209 // layer as NoVote to allow the children to control the refresh rate
1210 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1211 childrenHaveFrameRate) {
1212 *transactionNeeded |=
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001213 setFrameRateForLayerTree(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001214 }
1215
1216 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1217 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001218 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001219 const auto layerVotedWithDefaultCompatibility =
1220 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1221 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1222 const auto layerVotedWithExactCompatibility =
1223 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1224 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1225 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1226}
1227
Ady Abraham60e42ea2020-03-09 19:17:31 -07001228void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001229 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001230 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001231 while (auto parent = layer->getParent()) {
1232 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001233 }
Ady Abrahama850c182021-08-04 13:04:37 -07001234 return layer;
1235 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001236
Ady Abraham60e42ea2020-03-09 19:17:31 -07001237 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001238 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001239
Ady Abrahama850c182021-08-04 13:04:37 -07001240 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001241 if (transactionNeeded) {
1242 mFlinger->setTransactionFlags(eTraversalNeeded);
1243 }
1244}
1245
Ady Abraham71c437d2020-01-31 15:56:57 -08001246bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001247 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001248 return false;
1249 }
1250
Robert Carr6a160312021-05-17 12:08:20 -07001251 mDrawingState.sequence++;
1252 mDrawingState.frameRate = frameRate;
1253 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001254
1255 updateTreeHasFrameRateVote();
1256
Steven Thomas3172e202020-01-06 19:25:30 -08001257 setTransactionFlags(eTransactionNeeded);
1258 return true;
1259}
1260
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001261void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1262 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001263 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001264
1265 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1266 // there are two transactions with the same token, the first one without a buffer and the
1267 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1268 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001269 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1270 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001271 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001272 mDrawingState.bufferSurfaceFrameTX = it->second;
1273 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1274 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1275 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001276 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001277 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001278 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1279 }
1280}
1281
1282void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1283 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001284 mDrawingState.frameTimelineInfo = info;
1285 mDrawingState.postTime = postTime;
1286 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001287 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001288
Robert Carr6a160312021-05-17 12:08:20 -07001289 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001290 bufferSurfaceFrameTX != nullptr) {
1291 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1292 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1293 // being used for BufferSurfaceFrame, don't create a new one.
1294 return;
1295 }
1296 }
1297 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1298 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1299 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001300 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1301 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001302 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001303 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001304 } else {
1305 if (it->second->getPresentState() == PresentState::Presented) {
1306 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1307 // have been from previous vsync.
1308 it->second = createSurfaceFrameForTransaction(info, postTime);
1309 }
1310 }
1311}
1312
1313void Layer::addSurfaceFrameDroppedForBuffer(
1314 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001315 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001316 surfaceFrame->setPresentState(PresentState::Dropped);
1317 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1318}
1319
1320void Layer::addSurfaceFramePresentedForBuffer(
1321 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1322 nsecs_t currentLatchTime) {
1323 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1324 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1325 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1326 mLastLatchTime = currentLatchTime;
1327}
1328
1329std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1330 const FrameTimelineInfo& info, nsecs_t postTime) {
1331 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001332 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1333 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001334 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001335 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001336 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001337 // For Transactions, the post time is considered to be both queue and acquire fence time.
1338 surfaceFrame->setActualQueueTime(postTime);
1339 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001340 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1341 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001342 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001343 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001344 onSurfaceFrameCreated(surfaceFrame);
1345 return surfaceFrame;
1346}
1347
1348std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1349 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1350 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001351 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001352 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001353 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001354 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001355 // For buffers, acquire fence time will set during latch.
1356 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001357 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1358 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001359 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001360 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001361 onSurfaceFrameCreated(surfaceFrame);
1362 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001363}
1364
Ady Abrahama850c182021-08-04 13:04:37 -07001365bool Layer::setFrameRateForLayerTree(FrameRate frameRate) {
1366 if (mDrawingState.frameRateForLayerTree == frameRate) {
1367 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001368 }
1369
Ady Abrahama850c182021-08-04 13:04:37 -07001370 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001371
Ady Abrahama850c182021-08-04 13:04:37 -07001372 // TODO(b/195668952): we probably don't need to dirty visible regions here
1373 // or even store frameRateForLayerTree in mDrawingState
1374 mDrawingState.sequence++;
1375 mDrawingState.modified = true;
1376 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001377
Dominik Laskowski068173d2021-08-11 17:22:59 -07001378 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
1379 mFlinger->mScheduler->recordLayerHistory(this, systemTime(), LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001380
1381 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001382}
1383
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001384Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1385 return getDrawingState().frameRateForLayerTree;
1386}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001387
Robert Carr1f0a16a2016-10-24 16:27:39 -07001388bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001389 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001390 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001391 if (parent != nullptr && parent->isHiddenByPolicy()) {
1392 return true;
1393 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001394 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1395 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1396 if (zOrderRelativeOf != nullptr) {
1397 if (zOrderRelativeOf->isHiddenByPolicy()) {
1398 return true;
1399 }
1400 }
1401 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001402 if (CC_UNLIKELY(!isTransformValid())) {
1403 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1404 return true;
1405 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001406 return s.flags & layer_state_t::eLayerHidden;
1407}
1408
David Sodman41fdfc92017-11-06 16:09:56 -08001409uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001410 // TODO: should we do something special if mSecure is set?
1411 if (mProtectedByApp) {
1412 // need a hardware-protected path to external video sink
1413 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001414 }
Riley Andrews03414a12014-07-01 14:22:59 -07001415 if (mPotentialCursor) {
1416 usage |= GraphicBuffer::USAGE_CURSOR;
1417 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001418 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001419 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001420}
1421
Vishnu Nair71fcf912022-10-18 09:14:20 -07001422void Layer::skipReportingTransformHint() {
1423 mSkipReportingTransformHint = true;
1424}
1425
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001426void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1427 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1428 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001429 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001430
Vishnu Nair6213bd92020-05-08 17:42:25 -07001431 setTransformHint(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001432}
1433
Mathias Agopian13127d82013-03-05 17:47:11 -08001434// ----------------------------------------------------------------------------
1435// debugging
1436// ----------------------------------------------------------------------------
1437
Marissa Wall61c58622018-07-18 10:12:20 -07001438// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001439gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001440 using namespace std::string_literals;
1441
Huihong Luo05539a12022-02-23 10:29:40 -08001442 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001443 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001444 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001445 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001446 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001447 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001448
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001449 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001450 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001451 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001452 info.mX = ds.transform.tx();
1453 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001454 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001455 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001456 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001457 info.mFlags = ds.flags;
1458 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001459 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001460 info.mMatrix[0][0] = ds.transform[0][0];
1461 info.mMatrix[0][1] = ds.transform[0][1];
1462 info.mMatrix[1][0] = ds.transform[1][0];
1463 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001464 {
chaviwd62d3062019-09-04 14:48:02 -07001465 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001466 if (buffer != 0) {
1467 info.mActiveBufferWidth = buffer->getWidth();
1468 info.mActiveBufferHeight = buffer->getHeight();
1469 info.mActiveBufferStride = buffer->getStride();
1470 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001471 } else {
1472 info.mActiveBufferWidth = 0;
1473 info.mActiveBufferHeight = 0;
1474 info.mActiveBufferStride = 0;
1475 info.mActiveBufferFormat = 0;
1476 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001477 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001478 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001479 info.mIsOpaque = isOpaque(ds);
1480 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001481 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001482 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001483}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001484
Yiwei Zhang5434a782018-12-05 18:06:32 -08001485void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001486 result.append(kDumpTableRowLength, '-');
1487 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001488 result.append(" Layer name\n");
1489 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001490 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001491 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001492 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001493 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001494 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001495 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1496 result.append(kDumpTableRowLength, '-');
1497 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001498}
1499
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001500void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1501 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001502 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001503 return;
1504 }
1505
Yiwei Zhang5434a782018-12-05 18:06:32 -08001506 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001507 if (mName.length() > 77) {
1508 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001509 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001510 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001511 shortened.append(mName, mName.length() - 36);
1512 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001513 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001514 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001515 }
1516
Yiwei Zhang5434a782018-12-05 18:06:32 -08001517 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001518
Alec Mourib416efd2018-09-06 21:01:59 +00001519 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001520 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001521
Chia-I Wu1e043612018-03-01 09:45:09 -08001522 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001523 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001524 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001525 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001526 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001527 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001528 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001529 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1530 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001531 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001532 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001533 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001534 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001535 const auto frameRate = getFrameRateForLayerTree();
1536 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1537 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001538 ftl::enum_string(frameRate.type).c_str(),
1539 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001540 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001541 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001542 }
Dan Stozae22aec72016-08-01 13:20:59 -07001543
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001544 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1545 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1546
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001547 result.append(kDumpTableRowLength, '-');
1548 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001549}
Dan Stozae22aec72016-08-01 13:20:59 -07001550
Yiwei Zhang5434a782018-12-05 18:06:32 -08001551void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001552 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001553}
1554
Svetoslavd85084b2014-03-20 10:28:31 -07001555void Layer::clearFrameStats() {
1556 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001557}
1558
Jamie Gennis6547ff42013-07-16 20:12:42 -07001559void Layer::logFrameStats() {
1560 mFrameTracker.logAndResetStats(mName);
1561}
1562
Svetoslavd85084b2014-03-20 10:28:31 -07001563void Layer::getFrameStats(FrameStats* outStats) const {
1564 mFrameTracker.getStats(outStats);
1565}
1566
Vishnu Nair76554eb2022-12-09 03:38:36 +00001567void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1568 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
1569 StringAppendF(&result, "Layer %s%s pid:%d uid:%d\n", getName().c_str(), hasBuffer.c_str(),
Vishnu Naircb8be502022-10-12 19:03:23 +00001570 mOwnerPid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001571}
1572
Brian Anderson5ea5e592016-12-01 16:54:33 -08001573void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001574 const int32_t layerId = getSequence();
1575 mFlinger->mTimeStats->onDestroy(layerId);
1576 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001577}
1578
Chia-I Wu98f1c102017-05-30 14:54:08 -07001579size_t Layer::getChildrenCount() const {
1580 size_t count = 0;
1581 for (const sp<Layer>& child : mCurrentChildren) {
1582 count += 1 + child->getChildrenCount();
1583 }
1584 return count;
1585}
1586
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001587void Layer::setGameModeForTree(GameMode gameMode) {
1588 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001589 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1590 gameMode =
1591 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001592 }
1593 setGameMode(gameMode);
1594 for (const sp<Layer>& child : mCurrentChildren) {
1595 child->setGameModeForTree(gameMode);
1596 }
1597}
1598
Robert Carr1f0a16a2016-10-24 16:27:39 -07001599void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001600 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001601 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001602
Robert Carr1f0a16a2016-10-24 16:27:39 -07001603 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001604 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001605 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001606 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001607}
1608
1609ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001610 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001611 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001612
Robert Carr1323c952019-01-28 18:13:27 -08001613 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001614 const auto removeResult = mCurrentChildren.remove(layer);
1615
1616 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001617 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001618 layer->updateTreeHasFrameRateVote();
1619
1620 return removeResult;
1621}
1622
Robert Carr15eae092018-03-23 13:43:53 -07001623void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001624 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001625 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001626 const float parentShadowRadius =
1627 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001628 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001629 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001630 }
1631}
1632
chaviwf1961f72017-09-18 16:41:07 -07001633bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001634 sp<Layer> newParent;
1635 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001636 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001637 if (newParent == nullptr) {
1638 ALOGE("Unable to promote Layer handle");
1639 return false;
1640 }
1641 if (newParent == this) {
1642 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1643 return false;
1644 }
1645 }
1646
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001647 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001648 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001649 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001650 }
1651
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001652 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001653 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001654 if (!newParent->isRemovedFromCurrentState()) {
1655 addToCurrentState();
1656 } else {
1657 onRemovedFromCurrentState();
1658 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001659 } else {
1660 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001661 }
1662
chaviw06178942017-07-27 10:25:59 -07001663 return true;
1664}
1665
Peiyong Lind3788632018-09-18 16:01:31 -07001666bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001667 static const mat4 identityMatrix = mat4();
1668
Robert Carr6a160312021-05-17 12:08:20 -07001669 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001670 return false;
1671 }
Robert Carr6a160312021-05-17 12:08:20 -07001672 ++mDrawingState.sequence;
1673 mDrawingState.colorTransform = matrix;
1674 mDrawingState.hasColorTransform = matrix != identityMatrix;
1675 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001676 setTransactionFlags(eTransactionNeeded);
1677 return true;
1678}
1679
chaviwf66724d2018-11-28 16:35:21 -08001680mat4 Layer::getColorTransform() const {
1681 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001682 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001683 colorTransform = parent->getColorTransform() * colorTransform;
1684 }
1685 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001686}
1687
1688bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001689 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001690 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001691 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1692 }
1693 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001694}
1695
Chia-I Wu11481472018-05-04 10:43:19 -07001696bool Layer::isLegacyDataSpace() const {
1697 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001698 return !(getDataSpace() &
1699 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1700 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001701}
1702
Robert Carr1f0a16a2016-10-24 16:27:39 -07001703void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001704 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001705}
1706
Robert Carr6a160312021-05-17 12:08:20 -07001707int32_t Layer::getZ(LayerVector::StateSet) const {
1708 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001709}
1710
Robert Carr1c5481e2019-07-01 14:42:27 -07001711bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001712 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001713 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001714 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001715}
1716
David Sodman41fdfc92017-11-06 16:09:56 -08001717__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001718 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001719 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1720 "makeTraversalList received invalid stateSet");
1721 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1722 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001723 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001724
Robert Carr29abff82017-12-04 13:51:20 -08001725 if (state.zOrderRelatives.size() == 0) {
1726 *outSkipRelativeZUsers = true;
1727 return children;
1728 }
1729
chaviwfd462612018-05-31 16:11:27 -07001730 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001731 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001732 sp<Layer> strongRelative = weakRelative.promote();
1733 if (strongRelative != nullptr) {
1734 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001735 }
1736 }
1737
Dan Stoza412903f2017-04-27 13:42:17 -07001738 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001739 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001740 continue;
1741 }
Robert Carrdb66e622017-04-10 16:55:57 -07001742 traverse.add(child);
1743 }
1744
1745 return traverse;
1746}
1747
Robert Carr1f0a16a2016-10-24 16:27:39 -07001748/**
Robert Carrdb66e622017-04-10 16:55:57 -07001749 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001750 */
Dan Stoza412903f2017-04-27 13:42:17 -07001751void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001752 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1753 // produce a new list for traversing, including our relatives, and not including our children
1754 // who are relatives of another surface. In the case that there are no relative Z,
1755 // makeTraversalList returns our children directly to avoid significant overhead.
1756 // However in this case we need to take the responsibility for filtering children which
1757 // are relatives of another surface here.
1758 bool skipRelativeZUsers = false;
1759 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001760
Robert Carr1f0a16a2016-10-24 16:27:39 -07001761 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001762 for (; i < list.size(); i++) {
1763 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001764 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1765 continue;
1766 }
1767
chaviw301b1d82019-11-06 13:15:09 -08001768 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001769 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001770 }
Dan Stoza412903f2017-04-27 13:42:17 -07001771 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001772 }
Robert Carr29abff82017-12-04 13:51:20 -08001773
Dan Stoza412903f2017-04-27 13:42:17 -07001774 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001775 for (; i < list.size(); i++) {
1776 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001777
Robert Carr29abff82017-12-04 13:51:20 -08001778 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1779 continue;
1780 }
Dan Stoza412903f2017-04-27 13:42:17 -07001781 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001782 }
1783}
1784
1785/**
Robert Carrdb66e622017-04-10 16:55:57 -07001786 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001787 */
Dan Stoza412903f2017-04-27 13:42:17 -07001788void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1789 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001790 // See traverseInZOrder for documentation.
1791 bool skipRelativeZUsers = false;
1792 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001793
Robert Carr1f0a16a2016-10-24 16:27:39 -07001794 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001795 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001796 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001797
1798 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1799 continue;
1800 }
1801
chaviw301b1d82019-11-06 13:15:09 -08001802 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001803 break;
1804 }
Dan Stoza412903f2017-04-27 13:42:17 -07001805 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001806 }
Dan Stoza412903f2017-04-27 13:42:17 -07001807 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001808 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001809 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001810
1811 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1812 continue;
1813 }
1814
Dan Stoza412903f2017-04-27 13:42:17 -07001815 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001816 }
1817}
1818
Edgar Arriaga844fa672020-01-16 14:21:42 -08001819void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1820 visitor(this);
1821 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001822 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001823 for (const sp<Layer>& child : children) {
1824 child->traverse(state, visitor);
1825 }
1826}
1827
chaviw4b129c22018-04-09 16:19:43 -07001828LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1829 const std::vector<Layer*>& layersInTree) {
1830 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1831 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001832 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1833 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001834 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001835
chaviwfd462612018-05-31 16:11:27 -07001836 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001837 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1838 sp<Layer> strongRelative = weakRelative.promote();
1839 // Only add relative layers that are also descendents of the top most parent of the tree.
1840 // If a relative layer is not a descendent, then it should be ignored.
1841 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1842 traverse.add(strongRelative);
1843 }
1844 }
1845
1846 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001847 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001848 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1849 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1850 // the child here since it won't be added later as a relative.
1851 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1852 childState.zOrderRelativeOf.promote().get())) {
1853 continue;
1854 }
1855 traverse.add(child);
1856 }
1857
1858 return traverse;
1859}
1860
1861void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1862 LayerVector::StateSet stateSet,
1863 const LayerVector::Visitor& visitor) {
1864 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001865
1866 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001867 for (; i < list.size(); i++) {
1868 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001869 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001870 break;
1871 }
chaviw4b129c22018-04-09 16:19:43 -07001872 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001873 }
chaviw4b129c22018-04-09 16:19:43 -07001874
chaviwa76b2712017-09-20 12:02:26 -07001875 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001876 for (; i < list.size(); i++) {
1877 const auto& relative = list[i];
1878 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001879 }
1880}
1881
chaviw4b129c22018-04-09 16:19:43 -07001882std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1883 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1884 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1885
1886 std::vector<Layer*> layersInTree = {this};
1887 for (size_t i = 0; i < children.size(); i++) {
1888 const auto& child = children[i];
1889 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1890 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1891 }
1892
1893 return layersInTree;
1894}
1895
1896void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1897 const LayerVector::Visitor& visitor) {
1898 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1899 std::sort(layersInTree.begin(), layersInTree.end());
1900 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1901}
1902
Peiyong Linefefaac2018-08-17 12:27:51 -07001903ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001904 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001905}
1906
Garfield Tan2c1782c2022-02-16 15:25:05 -08001907bool Layer::isTransformValid() const {
1908 float transformDet = getTransform().det();
1909 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1910}
1911
chaviw13fdc492017-06-27 12:40:18 -07001912half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001913 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001914
chaviw13fdc492017-06-27 12:40:18 -07001915 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1916 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07001917}
Robert Carr6452f122017-03-21 10:41:29 -07001918
Vishnu Nair6213bd92020-05-08 17:42:25 -07001919ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07001920 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001921 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
1922 return fixedTransformHint;
1923 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001924 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07001925 if (!p) return fixedTransformHint;
1926 return p->getFixedTransformHint();
1927}
1928
chaviw13fdc492017-06-27 12:40:18 -07001929half4 Layer::getColor() const {
1930 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001931 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07001932}
Robert Carr6452f122017-03-21 10:41:29 -07001933
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001934int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00001935 if (getDrawingState().backgroundBlurRadius == 0) {
1936 return 0;
1937 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01001938
Vishnu Nair29810f72022-07-01 16:38:41 +00001939 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01001940 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1941 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001942}
1943
Galia Peychevae0acf382021-04-12 21:22:34 +02001944const std::vector<BlurRegion> Layer::getBlurRegions() const {
1945 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02001946 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02001947 for (auto& region : regionsCopy) {
1948 region.alpha = region.alpha * layerAlpha;
1949 }
1950 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001951}
1952
Vishnu Naire14c6b32022-08-06 04:20:15 +00001953RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001954 // Get parent settings
1955 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001956 const auto& parent = mDrawingParent.promote();
1957 if (parent != nullptr) {
1958 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001959 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001960 ui::Transform t = getActiveTransform(getDrawingState());
1961 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001962 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001963 parentSettings.radius.x *= t.getScaleX();
1964 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001965 }
1966 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001967
1968 // Get layer settings
1969 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001970 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001971 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001972 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001973
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001974 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001975 // If the parent and the layer have rounded corner settings, use the parent settings if the
1976 // parent crop is entirely inside the layer crop.
1977 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
1978 if (parentSettings.cropRect.left > layerCropRect.left &&
1979 parentSettings.cropRect.top > layerCropRect.top &&
1980 parentSettings.cropRect.right < layerCropRect.right &&
1981 parentSettings.cropRect.bottom < layerCropRect.bottom) {
1982 return parentSettings;
1983 } else {
1984 return layerSettings;
1985 }
Vishnu Nairb1845592021-10-07 12:17:57 -07001986 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001987 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001988 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001989 return parentSettings;
1990 }
1991 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001992}
1993
Robert Carr88b85e12022-03-21 15:47:35 -07001994bool Layer::findInHierarchy(const sp<Layer>& l) {
1995 if (l == this) {
1996 return true;
1997 }
1998 for (auto& child : mDrawingChildren) {
1999 if (child->findInHierarchy(l)) {
2000 return true;
2001 }
2002 }
2003 return false;
2004}
2005
Robert Carr1f0a16a2016-10-24 16:27:39 -07002006void Layer::commitChildList() {
2007 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2008 const auto& child = mCurrentChildren[i];
2009 child->commitChildList();
2010 }
2011 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002012 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002013 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2014 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2015 if (zOrderRelativeOf == nullptr) return;
2016 if (findInHierarchy(zOrderRelativeOf)) {
2017 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2018 zOrderRelativeOf->mName.c_str());
2019 ALOGE("Severing rel Z loop, potentially dangerous");
2020 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002021 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002022 }
2023 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002024}
2025
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002026
chaviw3277faf2021-05-19 16:45:23 -05002027void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002028 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002029 mDrawingState.touchableRegionCrop =
2030 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002031 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002032 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002033 setTransactionFlags(eTransactionNeeded);
2034}
2035
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002036LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002037 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002038 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002039 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2040
Vishnu Nair00b90132021-11-05 14:03:40 -07002041 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002042 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2043
Vishnu Nair60db8c02020-04-02 11:55:16 -07002044 // Only populate for the primary display.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002045 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -05002046 const auto compositionType = getCompositionType(*display);
Vishnu Nair60db8c02020-04-02 11:55:16 -07002047 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002048 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2049 [&]() { return layerProto->mutable_visible_region(); });
Vishnu Nair60db8c02020-04-02 11:55:16 -07002050 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08002051 }
2052
chaviw08f3cb22020-01-13 13:17:21 -08002053 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002054 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002055 }
chaviw6d89e2d2020-01-14 14:42:01 -08002056
2057 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002058}
2059
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002060void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002061 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002062 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002063 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002064 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002065 [&]() { return layerInfo->mutable_active_buffer(); });
2066 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2067 layerInfo->mutable_buffer_transform());
2068 }
2069 layerInfo->set_invalidate(contentDirty);
2070 layerInfo->set_is_protected(isProtected());
2071 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2072 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002073 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002074 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002075 layerInfo->set_corner_radius(
2076 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002077 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2078 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2079 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2080 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2081 [&]() { return layerInfo->mutable_position(); });
2082 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002083 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2084 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002085
Vishnu Nair00b90132021-11-05 14:03:40 -07002086 if (hasColorTransform()) {
2087 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002088 }
2089
Vishnu Nair60db8c02020-04-02 11:55:16 -07002090 LayerProtoHelper::writeToProto(mSourceBounds,
2091 [&]() { return layerInfo->mutable_source_bounds(); });
2092 LayerProtoHelper::writeToProto(mScreenBounds,
2093 [&]() { return layerInfo->mutable_screen_bounds(); });
2094 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2095 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2096 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002097}
2098
2099void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002100 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002101 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2102 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002103 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002104
chaviw766c9c52021-02-10 17:36:47 -08002105 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002106
Vishnu Nair00b90132021-11-05 14:03:40 -07002107 layerInfo->set_id(sequence);
2108 layerInfo->set_name(getName().c_str());
2109 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002110
Vishnu Nair00b90132021-11-05 14:03:40 -07002111 for (const auto& child : children) {
2112 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002113 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002114
Vishnu Nair00b90132021-11-05 14:03:40 -07002115 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2116 sp<Layer> strongRelative = weakRelative.promote();
2117 if (strongRelative != nullptr) {
2118 layerInfo->add_relatives(strongRelative->sequence);
2119 }
2120 }
2121
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002122 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002123 [&]() { return layerInfo->mutable_transparent_region(); });
2124
2125 layerInfo->set_layer_stack(getLayerStack().id);
2126 layerInfo->set_z(state.z);
2127
2128 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2129 return layerInfo->mutable_requested_position();
2130 });
2131
Vishnu Nair00b90132021-11-05 14:03:40 -07002132 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2133
2134 layerInfo->set_is_opaque(isOpaque(state));
2135
2136 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2137 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2138 LayerProtoHelper::writeToProto(state.color,
2139 [&]() { return layerInfo->mutable_requested_color(); });
2140 layerInfo->set_flags(state.flags);
2141
2142 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2143 layerInfo->mutable_requested_transform());
2144
2145 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2146 if (parent != nullptr) {
2147 layerInfo->set_parent(parent->sequence);
2148 } else {
2149 layerInfo->set_parent(-1);
2150 }
2151
2152 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2153 if (zOrderRelativeOf != nullptr) {
2154 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2155 } else {
2156 layerInfo->set_z_order_relative_of(-1);
2157 }
2158
2159 layerInfo->set_is_relative_of(state.isRelativeOf);
2160
2161 layerInfo->set_owner_uid(mOwnerUid);
2162
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002163 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002164 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002165 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002166 info = fillInputInfo(
2167 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002168 } else {
2169 info = state.inputInfo;
2170 }
2171
2172 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002173 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002174 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002175
Vishnu Nair00b90132021-11-05 14:03:40 -07002176 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002177 auto protoMap = layerInfo->mutable_metadata();
2178 for (const auto& entry : state.metadata.mMap) {
2179 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2180 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002181 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002182
2183 LayerProtoHelper::writeToProto(state.destinationFrame,
2184 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002185}
2186
Robert Carr2e102c92018-10-23 12:11:15 -07002187bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002188 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002189}
2190
Prabir Pradhan33da9462022-06-14 14:55:57 +00002191// Applies the given transform to the region, while protecting against overflows caused by any
2192// offsets. If applying the offset in the transform to any of the Rects in the region would result
2193// in an overflow, they are not added to the output Region.
2194static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2195 const std::string& debugWindowName) {
2196 // Round the translation using the same rounding strategy used by ui::Transform.
2197 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2198 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2199
2200 ui::Transform transformWithoutOffset = t;
2201 transformWithoutOffset.set(0.f, 0.f);
2202
2203 const Region transformed = transformWithoutOffset.transform(r);
2204
2205 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2206 Region ret;
2207 for (const auto& rect : transformed) {
2208 Rect newRect;
2209 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2210 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2211 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2212 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2213 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2214 debugWindowName.c_str());
2215 continue;
2216 }
2217 ret.orSelf(newRect);
2218 }
2219 return ret;
2220}
2221
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002222void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
2223 Rect tmpBounds = getInputBounds();
2224 if (!tmpBounds.isValid()) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002225 info.touchableRegion.clear();
2226 // A layer could have invalid input bounds and still expect to receive touch input if it has
2227 // replaceTouchableRegionWithCrop. For that case, the input transform needs to be calculated
2228 // correctly to determine the coordinate space for input events. Use an empty rect so that
2229 // the layer will receive input in its own layer space.
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002230 tmpBounds = Rect::EMPTY_RECT;
chaviw7e72caf2020-12-02 16:50:43 -08002231 }
2232
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002233 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2234 // frame and transform used for the layer, which determines the bounds and the coordinate space
2235 // within which the layer will receive input.
2236 //
2237 // The coordinate space within which each of the bounds are specified is explicitly documented
2238 // in the variable name. For example "inputBoundsInLayer" is specified in layer space. A
2239 // Transform converts one coordinate space to another, which is apparent in its naming. For
2240 // example, "layerToDisplay" transforms layer space to display space.
2241 //
2242 // Coordinate space definitions:
2243 // - display: The display device's coordinate space. Correlates to pixels on the display.
2244 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2245 // - layer: The coordinate space of this layer.
2246 // - input: The coordinate space in which this layer will receive input events. This could be
2247 // different than layer space if a surfaceInset is used, which changes the origin
2248 // of the input space.
2249 const FloatRect inputBoundsInLayer = tmpBounds.toFloatRect();
chaviw7e72caf2020-12-02 16:50:43 -08002250
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002251 // Clamp surface inset to the input bounds.
2252 const auto surfaceInset = static_cast<float>(info.surfaceInset);
2253 const float xSurfaceInset =
2254 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getWidth() / 2.f));
2255 const float ySurfaceInset =
2256 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getHeight() / 2.f));
chaviw1ff3d1e2020-07-01 15:53:47 -07002257
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002258 // Apply the insets to the input bounds.
2259 const FloatRect insetBoundsInLayer(inputBoundsInLayer.left + xSurfaceInset,
2260 inputBoundsInLayer.top + ySurfaceInset,
2261 inputBoundsInLayer.right - xSurfaceInset,
2262 inputBoundsInLayer.bottom - ySurfaceInset);
Ady Abraham282f1d72019-07-24 18:05:56 -07002263
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002264 // Crop the input bounds to ensure it is within the parent's bounds.
2265 const FloatRect croppedInsetBoundsInLayer = mBounds.intersect(insetBoundsInLayer);
Ady Abraham282f1d72019-07-24 18:05:56 -07002266
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002267 const ui::Transform layerToScreen = getInputTransform();
2268 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
Vishnu Nair8033a492018-12-05 07:27:23 -08002269
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002270 const Rect roundedFrameInDisplay{layerToDisplay.transform(croppedInsetBoundsInLayer)};
2271 info.frameLeft = roundedFrameInDisplay.left;
2272 info.frameTop = roundedFrameInDisplay.top;
2273 info.frameRight = roundedFrameInDisplay.right;
2274 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002275
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002276 ui::Transform inputToLayer;
2277 inputToLayer.set(insetBoundsInLayer.left, insetBoundsInLayer.top);
2278 const ui::Transform inputToDisplay = layerToDisplay * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002279
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002280 // InputDispatcher expects a display-to-input transform.
2281 info.transform = inputToDisplay.inverse();
2282
2283 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002284 info.touchableRegion =
2285 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002286}
2287
chaviw3277faf2021-05-19 16:45:23 -05002288void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002289 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002290 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002291 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002292 }
2293 if (p != nullptr) {
2294 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2295 }
2296}
2297
Vishnu Naira066d902021-09-13 18:40:17 -07002298gui::DropInputMode Layer::getDropInputMode() const {
2299 gui::DropInputMode mode = mDrawingState.dropInputMode;
2300 if (mode == gui::DropInputMode::ALL) {
2301 return mode;
2302 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002303 sp<Layer> parent = mDrawingParent.promote();
2304 if (parent) {
2305 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002306 if (parentMode != gui::DropInputMode::NONE) {
2307 return parentMode;
2308 }
2309 }
2310 return mode;
2311}
2312
2313void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002314 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002315 return;
2316 }
2317
2318 // Check if we need to drop input unconditionally
2319 gui::DropInputMode dropInputMode = getDropInputMode();
2320 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002321 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002322 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2323 return;
2324 }
2325
2326 // Check if we need to check if the window is obscured by parent
2327 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2328 return;
2329 }
2330
2331 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002332 sp<Layer> parent = mDrawingParent.promote();
2333 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002334 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002335 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2336 static_cast<float>(getAlpha()));
2337 }
2338
2339 // Check if the parent has cropped the buffer
2340 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2341 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002342 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002343 return;
2344 }
2345
2346 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2347 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2348 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2349 // match then the layer has not been cropped by its parents.
2350 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2351 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2352
2353 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002354 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002355 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2356 getDebugName());
2357 } else {
2358 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2359 // input if the window is obscured. This check should be done in surfaceflinger but the
2360 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2361 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002362 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002363 }
2364}
2365
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002366WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002367 if (!hasInputInfo()) {
2368 mDrawingState.inputInfo.name = getName();
2369 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2370 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002371 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002372 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002373 }
2374
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002375 const ui::Transform& displayTransform =
2376 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2377
chaviw3277faf2021-05-19 16:45:23 -05002378 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002379 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002380 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002381
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002382 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002383
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002384 if (displayArgs.transform == nullptr) {
2385 // Do not let the window receive touches if it is not associated with a valid display
2386 // transform. We still allow the window to receive keys and prevent ANRs.
2387 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2388 }
2389
Robert Carr5dc426e2020-06-10 14:29:14 -07002390 // For compatibility reasons we let layers which can receive input
2391 // receive input before they have actually submitted a buffer. Because
2392 // of this we use canReceiveInput instead of isVisible to check the
2393 // policy-visibility, ignoring the buffer state. However for layers with
2394 // hasInputInfo()==false we can use the real visibility state.
2395 // We are just using these layers for occlusion detection in
2396 // InputDispatcher, and obviously if they aren't visible they can't occlude
2397 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002398 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2399 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2400
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002401 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002402 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002403 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002404
Vishnu Nair16a938f2021-09-24 07:14:54 -07002405 // If the window will be blacked out on a display because the display does not have the secure
2406 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002407 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002408 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002409 }
2410
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002411 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2412 if (info.replaceTouchableRegionWithCrop) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002413 const Rect bounds(cropLayer ? cropLayer->mScreenBounds : mScreenBounds);
2414 info.touchableRegion = Region(displayTransform.transform(bounds));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002415 } else if (cropLayer != nullptr) {
[1;3C2b9fc252021-02-04 16:16:50 -08002416 info.touchableRegion = info.touchableRegion.intersect(
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002417 displayTransform.transform(Rect{cropLayer->mScreenBounds}));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002418 }
2419
Winson Chunga30f7c92021-06-29 15:42:56 -07002420 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2421 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002422 if (isTrustedOverlay()) {
2423 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2424 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002425
chaviwaf87b3e2019-10-01 16:59:28 -07002426 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2427 // touches from going outside the cloned area.
2428 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002429 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002430 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2431 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002432 info.touchableRegion = info.touchableRegion.intersect(rect);
2433 }
2434 }
2435
Robert Carr720e5062018-07-30 17:45:14 -07002436 return info;
2437}
2438
chaviwaf87b3e2019-10-01 16:59:28 -07002439sp<Layer> Layer::getClonedRoot() {
2440 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002441 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002442 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002443 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002444 return nullptr;
2445 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002446 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002447}
2448
Robert Carredd13602020-04-13 17:24:34 -07002449bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002450 return mDrawingState.inputInfo.token != nullptr ||
2451 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002452}
2453
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002454compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002455 const DisplayDevice* display) const {
2456 if (!display) return nullptr;
Lloyd Piquede196652020-01-22 17:29:58 -08002457 return display->getCompositionDisplay()->getOutputLayerForLayer(getCompositionEngineLayerFE());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002458}
2459
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002460Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2461 const auto outputLayer = findOutputLayerForDisplay(display);
2462 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002463}
2464
chaviwb4c6e582019-08-16 14:35:07 -07002465void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002466 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002467 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002468 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2469 mPotentialCursor = clonedFrom->mPotentialCursor;
2470 mProtectedByApp = clonedFrom->mProtectedByApp;
2471 updateCloneBufferInfo();
2472}
2473
2474void Layer::updateCloneBufferInfo() {
2475 if (!isClone() || !isClonedFromAlive()) {
2476 return;
2477 }
2478
2479 sp<Layer> clonedFrom = getClonedFrom();
2480 mBufferInfo = clonedFrom->mBufferInfo;
2481 mSidebandStream = clonedFrom->mSidebandStream;
2482 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2483 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2484 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2485
2486 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2487 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2488 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2489 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2490 // the cloned drawingState again.
2491 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2492 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2493 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2494 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2495
2496 cloneDrawingState(clonedFrom.get());
2497
2498 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2499 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2500 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2501 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002502}
chaviw74b03172019-08-19 11:09:03 -07002503
2504void Layer::updateMirrorInfo() {
2505 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2506 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2507 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2508 // that case, we want to delete the reference to the clone since we want it to get
2509 // destroyed. The root, this layer, will still be around since the client can continue
2510 // to hold a reference, but no cloned layers will be displayed.
2511 mClonedChild = nullptr;
2512 return;
2513 }
2514
2515 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2516 // If the real layer exists and is in current state, add the clone as a child of the root.
2517 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2518 // copied to drawingState for the root layer. So the clonedChild is always removed from
2519 // drawingState and then needs to be added back each traversal.
2520 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2521 addChildToDrawing(mClonedChild);
2522 }
2523
2524 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002525 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002526 mClonedChild->updateClonedRelatives(clonedLayersMap);
2527}
2528
2529void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2530 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2531 // to the clone. If the real layer is no longer alive, continue traversing the children
2532 // since we may be able to pull out other children that are still alive.
2533 if (isClonedFromAlive()) {
2534 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002535 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002536 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002537 }
2538
2539 // The clone layer may have children in drawingState since they may have been created and
2540 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2541 // that already exist, since we can just re-use them.
2542 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2543 // not updated in the regular traversal. They are skipped since the root will lose the
2544 // reference to them when it copies its currentChildren to drawing.
2545 for (sp<Layer>& child : mDrawingChildren) {
2546 child->updateClonedDrawingState(clonedLayersMap);
2547 }
2548}
2549
2550void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2551 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2552 mDrawingChildren.clear();
2553
2554 if (!isClonedFromAlive()) {
2555 return;
2556 }
2557
2558 sp<Layer> clonedFrom = getClonedFrom();
2559 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2560 if (child == mirrorRoot) {
2561 // This is to avoid cyclical mirroring.
2562 continue;
2563 }
2564 sp<Layer> clonedChild = clonedLayersMap[child];
2565 if (clonedChild == nullptr) {
2566 clonedChild = child->createClone();
2567 clonedLayersMap[child] = clonedChild;
2568 }
2569 addChildToDrawing(clonedChild);
2570 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2571 }
2572}
2573
chaviwaf87b3e2019-10-01 16:59:28 -07002574void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2575 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2576 if (cropLayer != nullptr) {
2577 if (clonedLayersMap.count(cropLayer) == 0) {
2578 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2579 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002580 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002581 } else {
2582 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2583 mDrawingState.touchableRegionCrop = clonedCropLayer;
2584 }
2585 }
2586 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2587 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002588 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002589}
2590
2591void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002592 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002593 mDrawingState.zOrderRelatives.clear();
2594
2595 if (!isClonedFromAlive()) {
2596 return;
2597 }
2598
chaviwaf87b3e2019-10-01 16:59:28 -07002599 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002600 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002601 const sp<Layer>& relative = relativeWeak.promote();
2602 if (clonedLayersMap.count(relative) > 0) {
2603 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002604 mDrawingState.zOrderRelatives.add(clonedRelative);
2605 }
2606 }
2607
2608 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2609 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2610 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2611 // still traverse the children, but the layer with the missing relativeOf will not be shown
2612 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002613 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2614 if (clonedLayersMap.count(relativeOf) > 0) {
2615 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002616 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2617 }
2618
chaviwaf87b3e2019-10-01 16:59:28 -07002619 updateClonedInputInfo(clonedLayersMap);
2620
chaviw74b03172019-08-19 11:09:03 -07002621 for (sp<Layer>& child : mDrawingChildren) {
2622 child->updateClonedRelatives(clonedLayersMap);
2623 }
2624}
2625
2626void Layer::addChildToDrawing(const sp<Layer>& layer) {
2627 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002628 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002629}
2630
Steven Thomas62a4cf82020-01-31 12:04:03 -08002631Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2632 switch (compatibility) {
2633 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2634 return FrameRateCompatibility::Default;
2635 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2636 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002637 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2638 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002639 case ANATIVEWINDOW_FRAME_RATE_MIN:
2640 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002641 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2642 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002643 default:
2644 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2645 return FrameRateCompatibility::Default;
2646 }
2647}
2648
Marin Shalamanovc5986772021-03-16 16:09:49 +01002649scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2650 switch (strategy) {
2651 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2652 return Seamlessness::OnlySeamless;
2653 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2654 return Seamlessness::SeamedAndSeamless;
2655 default:
2656 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2657 return Seamlessness::Default;
2658 }
2659}
2660
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002661bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002662 const State& s(mDrawingState);
2663 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2664 return true;
2665 }
2666
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002667 sp<Layer> parent = mDrawingParent.promote();
2668 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002669}
2670
Robert Carr6a0382d2021-07-01 15:57:17 -07002671void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2672 mClonedChild = clonedChild;
2673 mHadClonedChild = true;
2674 mFlinger->mNumClones++;
2675}
2676
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002677bool Layer::setDropInputMode(gui::DropInputMode mode) {
2678 if (mDrawingState.dropInputMode == mode) {
2679 return false;
2680 }
2681 mDrawingState.dropInputMode = mode;
2682 return true;
2683}
2684
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002685void Layer::cloneDrawingState(const Layer* from) {
2686 mDrawingState = from->mDrawingState;
2687 // Skip callback info since they are not applicable for cloned layers.
2688 mDrawingState.releaseBufferListener = nullptr;
2689 mDrawingState.callbackHandles = {};
2690}
2691
Patrick Williamsbb25f802022-08-30 23:02:34 +00002692void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2693 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
2694 const sp<Fence>& releaseFence,
2695 uint32_t currentMaxAcquiredBufferCount) {
2696 if (!listener) {
2697 return;
2698 }
2699 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002700 listener->onReleaseBuffer({buffer->getId(), framenumber},
2701 releaseFence ? releaseFence : Fence::NO_FENCE,
2702 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002703}
2704
2705void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2706 // If we are displayed on multiple displays in a single composition cycle then we would
2707 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2708 // For example we can only use it if all the displays are client comp, and we need
2709 // to merge all the client comp fences. We could do this, but for now we just
2710 // disable the optimization when a layer is composed on multiple displays.
2711 if (mClearClientCompositionFenceOnLayerDisplayed) {
2712 mLastClientCompositionFence = nullptr;
2713 } else {
2714 mClearClientCompositionFenceOnLayerDisplayed = true;
2715 }
2716
2717 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2718 // buffer that was presented on this layer. The first transaction that came in this frame that
2719 // replaced the previous buffer on this layer needs this release fence, because the fence will
2720 // let the client know when that previous buffer is removed from the screen.
2721 //
2722 // Every other transaction on this layer does not need a release fence because no other
2723 // Transactions that were set on this layer this frame are going to have their preceding buffer
2724 // removed from the display this frame.
2725 //
2726 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2727 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2728 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2729 // the previous buffer will be released this frame. The third transaction also contains a
2730 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2731 // transaction will now no longer be presented so it is released immediately and the third
2732 // transaction doesn't need a previous release fence.
2733 sp<CallbackHandle> ch;
2734 for (auto& handle : mDrawingState.callbackHandles) {
2735 if (handle->releasePreviousBuffer &&
2736 mDrawingState.releaseBufferEndpoint == handle->listener) {
2737 ch = handle;
2738 break;
2739 }
2740 }
2741
2742 // Prevent tracing the same release multiple times.
2743 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2744 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2745 }
2746
2747 if (ch != nullptr) {
2748 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2749 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2750 ch->name = mName;
2751 }
2752}
2753
2754void Layer::onSurfaceFrameCreated(
2755 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2756 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2757 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2758 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2759 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002760 if (hasBufferOrSidebandStreamInDrawing()) {
2761 // Only log for layers with a buffer, since we expect the jank data to be drained for
2762 // these, while there may be no jank listeners for bufferless layers.
2763 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2764 mName.c_str());
2765 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2766 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2767 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002768 mPendingJankClassifications.pop_front();
2769 }
2770 mPendingJankClassifications.emplace_back(surfaceFrame);
2771}
2772
2773void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2774 for (const auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair71fcf912022-10-18 09:14:20 -07002775 handle->transformHint = mSkipReportingTransformHint
2776 ? std::nullopt
2777 : std::make_optional<uint32_t>(mTransformHint);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002778 handle->dequeueReadyTime = dequeueReadyTime;
2779 handle->currentMaxAcquiredBufferCount =
2780 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2781 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2782 handle->previousReleaseCallbackId.framenumber);
2783 }
2784
2785 for (auto& handle : mDrawingState.callbackHandles) {
2786 if (handle->releasePreviousBuffer &&
2787 mDrawingState.releaseBufferEndpoint == handle->listener) {
2788 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2789 break;
2790 }
2791 }
2792
2793 std::vector<JankData> jankData;
2794 jankData.reserve(mPendingJankClassifications.size());
2795 while (!mPendingJankClassifications.empty() &&
2796 mPendingJankClassifications.front()->getJankType()) {
2797 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
2798 mPendingJankClassifications.front();
2799 mPendingJankClassifications.pop_front();
2800 jankData.emplace_back(
2801 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
2802 }
2803
2804 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2805 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002806 mDrawingState.callbackHandles = {};
2807}
2808
2809bool Layer::willPresentCurrentTransaction() const {
2810 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2811 return (getSidebandStreamChanged() || getAutoRefresh() ||
2812 (mDrawingState.modified &&
2813 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2814}
2815
2816bool Layer::setTransform(uint32_t transform) {
2817 if (mDrawingState.bufferTransform == transform) return false;
2818 mDrawingState.bufferTransform = transform;
2819 mDrawingState.modified = true;
2820 setTransactionFlags(eTransactionNeeded);
2821 return true;
2822}
2823
2824bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2825 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2826 mDrawingState.sequence++;
2827 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2828 mDrawingState.modified = true;
2829 setTransactionFlags(eTransactionNeeded);
2830 return true;
2831}
2832
2833bool Layer::setBufferCrop(const Rect& bufferCrop) {
2834 if (mDrawingState.bufferCrop == bufferCrop) return false;
2835
2836 mDrawingState.sequence++;
2837 mDrawingState.bufferCrop = bufferCrop;
2838
2839 mDrawingState.modified = true;
2840 setTransactionFlags(eTransactionNeeded);
2841 return true;
2842}
2843
2844bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2845 if (mDrawingState.destinationFrame == destinationFrame) return false;
2846
2847 mDrawingState.sequence++;
2848 mDrawingState.destinationFrame = destinationFrame;
2849
2850 mDrawingState.modified = true;
2851 setTransactionFlags(eTransactionNeeded);
2852 return true;
2853}
2854
2855// Translate destination frame into scale and position. If a destination frame is not set, use the
2856// provided scale and position
2857bool Layer::updateGeometry() {
2858 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2859 mDrawingState.destinationFrame.isEmpty()) {
2860 // If destination frame is not set, use the requested transform set via
2861 // Layer::setPosition and Layer::setMatrix.
2862 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2863 }
2864
2865 Rect destRect = mDrawingState.destinationFrame;
2866 int32_t destW = destRect.width();
2867 int32_t destH = destRect.height();
2868 if (destRect.left < 0) {
2869 destRect.left = 0;
2870 destRect.right = destW;
2871 }
2872 if (destRect.top < 0) {
2873 destRect.top = 0;
2874 destRect.bottom = destH;
2875 }
2876
2877 if (!mDrawingState.buffer) {
2878 ui::Transform t;
2879 t.set(destRect.left, destRect.top);
2880 return assignTransform(&mDrawingState.transform, t);
2881 }
2882
2883 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2884 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2885 // Undo any transformations on the buffer.
2886 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2887 std::swap(bufferWidth, bufferHeight);
2888 }
2889 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
2890 if (mDrawingState.transformToDisplayInverse) {
2891 if (invTransform & ui::Transform::ROT_90) {
2892 std::swap(bufferWidth, bufferHeight);
2893 }
2894 }
2895
2896 float sx = destW / static_cast<float>(bufferWidth);
2897 float sy = destH / static_cast<float>(bufferHeight);
2898 ui::Transform t;
2899 t.set(sx, 0, 0, sy);
2900 t.set(destRect.left, destRect.top);
2901 return assignTransform(&mDrawingState.transform, t);
2902}
2903
2904bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
2905 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
2906 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
2907 return false;
2908 }
2909
2910 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
2911
2912 mDrawingState.sequence++;
2913 mDrawingState.modified = true;
2914 setTransactionFlags(eTransactionNeeded);
2915
2916 return true;
2917}
2918
2919bool Layer::setPosition(float x, float y) {
2920 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
2921 return false;
2922 }
2923
2924 mRequestedTransform.set(x, y);
2925
2926 mDrawingState.sequence++;
2927 mDrawingState.modified = true;
2928 setTransactionFlags(eTransactionNeeded);
2929
2930 return true;
2931}
2932
2933bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
2934 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
2935 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07002936 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00002937 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00002938 if (!buffer) {
2939 return false;
2940 }
2941
2942 const bool frameNumberChanged =
2943 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
2944 const uint64_t frameNumber =
2945 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00002946 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002947
2948 if (mDrawingState.buffer) {
2949 mReleasePreviousBuffer = true;
2950 if (!mBufferInfo.mBuffer ||
2951 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
2952 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
2953 // If mDrawingState has a buffer, and we are about to update again
2954 // before swapping to drawing state, then the first buffer will be
2955 // dropped and we should decrement the pending buffer count and
2956 // call any release buffer callbacks if set.
2957 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
2958 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
2959 mDrawingState.acquireFence,
2960 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
2961 mOwnerUid));
2962 decrementPendingBufferCount();
2963 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
2964 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
2965 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
2966 mDrawingState.bufferSurfaceFrameTX.reset();
2967 }
2968 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
2969 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
2970 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
2971 mLastClientCompositionFence,
2972 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
2973 mOwnerUid));
2974 mLastClientCompositionFence = nullptr;
2975 }
2976 }
2977
2978 mDrawingState.frameNumber = frameNumber;
2979 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
2980 mDrawingState.buffer = std::move(buffer);
2981 mDrawingState.clientCacheId = bufferData.cachedBuffer;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002982 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
2983 ? bufferData.acquireFence
2984 : Fence::NO_FENCE;
2985 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
2986 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
2987 // We latched this buffer unsiganled, so we need to pass the acquire fence
2988 // on the callback instead of just the acquire time, since it's unknown at
2989 // this point.
2990 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
2991 } else {
2992 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
2993 }
2994
2995 mDrawingState.modified = true;
2996 setTransactionFlags(eTransactionNeeded);
2997
2998 const int32_t layerId = getSequence();
2999 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3000 mOwnerUid, postTime, getGameMode());
3001 mDrawingState.desiredPresentTime = desiredPresentTime;
3002 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3003
3004 const nsecs_t presentTime = [&] {
3005 if (!isAutoTimestamp) return desiredPresentTime;
3006
3007 const auto prediction =
3008 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
3009 if (prediction.has_value()) return prediction->presentTime;
3010
3011 return static_cast<nsecs_t>(0);
3012 }();
3013
3014 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
3015 mFlinger->mScheduler->recordLayerHistory(this, presentTime, LayerUpdateType::Buffer);
3016
3017 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3018
3019 if (dequeueTime && *dequeueTime != 0) {
3020 const uint64_t bufferId = mDrawingState.buffer->getId();
3021 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3022 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3023 FrameTracer::FrameEvent::DEQUEUE);
3024 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3025 FrameTracer::FrameEvent::QUEUE);
3026 }
3027
3028 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3029 return true;
3030}
3031
3032bool Layer::setDataspace(ui::Dataspace dataspace) {
3033 mDrawingState.dataspaceRequested = true;
3034 if (mDrawingState.dataspace == dataspace) return false;
3035 mDrawingState.dataspace = dataspace;
3036 mDrawingState.modified = true;
3037 setTransactionFlags(eTransactionNeeded);
3038 return true;
3039}
3040
3041bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3042 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3043 mDrawingState.hdrMetadata = hdrMetadata;
3044 mDrawingState.modified = true;
3045 setTransactionFlags(eTransactionNeeded);
3046 return true;
3047}
3048
3049bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
3050 mDrawingState.surfaceDamageRegion = surfaceDamage;
3051 mDrawingState.modified = true;
3052 setTransactionFlags(eTransactionNeeded);
3053 return true;
3054}
3055
3056bool Layer::setApi(int32_t api) {
3057 if (mDrawingState.api == api) return false;
3058 mDrawingState.api = api;
3059 mDrawingState.modified = true;
3060 setTransactionFlags(eTransactionNeeded);
3061 return true;
3062}
3063
3064bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3065 if (mDrawingState.sidebandStream == sidebandStream) return false;
3066
3067 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3068 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3069 } else if (sidebandStream != nullptr) {
3070 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3071 }
3072
3073 mDrawingState.sidebandStream = sidebandStream;
3074 mDrawingState.modified = true;
3075 setTransactionFlags(eTransactionNeeded);
3076 if (!mSidebandStreamChanged.exchange(true)) {
3077 // mSidebandStreamChanged was false
3078 mFlinger->onLayerUpdate();
3079 }
3080 return true;
3081}
3082
3083bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles) {
3084 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3085 if (handles.empty()) {
3086 mReleasePreviousBuffer = false;
3087 return false;
3088 }
3089
3090 const bool willPresent = willPresentCurrentTransaction();
3091
3092 for (const auto& handle : handles) {
3093 // If this transaction set a buffer on this layer, release its previous buffer
3094 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3095
3096 // If this layer will be presented in this frame
3097 if (willPresent) {
3098 // If this transaction set an acquire fence on this layer, set its acquire time
3099 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3100 handle->frameNumber = mDrawingState.frameNumber;
3101
3102 // Store so latched time and release fence can be set
3103 mDrawingState.callbackHandles.push_back(handle);
3104
3105 } else { // If this layer will NOT need to be relatched and presented this frame
3106 // Notify the transaction completed thread this handle is done
3107 mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
3108 }
3109 }
3110
3111 mReleasePreviousBuffer = false;
3112 mCallbackHandleAcquireTimeOrFence = -1;
3113
3114 return willPresent;
3115}
3116
3117Rect Layer::getBufferSize(const State& /*s*/) const {
3118 // for buffer state layers we use the display frame size as the buffer size.
3119
3120 if (mBufferInfo.mBuffer == nullptr) {
3121 return Rect::INVALID_RECT;
3122 }
3123
3124 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3125 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3126
3127 // Undo any transformations on the buffer and return the result.
3128 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3129 std::swap(bufWidth, bufHeight);
3130 }
3131
3132 if (getTransformToDisplayInverse()) {
3133 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3134 if (invTransform & ui::Transform::ROT_90) {
3135 std::swap(bufWidth, bufHeight);
3136 }
3137 }
3138
3139 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3140}
3141
3142FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3143 if (mBufferInfo.mBuffer == nullptr) {
3144 return parentBounds;
3145 }
3146
3147 return getBufferSize(getDrawingState()).toFloatRect();
3148}
3149
3150bool Layer::fenceHasSignaled() const {
3151 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3152 return true;
3153 }
3154
3155 const bool fenceSignaled =
3156 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3157 if (!fenceSignaled) {
3158 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3159 TimeStats::LatchSkipReason::LateAcquire);
3160 }
3161
3162 return fenceSignaled;
3163}
3164
Vishnu Naire14c6b32022-08-06 04:20:15 +00003165bool Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003166 for (const auto& handle : mDrawingState.callbackHandles) {
3167 handle->refreshStartTime = refreshStartTime;
3168 }
3169 return hasReadyFrame();
3170}
3171
3172void Layer::setAutoRefresh(bool autoRefresh) {
3173 mDrawingState.autoRefresh = autoRefresh;
3174}
3175
3176bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3177 // 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 +00003178 auto* snapshot = editLayerSnapshot();
3179 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003180
3181 if (mSidebandStreamChanged.exchange(false)) {
3182 const State& s(getDrawingState());
3183 // mSidebandStreamChanged was true
3184 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003185 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003186 if (mSidebandStream != nullptr) {
3187 setTransactionFlags(eTransactionNeeded);
3188 mFlinger->setTransactionFlags(eTraversalNeeded);
3189 }
3190 recomputeVisibleRegions = true;
3191
3192 return true;
3193 }
3194 return false;
3195}
3196
3197bool Layer::hasFrameUpdate() const {
3198 const State& c(getDrawingState());
3199 return (mDrawingStateModified || mDrawingState.modified) &&
3200 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3201}
3202
3203void Layer::updateTexImage(nsecs_t latchTime) {
3204 const State& s(getDrawingState());
3205
3206 if (!s.buffer) {
3207 if (s.bgColorLayer) {
3208 for (auto& handle : mDrawingState.callbackHandles) {
3209 handle->latchTime = latchTime;
3210 }
3211 }
3212 return;
3213 }
3214
3215 for (auto& handle : mDrawingState.callbackHandles) {
3216 if (handle->frameNumber == mDrawingState.frameNumber) {
3217 handle->latchTime = latchTime;
3218 }
3219 }
3220
3221 const int32_t layerId = getSequence();
3222 const uint64_t bufferId = mDrawingState.buffer->getId();
3223 const uint64_t frameNumber = mDrawingState.frameNumber;
3224 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3225 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3226 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3227
3228 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3229 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3230 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3231 FrameTracer::FrameEvent::LATCH);
3232
3233 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3234 if (bufferSurfaceFrame != nullptr &&
3235 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3236 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3237 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3238 // are processing the next state.
3239 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3240 mDrawingState.acquireFenceTime->getSignalTime(),
3241 latchTime);
3242 mDrawingState.bufferSurfaceFrameTX.reset();
3243 }
3244
3245 std::deque<sp<CallbackHandle>> remainingHandles;
3246 mFlinger->getTransactionCallbackInvoker()
3247 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3248 mDrawingState.callbackHandles = remainingHandles;
3249
3250 mDrawingStateModified = false;
3251}
3252
3253void Layer::gatherBufferInfo() {
3254 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3255 decrementPendingBufferCount();
3256 }
3257
3258 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3259 mBufferInfo.mBuffer = mDrawingState.buffer;
3260 mBufferInfo.mFence = mDrawingState.acquireFence;
3261 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3262 mBufferInfo.mPixelFormat =
3263 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3264 mBufferInfo.mFrameLatencyNeeded = true;
3265 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3266 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3267 mBufferInfo.mFence = mDrawingState.acquireFence;
3268 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3269 auto lastDataspace = mBufferInfo.mDataspace;
3270 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3271 if (lastDataspace != mBufferInfo.mDataspace) {
3272 mFlinger->mSomeDataspaceChanged = true;
3273 }
3274 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3275 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3276 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3277 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3278 mBufferInfo.mApi = mDrawingState.api;
3279 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003280}
3281
3282Rect Layer::computeBufferCrop(const State& s) {
3283 if (s.buffer && !s.bufferCrop.isEmpty()) {
3284 Rect bufferCrop;
3285 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3286 return bufferCrop;
3287 } else if (s.buffer) {
3288 return s.buffer->getBounds();
3289 } else {
3290 return s.bufferCrop;
3291 }
3292}
3293
3294sp<Layer> Layer::createClone() {
3295 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3296 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003297 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003298 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3299 return layer;
3300}
3301
3302bool Layer::bufferNeedsFiltering() const {
3303 const State& s(getDrawingState());
3304 if (!s.buffer) {
3305 return false;
3306 }
3307
3308 int32_t bufferWidth = static_cast<int32_t>(s.buffer->getWidth());
3309 int32_t bufferHeight = static_cast<int32_t>(s.buffer->getHeight());
3310
3311 // Undo any transformations on the buffer and return the result.
3312 if (s.bufferTransform & ui::Transform::ROT_90) {
3313 std::swap(bufferWidth, bufferHeight);
3314 }
3315
3316 if (s.transformToDisplayInverse) {
3317 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3318 if (invTransform & ui::Transform::ROT_90) {
3319 std::swap(bufferWidth, bufferHeight);
3320 }
3321 }
3322
3323 const Rect layerSize{getBounds()};
3324 int32_t layerWidth = layerSize.getWidth();
3325 int32_t layerHeight = layerSize.getHeight();
3326
3327 // Align the layer orientation with the buffer before comparism
3328 if (mTransformHint & ui::Transform::ROT_90) {
3329 std::swap(layerWidth, layerHeight);
3330 }
3331
3332 return layerWidth != bufferWidth || layerHeight != bufferHeight;
3333}
3334
3335void Layer::decrementPendingBufferCount() {
3336 int32_t pendingBuffers = --mPendingBufferTransactions;
3337 tracePendingBufferCount(pendingBuffers);
3338}
3339
3340void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3341 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3342}
3343
3344/*
3345 * We don't want to send the layer's transform to input, but rather the
3346 * parent's transform. This is because Layer's transform is
3347 * information about how the buffer is placed on screen. The parent's
3348 * transform makes more sense to send since it's information about how the
3349 * layer is placed on screen. This transform is used by input to determine
3350 * how to go from screen space back to window space.
3351 */
3352ui::Transform Layer::getInputTransform() const {
3353 if (!hasBufferOrSidebandStream()) {
3354 return getTransform();
3355 }
3356 sp<Layer> parent = mDrawingParent.promote();
3357 if (parent == nullptr) {
3358 return ui::Transform();
3359 }
3360
3361 return parent->getTransform();
3362}
3363
3364/**
3365 * Similar to getInputTransform, we need to update the bounds to include the transform.
3366 * This is because bounds don't include the buffer transform, where the input assumes
3367 * that's already included.
3368 */
3369Rect Layer::getInputBounds() const {
3370 if (!hasBufferOrSidebandStream()) {
3371 return getCroppedBufferSize(getDrawingState());
3372 }
3373
3374 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
3375 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
3376 return bufferBounds;
3377 }
3378 return mDrawingState.transform.transform(bufferBounds);
3379}
3380
3381bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3382 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3383
3384 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3385 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3386 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3387 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3388 layer_state_t::eReparent;
3389
3390 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3391 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3392 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3393 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3394 layer_state_t::eInputInfoChanged;
3395
3396 if ((s.what & requiredFlags) != requiredFlags) {
3397 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3398 (s.what | requiredFlags) & ~s.what);
3399 return false;
3400 }
3401
3402 if (s.what & deniedFlags) {
3403 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3404 return false;
3405 }
3406
3407 if (s.what & allowedFlags) {
3408 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3409 }
3410
3411 if (s.what & layer_state_t::ePositionChanged) {
3412 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3413 ALOGV("%s: false [ePositionChanged changed]", __func__);
3414 return false;
3415 }
3416 }
3417
3418 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003419 if (mDrawingState.color.a != s.color.a) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003420 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3421 return false;
3422 }
3423 }
3424
3425 if (s.what & layer_state_t::eColorTransformChanged) {
3426 if (mDrawingState.colorTransform != s.colorTransform) {
3427 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3428 return false;
3429 }
3430 }
3431
3432 if (s.what & layer_state_t::eBackgroundColorChanged) {
3433 if (mDrawingState.bgColorLayer || s.bgColorAlpha != 0) {
3434 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3435 return false;
3436 }
3437 }
3438
3439 if (s.what & layer_state_t::eMatrixChanged) {
3440 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3441 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3442 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3443 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3444 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3445 return false;
3446 }
3447 }
3448
3449 if (s.what & layer_state_t::eCornerRadiusChanged) {
3450 if (mDrawingState.cornerRadius != s.cornerRadius) {
3451 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3452 return false;
3453 }
3454 }
3455
3456 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3457 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3458 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3459 return false;
3460 }
3461 }
3462
Vishnu Nairbbceb462022-10-10 04:52:13 +00003463 if (s.what & layer_state_t::eBufferTransformChanged) {
3464 if (mDrawingState.bufferTransform != s.bufferTransform) {
3465 ALOGV("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003466 return false;
3467 }
3468 }
3469
3470 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3471 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3472 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3473 return false;
3474 }
3475 }
3476
3477 if (s.what & layer_state_t::eCropChanged) {
3478 if (mDrawingState.crop != s.crop) {
3479 ALOGV("%s: false [eCropChanged changed]", __func__);
3480 return false;
3481 }
3482 }
3483
3484 if (s.what & layer_state_t::eDataspaceChanged) {
3485 if (mDrawingState.dataspace != s.dataspace) {
3486 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3487 return false;
3488 }
3489 }
3490
3491 if (s.what & layer_state_t::eHdrMetadataChanged) {
3492 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3493 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3494 return false;
3495 }
3496 }
3497
3498 if (s.what & layer_state_t::eSidebandStreamChanged) {
3499 if (mDrawingState.sidebandStream != s.sidebandStream) {
3500 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3501 return false;
3502 }
3503 }
3504
3505 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3506 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3507 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3508 return false;
3509 }
3510 }
3511
3512 if (s.what & layer_state_t::eShadowRadiusChanged) {
3513 if (mDrawingState.shadowRadius != s.shadowRadius) {
3514 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3515 return false;
3516 }
3517 }
3518
3519 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3520 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3521 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3522 return false;
3523 }
3524 }
3525
3526 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3527 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3528 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3529 return false;
3530 }
3531 }
3532
3533 if (s.what & layer_state_t::eStretchChanged) {
3534 StretchEffect temp = s.stretchEffect;
3535 temp.sanitize();
3536 if (mDrawingState.stretchEffect != temp) {
3537 ALOGV("%s: false [eStretchChanged changed]", __func__);
3538 return false;
3539 }
3540 }
3541
3542 if (s.what & layer_state_t::eBufferCropChanged) {
3543 if (mDrawingState.bufferCrop != s.bufferCrop) {
3544 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3545 return false;
3546 }
3547 }
3548
3549 if (s.what & layer_state_t::eDestinationFrameChanged) {
3550 if (mDrawingState.destinationFrame != s.destinationFrame) {
3551 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3552 return false;
3553 }
3554 }
3555
3556 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3557 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3558 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3559 return false;
3560 }
3561 }
3562
3563 ALOGV("%s: true", __func__);
3564 return true;
3565}
3566
3567bool Layer::isHdrY410() const {
3568 // pixel format is HDR Y410 masquerading as RGBA_1010102
3569 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3570 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3571 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3572}
3573
Vishnu Naire14c6b32022-08-06 04:20:15 +00003574sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003575 // 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 +00003576 return hasSomethingToDraw() ? mLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003577}
3578
Vishnu Naire14c6b32022-08-06 04:20:15 +00003579const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003580 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003581}
3582
Vishnu Naire14c6b32022-08-06 04:20:15 +00003583LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003584 return mSnapshot.get();
3585}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003586
Patrick Williamsbb25f802022-08-30 23:02:34 +00003587const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003588 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003589}
3590
Patrick Williams7584c6a2022-10-29 02:10:58 +00003591sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
3592 auto result = mFlinger->getFactory().createLayerFE(mLayerFE->getDebugName());
3593 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3594 return result;
3595}
3596
Patrick Williamsbb25f802022-08-30 23:02:34 +00003597void Layer::useSurfaceDamage() {
3598 if (mFlinger->mForceFullDamage) {
3599 surfaceDamageRegion = Region::INVALID_REGION;
3600 } else {
3601 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3602 }
3603}
3604
3605void Layer::useEmptyDamage() {
3606 surfaceDamageRegion.clear();
3607}
3608
3609bool Layer::isOpaque(const Layer::State& s) const {
3610 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3611 // layer's opaque flag.
3612 if (!hasSomethingToDraw()) {
3613 return false;
3614 }
3615
3616 // if the layer has the opaque flag, then we're always opaque
3617 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3618 return true;
3619 }
3620
3621 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003622 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003623 return true;
3624 }
3625
3626 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3627 return fillsColor() && getAlpha() == 1.0_hf;
3628}
3629
3630bool Layer::canReceiveInput() const {
3631 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3632}
3633
3634bool Layer::isVisible() const {
3635 if (!hasSomethingToDraw()) {
3636 return false;
3637 }
3638
3639 if (isHiddenByPolicy()) {
3640 return false;
3641 }
3642
3643 return getAlpha() > 0.0f || hasBlur();
3644}
3645
3646void Layer::onPostComposition(const DisplayDevice* display,
3647 const std::shared_ptr<FenceTime>& glDoneFence,
3648 const std::shared_ptr<FenceTime>& presentFence,
3649 const CompositorTiming& compositorTiming) {
3650 // mFrameLatencyNeeded is true when a new frame was latched for the
3651 // composition.
3652 if (!mBufferInfo.mFrameLatencyNeeded) return;
3653
3654 for (const auto& handle : mDrawingState.callbackHandles) {
3655 handle->gpuCompositionDoneFence = glDoneFence;
3656 handle->compositorTiming = compositorTiming;
3657 }
3658
3659 // Update mFrameTracker.
3660 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3661 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3662
3663 const int32_t layerId = getSequence();
3664 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3665
3666 const auto outputLayer = findOutputLayerForDisplay(display);
3667 if (outputLayer && outputLayer->requiresClientComposition()) {
3668 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3669 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3670 clientCompositionTimestamp,
3671 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3672 // Update the SurfaceFrames in the drawing state
3673 if (mDrawingState.bufferSurfaceFrameTX) {
3674 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3675 }
3676 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3677 surfaceFrame->setGpuComposition();
3678 }
3679 }
3680
3681 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3682 if (frameReadyFence->isValid()) {
3683 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3684 } else {
3685 // There was no fence for this frame, so assume that it was ready
3686 // to be presented at the desired present time.
3687 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3688 }
3689
3690 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08003691 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003692 const std::optional<Fps> renderRate =
3693 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3694
3695 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3696 const auto gameMode = getGameMode();
3697
3698 if (presentFence->isValid()) {
3699 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3700 refreshRate, renderRate, vote, gameMode);
3701 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3702 presentFence,
3703 FrameTracer::FrameEvent::PRESENT_FENCE);
3704 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3705 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3706 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003707 // The HWC doesn't support present fences, so use the present timestamp instead.
3708 const nsecs_t presentTimestamp =
3709 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3710
3711 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3712 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3713 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3714
Patrick Williamsbb25f802022-08-30 23:02:34 +00003715 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3716 refreshRate, renderRate, vote, gameMode);
3717 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3718 mCurrentFrameNumber, actualPresentTime,
3719 FrameTracer::FrameEvent::PRESENT_FENCE);
3720 mFrameTracker.setActualPresentTime(actualPresentTime);
3721 }
3722 }
3723
3724 mFrameTracker.advanceFrame();
3725 mBufferInfo.mFrameLatencyNeeded = false;
3726}
3727
3728bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
3729 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3730 getDrawingState().frameNumber);
3731
3732 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3733
3734 if (refreshRequired) {
3735 return refreshRequired;
3736 }
3737
3738 // If the head buffer's acquire fence hasn't signaled yet, return and
3739 // try again later
3740 if (!fenceHasSignaled()) {
3741 ATRACE_NAME("!fenceHasSignaled()");
3742 mFlinger->onLayerUpdate();
3743 return false;
3744 }
3745
3746 updateTexImage(latchTime);
3747 if (mDrawingState.buffer == nullptr) {
3748 return false;
3749 }
3750
3751 // Capture the old state of the layer for comparisons later
3752 BufferInfo oldBufferInfo = mBufferInfo;
3753 const bool oldOpacity = isOpaque(mDrawingState);
3754 mPreviousFrameNumber = mCurrentFrameNumber;
3755 mCurrentFrameNumber = mDrawingState.frameNumber;
3756 gatherBufferInfo();
3757
3758 if (oldBufferInfo.mBuffer == nullptr) {
3759 // the first time we receive a buffer, we need to trigger a
3760 // geometry invalidation.
3761 recomputeVisibleRegions = true;
3762 }
3763
3764 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3765 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3766 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3767 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3768 recomputeVisibleRegions = true;
3769 }
3770
3771 if (oldBufferInfo.mBuffer != nullptr) {
3772 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3773 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3774 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3775 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3776 recomputeVisibleRegions = true;
3777 }
3778 }
3779
3780 if (oldOpacity != isOpaque(mDrawingState)) {
3781 recomputeVisibleRegions = true;
3782 }
3783
3784 return true;
3785}
3786
3787bool Layer::hasReadyFrame() const {
3788 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
3789}
3790
3791bool Layer::isProtected() const {
3792 return (mBufferInfo.mBuffer != nullptr) &&
3793 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
3794}
3795
Patrick Williamsbb25f802022-08-30 23:02:34 +00003796bool Layer::needsFiltering(const DisplayDevice* display) const {
3797 if (!hasBufferOrSidebandStream()) {
3798 return false;
3799 }
3800 const auto outputLayer = findOutputLayerForDisplay(display);
3801 if (outputLayer == nullptr) {
3802 return false;
3803 }
3804
3805 // We need filtering if the sourceCrop rectangle size does not match the
3806 // displayframe rectangle size (not a 1:1 render)
3807 const auto& compositionState = outputLayer->getState();
3808 const auto displayFrame = compositionState.displayFrame;
3809 const auto sourceCrop = compositionState.sourceCrop;
3810 return sourceCrop.getHeight() != displayFrame.getHeight() ||
3811 sourceCrop.getWidth() != displayFrame.getWidth();
3812}
3813
3814bool Layer::needsFilteringForScreenshots(const DisplayDevice* display,
3815 const ui::Transform& inverseParentTransform) const {
3816 if (!hasBufferOrSidebandStream()) {
3817 return false;
3818 }
3819 const auto outputLayer = findOutputLayerForDisplay(display);
3820 if (outputLayer == nullptr) {
3821 return false;
3822 }
3823
3824 // We need filtering if the sourceCrop rectangle size does not match the
3825 // viewport rectangle size (not a 1:1 render)
3826 const auto& compositionState = outputLayer->getState();
3827 const ui::Transform& displayTransform = display->getTransform();
3828 const ui::Transform inverseTransform = inverseParentTransform * displayTransform.inverse();
3829 // Undo the transformation of the displayFrame so that we're back into
3830 // layer-stack space.
3831 const Rect frame = inverseTransform.transform(compositionState.displayFrame);
3832 const FloatRect sourceCrop = compositionState.sourceCrop;
3833
3834 int32_t frameHeight = frame.getHeight();
3835 int32_t frameWidth = frame.getWidth();
3836 // If the display transform had a rotational component then undo the
3837 // rotation so that the orientation matches the source crop.
3838 if (displayTransform.getOrientation() & ui::Transform::ROT_90) {
3839 std::swap(frameHeight, frameWidth);
3840 }
3841 return sourceCrop.getHeight() != frameHeight || sourceCrop.getWidth() != frameWidth;
3842}
3843
3844void Layer::latchAndReleaseBuffer() {
3845 if (hasReadyFrame()) {
3846 bool ignored = false;
3847 latchBuffer(ignored, systemTime());
3848 }
3849 releasePendingBuffer(systemTime());
3850}
3851
3852PixelFormat Layer::getPixelFormat() const {
3853 return mBufferInfo.mPixelFormat;
3854}
3855
3856bool Layer::getTransformToDisplayInverse() const {
3857 return mBufferInfo.mTransformToDisplayInverse;
3858}
3859
3860Rect Layer::getBufferCrop() const {
3861 // this is the crop rectangle that applies to the buffer
3862 // itself (as opposed to the window)
3863 if (!mBufferInfo.mCrop.isEmpty()) {
3864 // if the buffer crop is defined, we use that
3865 return mBufferInfo.mCrop;
3866 } else if (mBufferInfo.mBuffer != nullptr) {
3867 // otherwise we use the whole buffer
3868 return mBufferInfo.mBuffer->getBounds();
3869 } else {
3870 // if we don't have a buffer yet, we use an empty/invalid crop
3871 return Rect();
3872 }
3873}
3874
3875uint32_t Layer::getBufferTransform() const {
3876 return mBufferInfo.mTransform;
3877}
3878
3879ui::Dataspace Layer::getDataSpace() const {
3880 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
3881}
3882
3883ui::Dataspace Layer::getRequestedDataSpace() const {
3884 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
3885}
3886
3887ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
3888 ui::Dataspace updatedDataspace = dataspace;
3889 // translate legacy dataspaces to modern dataspaces
3890 switch (dataspace) {
3891 case ui::Dataspace::SRGB:
3892 updatedDataspace = ui::Dataspace::V0_SRGB;
3893 break;
3894 case ui::Dataspace::SRGB_LINEAR:
3895 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
3896 break;
3897 case ui::Dataspace::JFIF:
3898 updatedDataspace = ui::Dataspace::V0_JFIF;
3899 break;
3900 case ui::Dataspace::BT601_625:
3901 updatedDataspace = ui::Dataspace::V0_BT601_625;
3902 break;
3903 case ui::Dataspace::BT601_525:
3904 updatedDataspace = ui::Dataspace::V0_BT601_525;
3905 break;
3906 case ui::Dataspace::BT709:
3907 updatedDataspace = ui::Dataspace::V0_BT709;
3908 break;
3909 default:
3910 break;
3911 }
3912
3913 return updatedDataspace;
3914}
3915
3916sp<GraphicBuffer> Layer::getBuffer() const {
3917 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
3918}
3919
Patrick Williamsbb25f802022-08-30 23:02:34 +00003920void Layer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
3921 mTransformHint = getFixedTransformHint();
3922 if (mTransformHint == ui::Transform::ROT_INVALID) {
3923 mTransformHint = displayTransformHint;
3924 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07003925 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003926}
3927
3928const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
3929 return mBufferInfo.mBuffer;
3930}
3931
3932bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003933 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003934 return false;
3935 }
3936
3937 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00003938 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003939 mDrawingState.modified = true;
3940 setTransactionFlags(eTransactionNeeded);
3941 return true;
3942}
3943
3944bool Layer::fillsColor() const {
3945 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
3946 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
3947}
3948
3949bool Layer::hasBlur() const {
3950 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
3951}
3952
Vishnu Nairba354102022-08-01 00:14:18 +00003953void Layer::updateSnapshot(bool updateGeometry) {
3954 if (!getCompositionEngineLayerFE()) {
3955 return;
3956 }
3957
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003958 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00003959 if (updateGeometry) {
3960 prepareBasicGeometryCompositionState();
3961 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003962 snapshot->roundedCorner = getRoundedCornerState();
3963 snapshot->stretchEffect = getStretchEffect();
3964 snapshot->transformedBounds = mScreenBounds;
3965 if (mEffectiveShadowRadius > 0.f) {
3966 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
3967
3968 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
3969 // it if transparent regions are present. This may not be necessary since shadows are
3970 // typically cast by layers without transparent regions.
3971 snapshot->shadowSettings.boundaries = mBounds;
3972
3973 const float casterAlpha = snapshot->alpha;
3974 const bool casterIsOpaque =
3975 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
3976
3977 // If the casting layer is translucent, we need to fill in the shadow underneath the
3978 // layer. Otherwise the generated shadow will only be shown around the casting layer.
3979 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
3980 snapshot->shadowSettings.ambientColor *= casterAlpha;
3981 snapshot->shadowSettings.spotColor *= casterAlpha;
3982 }
3983 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00003984 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003985 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003986 snapshot->layerOpaqueFlagSet =
3987 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003988 snapshot->isHdrY410 = isHdrY410();
3989 snapshot->bufferNeedsFiltering = bufferNeedsFiltering();
3990 sp<Layer> p = mDrawingParent.promote();
3991 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003992 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003993 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003994 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003995 }
3996 snapshot->bufferSize = getBufferSize(mDrawingState);
3997 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00003998 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00003999 preparePerFrameCompositionState();
4000}
4001
Vishnu Naire14c6b32022-08-06 04:20:15 +00004002void Layer::updateChildrenSnapshots(bool updateGeometry) {
4003 for (const sp<Layer>& child : mDrawingChildren) {
4004 child->updateSnapshot(updateGeometry);
4005 child->updateChildrenSnapshots(updateGeometry);
4006 }
4007}
4008
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004009void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4010 mSnapshot->layerMetadata = parentMetadata;
4011 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4012 for (const sp<Layer>& child : mDrawingChildren) {
4013 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4014 }
4015}
4016
4017void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4018 std::unordered_set<Layer*>& visited) {
4019 if (visited.find(this) != visited.end()) {
4020 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4021 return;
4022 }
4023 visited.insert(this);
4024
4025 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4026
4027 if (mDrawingState.zOrderRelatives.empty()) {
4028 return;
4029 }
4030 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4031 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4032 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4033 sp<Layer> relative = weakRelative.promote();
4034 if (!relative) {
4035 continue;
4036 }
4037 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4038 }
4039}
4040
Patrick Williams377c0142022-10-13 17:33:38 +00004041LayerSnapshotGuard::LayerSnapshotGuard(Layer* layer) : mLayer(layer) {
Patrick Williams4da60852022-11-17 17:19:38 +00004042 if (mLayer) {
4043 mLayer->mLayerFE->mSnapshot = std::move(mLayer->mSnapshot);
4044 }
Patrick Williams377c0142022-10-13 17:33:38 +00004045}
4046
4047LayerSnapshotGuard::~LayerSnapshotGuard() {
4048 if (mLayer) {
4049 mLayer->mSnapshot = std::move(mLayer->mLayerFE->mSnapshot);
4050 }
4051}
4052
4053LayerSnapshotGuard::LayerSnapshotGuard(LayerSnapshotGuard&& other) : mLayer(other.mLayer) {
4054 other.mLayer = nullptr;
4055}
4056
4057LayerSnapshotGuard& LayerSnapshotGuard::operator=(LayerSnapshotGuard&& other) {
4058 mLayer = other.mLayer;
4059 other.mLayer = nullptr;
4060 return *this;
4061}
4062
Chavi Weingarten076acac2023-01-19 17:20:43 +00004063void Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
4064 TrustedPresentationListener const& listener) {
4065 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4066 mTrustedPresentationListener = listener;
4067 mTrustedPresentationThresholds = thresholds;
4068 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4069 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4070 mFlinger->mNumTrustedPresentationListeners++;
4071 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4072 mFlinger->mNumTrustedPresentationListeners--;
4073 }
4074}
4075
Mathias Agopian13127d82013-03-05 17:47:11 -08004076// ---------------------------------------------------------------------------
4077
Marin Shalamanov46084422020-10-13 12:33:42 +02004078std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004079 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4080 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004081}
4082
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004083} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004084
4085#if defined(__gl_h_)
4086#error "don't include gl/gl.h in this file"
4087#endif
4088
4089#if defined(__gl2_h_)
4090#error "don't include gl2/gl2.h in this file"
4091#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004092
4093// TODO(b/129481165): remove the #pragma below and fix conversion issues
4094#pragma clang diagnostic pop // ignored "-Wconversion"