blob: 8c484f0039807038ea3c039c2247083695957c7d [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 Naird6913222023-02-01 22:56:21 +0000149 mLegacyLayerFE(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 Laskowski933f8de2023-01-20 13:15:51 -0500199 mFrameTracker.setDisplayRefreshPeriod(args.flinger->mScheduler->getLeaderVsyncPeriod().ns());
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,
liulijuneb489f62022-10-17 22:02:14 +0800231 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000232 }
233 if (!isClone()) {
234 // The original layer and the clone layer share the same texture. Therefore, only one of
235 // the layers, in this case the original layer, needs to handle the deletion. The original
236 // layer and the clone should be removed at the same time so there shouldn't be any issue
237 // with the clone layer trying to use the deleted texture.
238 mFlinger->deleteTextureAsync(mTextureName);
239 }
240 const int32_t layerId = getSequence();
241 mFlinger->mTimeStats->onDestroy(layerId);
242 mFlinger->mFrameTracer->onDestroy(layerId);
243
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000244 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700245 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700246
247 if (mDrawingState.sidebandStream != nullptr) {
248 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
249 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700250 if (mHadClonedChild) {
251 mFlinger->mNumClones--;
252 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000253 if (hasTrustedPresentationListener()) {
254 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000255 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000256 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700257}
258
Mathias Agopian13127d82013-03-05 17:47:11 -0800259// ---------------------------------------------------------------------------
260// callbacks
261// ---------------------------------------------------------------------------
262
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700263void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700264 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700265 return;
266 }
Robert Carr2e102c92018-10-23 12:11:15 -0700267
Robert Carr6a160312021-05-17 12:08:20 -0700268 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700269 if (strongRelative == nullptr) {
270 setZOrderRelativeOf(nullptr);
271 return;
272 }
273
274 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700275 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700276 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800277 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700278 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700279}
280
281void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700282 if (!mRemovedFromDrawingState) {
283 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700284 mFlinger->mScheduler->deregisterLayer(this);
285 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000286 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000287
Ady Abrahamd11bade2022-08-01 16:18:03 -0700288 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700289}
Chia-I Wu38512252017-05-17 14:36:16 -0700290
chaviw68d4dab2020-06-08 15:07:32 -0700291sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000292 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700293 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700294 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700295 }
296 return parent->getRootLayer();
297}
298
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700299void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700300 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
301 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700302 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700303
304 traverse(LayerVector::StateSet::Current, [&](Layer* layer) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700305 layer->removeFromCurrentState();
306 layer->removeRelativeZ(layersInTree);
chaviw68d4dab2020-06-08 15:07:32 -0700307 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700308}
309
chaviw61626f22018-11-15 16:26:27 -0800310void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700311 if (mRemovedFromDrawingState) {
312 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700313 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700314 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700315 }
chaviw61626f22018-11-15 16:26:27 -0800316
317 for (const auto& child : mCurrentChildren) {
318 child->addToCurrentState();
319 }
320}
321
Mathias Agopian13127d82013-03-05 17:47:11 -0800322// ---------------------------------------------------------------------------
323// set-up
324// ---------------------------------------------------------------------------
325
chaviw13fdc492017-06-27 12:40:18 -0700326bool Layer::getPremultipledAlpha() const {
327 return mPremultipliedAlpha;
328}
329
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700330sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800331 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700332 if (mGetHandleCalled) {
333 ALOGE("Get handle called twice" );
334 return nullptr;
335 }
336 mGetHandleCalled = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000337 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800338}
339
340// ---------------------------------------------------------------------------
341// h/w composer set-up
342// ---------------------------------------------------------------------------
343
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700344static Rect reduce(const Rect& win, const Region& exclude) {
345 if (CC_LIKELY(exclude.isEmpty())) {
346 return win;
347 }
348 if (exclude.isRect()) {
349 return win.reduce(exclude.getBounds());
350 }
351 return Region(win).subtract(exclude).getBounds();
352}
353
Dan Stoza80d61162017-12-20 15:57:52 -0800354static FloatRect reduce(const FloatRect& win, const Region& exclude) {
355 if (CC_LIKELY(exclude.isEmpty())) {
356 return win;
357 }
358 // Convert through Rect (by rounding) for lack of FloatRegion
359 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
360}
361
Vishnu Nair4351ad52019-02-11 14:13:02 -0800362Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800363 if (!reduceTransparentRegion) {
364 return Rect{mScreenBounds};
365 }
366
367 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800368 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800369 // Transform to screen space.
370 bounds = t.transform(bounds);
371 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700372}
373
Vishnu Nair4351ad52019-02-11 14:13:02 -0800374FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000375 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800376 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700377}
378
Vishnu Nairf0c28512019-02-08 12:40:28 -0800379FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
380 // Subtract the transparent region and snap to the bounds.
381 return reduce(mBounds, activeTransparentRegion);
382}
383
Chavi Weingarten076acac2023-01-19 17:20:43 +0000384// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000385void Layer::updateTrustedPresentationState(const DisplayDevice* display,
386 const frontend::LayerSnapshot* snapshot,
387 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000388 if (!hasTrustedPresentationListener()) {
389 return;
390 }
391 const bool lastState = mLastComputedTrustedPresentationState;
392 mLastComputedTrustedPresentationState = false;
393
394 if (!leaveState) {
395 const auto outputLayer = findOutputLayerForDisplay(display);
Vishnu Nair781d7252023-01-30 18:16:01 +0000396 if (outputLayer != nullptr && snapshot != nullptr) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000397 mLastComputedTrustedPresentationState =
Vishnu Nair781d7252023-01-30 18:16:01 +0000398 computeTrustedPresentationState(snapshot->geomLayerBounds,
399 snapshot->sourceBounds(),
Chavi Weingarten076acac2023-01-19 17:20:43 +0000400 outputLayer->getState().coveredRegion,
Vishnu Nair781d7252023-01-30 18:16:01 +0000401 snapshot->transformedBounds, snapshot->alpha,
402 snapshot->geomLayerTransform,
Chavi Weingarten076acac2023-01-19 17:20:43 +0000403 mTrustedPresentationThresholds);
404 }
405 }
406 const bool newState = mLastComputedTrustedPresentationState;
407 if (lastState && !newState) {
408 // We were in the trusted presentation state, but now we left it,
409 // emit the callback if needed
410 if (mLastReportedTrustedPresentationState) {
411 mLastReportedTrustedPresentationState = false;
412 mTrustedPresentationListener.invoke(false);
413 }
414 // Reset the timer
415 mEnteredTrustedPresentationStateTime = -1;
416 } else if (!lastState && newState) {
417 // We were not in the trusted presentation state, but we entered it, begin the timer
418 // and make sure this gets called at least once more!
419 mEnteredTrustedPresentationStateTime = time_in_ms;
420 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
421 }
422
423 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
424 if (!mLastReportedTrustedPresentationState && newState &&
425 (time_in_ms - mEnteredTrustedPresentationStateTime >
426 mTrustedPresentationThresholds.stabilityRequirementMs)) {
427 mLastReportedTrustedPresentationState = true;
428 mTrustedPresentationListener.invoke(true);
429 }
430}
431
432/**
433 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
434 * of how the parameters and thresholds are interpreted. The general spirit is
435 * to produce an upper bound on the amount of the buffer which was presented.
436 */
437bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
438 const Region& coveredRegion,
439 const FloatRect& screenBounds, float alpha,
440 const ui::Transform& effectiveTransform,
441 const TrustedPresentationThresholds& thresholds) {
442 if (alpha < thresholds.minAlpha) {
443 return false;
444 }
445 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
446 return false;
447 }
448 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
449 return false;
450 }
451
452 const float sx = effectiveTransform.dsdx();
453 const float sy = effectiveTransform.dsdy();
454 float fractionRendered = std::min(sx * sy, 1.0f);
455
456 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
457 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
458 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
459
460 Rect coveredBounds = coveredRegion.bounds();
461 fractionRendered *= (1 -
462 ((coveredBounds.width() / (float)screenBounds.getWidth()) *
463 coveredBounds.height() / (float)screenBounds.getHeight()));
464
465 if (fractionRendered < thresholds.minFractionRendered) {
466 return false;
467 }
468
469 return true;
470}
471
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700472void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
473 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800474 const State& s(getDrawingState());
475
476 // Calculate effective layer transform
477 mEffectiveTransform = parentTransform * getActiveTransform(s);
478
Garfield Tan2c1782c2022-02-16 15:25:05 -0800479 if (CC_UNLIKELY(!isTransformValid())) {
480 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
481 getDebugName());
482 return;
483 }
484
Vishnu Nair4351ad52019-02-11 14:13:02 -0800485 // Transform parent bounds to layer space
486 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
487
Vishnu Nairc652ff82019-03-15 12:48:54 -0700488 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800489 mSourceBounds = computeSourceBounds(parentBounds);
490
491 // Calculate bounds by croping diplay frame with layer crop and parent bounds
492 FloatRect bounds = mSourceBounds;
493 const Rect layerCrop = getCrop(s);
494 if (!layerCrop.isEmpty()) {
495 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
496 }
497 bounds = bounds.intersect(parentBounds);
498
499 mBounds = bounds;
500 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700501
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700502 // Use the layer's own shadow radius if set. Otherwise get the radius from
503 // parent.
504 if (s.shadowRadius > 0.f) {
505 mEffectiveShadowRadius = s.shadowRadius;
506 } else {
507 mEffectiveShadowRadius = parentShadowRadius;
508 }
509
510 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
511 // don't pass it to its children.
512 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
513
Vishnu Nair4351ad52019-02-11 14:13:02 -0800514 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700515 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800516 }
Vishnu Nairba354102022-08-01 00:14:18 +0000517
518 if (mPotentialCursor) {
519 prepareCursorCompositionState();
520 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800521}
522
Vishnu Nair60356342018-11-13 13:00:45 -0800523Rect Layer::getCroppedBufferSize(const State& s) const {
524 Rect size = getBufferSize(s);
525 Rect crop = getCrop(s);
526 if (!crop.isEmpty() && size.isValid()) {
527 size.intersect(crop, &size);
528 } else if (!crop.isEmpty()) {
529 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700530 }
Vishnu Nair60356342018-11-13 13:00:45 -0800531 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800532}
533
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700534void Layer::setupRoundedCornersCropCoordinates(Rect win,
535 const FloatRect& roundedCornersCrop) const {
536 // Translate win by the rounded corners rect coordinates, to have all values in
537 // layer coordinate space.
538 win.left -= roundedCornersCrop.left;
539 win.right -= roundedCornersCrop.left;
540 win.top -= roundedCornersCrop.top;
541 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700542}
543
Lloyd Piquede196652020-01-22 17:29:58 -0800544void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800545 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800546 const auto alpha = static_cast<float>(getAlpha());
547 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700548 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800549
550 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
551 if (!opaque || alpha != 1.0f) {
552 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
553 : Hwc2::IComposerClient::BlendMode::COVERAGE;
554 }
555
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000556 auto* snapshot = editLayerSnapshot();
557 snapshot->outputFilter = getOutputFilter();
558 snapshot->isVisible = isVisible();
559 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
560 snapshot->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800561
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000562 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800563 contentDirty = false;
564
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000565 snapshot->geomLayerBounds = mBounds;
566 snapshot->geomLayerTransform = getTransform();
567 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
568 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000569 snapshot->localTransform = getActiveTransform(drawingState);
570 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000571 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
572 snapshot->alpha = alpha;
573 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
574 snapshot->blurRegions = drawingState.blurRegions;
575 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800576}
577
Lloyd Piquede196652020-01-22 17:29:58 -0800578void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800579 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000580 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700581
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000582 snapshot->geomBufferSize = getBufferSize(drawingState);
583 snapshot->geomContentCrop = getBufferCrop();
584 snapshot->geomCrop = getCrop(drawingState);
585 snapshot->geomBufferTransform = getBufferTransform();
586 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
587 snapshot->geomUsesSourceCrop = usesSourceCrop();
588 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800589
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000590 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800591 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
592 for (const auto& [key, mandatory] : supportedMetadata) {
593 const auto& genericLayerMetadataCompatibilityMap =
594 mFlinger->getGenericLayerMetadataKeyMap();
595 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
596 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
597 continue;
598 }
599 const uint32_t id = compatIter->second;
600
601 auto it = drawingState.metadata.mMap.find(id);
602 if (it == std::end(drawingState.metadata.mMap)) {
603 continue;
604 }
605
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000606 snapshot->metadata.emplace(key,
607 compositionengine::GenericLayerMetadataEntry{mandatory,
608 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800609 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800610}
David Sodmanba340492018-08-05 21:51:33 -0700611
Lloyd Piquede196652020-01-22 17:29:58 -0800612void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800613 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000614 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800615
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000616 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800617
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000618 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
619 snapshot->dataspace = getDataSpace();
620 snapshot->colorTransform = getColorTransform();
621 snapshot->colorTransformIsIdentity = !hasColorTransform();
622 snapshot->surfaceDamage = surfaceDamageRegion;
623 snapshot->hasProtectedContent = isProtected();
624 snapshot->dimmingEnabled = isDimmingEnabled();
John Reck68796592023-01-25 13:47:12 -0500625 snapshot->currentSdrHdrRatio = getCurrentSdrHdrRatio();
626 snapshot->desiredSdrHdrRatio = getDesiredSdrHdrRatio();
Lloyd Pique688abd42019-02-15 15:42:24 -0800627
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700628 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700629
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000630 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800631
632 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400633 // Rounded corners no longer force client composition, since we may use a
634 // hole punch so that the layer will appear to have rounded corners.
635 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000636 snapshot->stretchEffect.hasEffect()) {
637 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800638 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700639 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000640 snapshot->blurRegions = drawingState.blurRegions;
641 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400642
643 // Layer framerate is used in caching decisions.
644 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
645 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000646 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000647
648 if (hasBufferOrSidebandStream()) {
649 preparePerFrameBufferCompositionState();
650 } else {
651 preparePerFrameEffectsCompositionState();
652 }
653}
654
655void Layer::preparePerFrameBufferCompositionState() {
656 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000657 auto* snapshot = editLayerSnapshot();
658 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
659 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000660 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
661 return;
662 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000663 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000664 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
665 } else {
666 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000667 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
668 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000669 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
670 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
671 }
672
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000673 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000674 snapshot->acquireFence = mBufferInfo.mFence;
675 snapshot->frameNumber = mBufferInfo.mFrameNumber;
676 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000677}
678
679void Layer::preparePerFrameEffectsCompositionState() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000680 auto* snapshot = editLayerSnapshot();
681 snapshot->color = getColor();
682 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000683 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800684}
685
Lloyd Piquede196652020-01-22 17:29:58 -0800686void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800687 const State& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000688 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800689
690 // Apply the layer's transform, followed by the display's global transform
691 // Here we're guaranteed that the layer's transform preserves rects
692 Rect win = getCroppedBufferSize(drawingState);
693 // Subtract the transparent region and snap to the bounds
694 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
695 Rect frame(getTransform().transform(bounds));
696
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000697 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800698}
699
Lloyd Piquea83776c2019-01-29 18:42:32 -0800700const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700701 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800702}
703
Mathias Agopian13127d82013-03-05 17:47:11 -0800704// ---------------------------------------------------------------------------
705// drawing...
706// ---------------------------------------------------------------------------
707
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500708aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
709 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700710 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800711 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500712 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800713 }
714 if (outputLayer->getState().hwc) {
715 return (*outputLayer->getState().hwc).hwcCompositionType;
716 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500717 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800718 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800719}
720
Mathias Agopian13127d82013-03-05 17:47:11 -0800721// ----------------------------------------------------------------------------
722// local state
723// ----------------------------------------------------------------------------
724
David Sodman41fdfc92017-11-06 16:09:56 -0800725bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800726 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700727 if (s.flags & layer_state_t::eLayerSecure) {
728 return true;
729 }
730
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000731 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700732 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700733}
734
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100735void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
736 std::vector<JankData>& jankData) {
737 if (mPendingJankClassifications.empty() ||
738 !mPendingJankClassifications.front()->getJankType()) {
739 return;
740 }
741
742 bool includeJankData = false;
743 for (const auto& handle : handles) {
744 for (const auto& cb : handle->callbackIds) {
745 if (cb.includeJankData) {
746 includeJankData = true;
747 break;
748 }
749 }
750
751 if (includeJankData) {
752 jankData.reserve(mPendingJankClassifications.size());
753 break;
754 }
755 }
756
757 while (!mPendingJankClassifications.empty() &&
758 mPendingJankClassifications.front()->getJankType()) {
759 if (includeJankData) {
760 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
761 mPendingJankClassifications.front();
762 jankData.emplace_back(
763 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
764 }
765 mPendingJankClassifications.pop_front();
766 }
767}
768
Mathias Agopian13127d82013-03-05 17:47:11 -0800769// ----------------------------------------------------------------------------
770// transaction
771// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800772
Marissa Wall61c58622018-07-18 10:12:20 -0700773uint32_t Layer::doTransaction(uint32_t flags) {
774 ATRACE_CALL();
775
Robert Carr0758e5d2021-03-11 22:15:04 -0800776 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700777 mDrawingStateModified = mDrawingState.modified;
778 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700779
Alec Mourib416efd2018-09-06 21:01:59 +0000780 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700781
Robert Carr6a160312021-05-17 12:08:20 -0700782 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800783 // invalidate and recompute the visible regions if needed
784 flags |= Layer::eVisibleRegion;
785 }
786
Robert Carr6a160312021-05-17 12:08:20 -0700787 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800788 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000789 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800790 flags |= eVisibleRegion;
791 this->contentDirty = true;
792
793 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700794 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800795 }
796
Arthur Hung9ed43392022-05-27 06:31:57 +0000797 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
798 mFlinger->mUpdateInputInfo = true;
799 }
800
Robert Carr6a160312021-05-17 12:08:20 -0700801 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800802
Mathias Agopian13127d82013-03-05 17:47:11 -0800803 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800804}
805
Robert Carr6a160312021-05-17 12:08:20 -0700806void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000807 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
808 // bufferSurfaceFrameTX will be presented in latchBuffer.
809 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
810 if (surfaceFrame->getPresentState() != PresentState::Presented) {
811 // With applyPendingStates, we could end up having presented surfaceframes from previous
812 // states
813 surfaceFrame->setPresentState(PresentState::Presented);
814 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
815 }
816 }
Robert Carr6a160312021-05-17 12:08:20 -0700817 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700818}
819
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700820uint32_t Layer::clearTransactionFlags(uint32_t mask) {
821 const auto flags = mTransactionFlags & mask;
822 mTransactionFlags &= ~mask;
823 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800824}
825
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700826void Layer::setTransactionFlags(uint32_t mask) {
827 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800828}
829
Robert Carr1f0a16a2016-10-24 16:27:39 -0700830bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
831 ssize_t idx = mCurrentChildren.indexOf(childLayer);
832 if (idx < 0) {
833 return false;
834 }
835 if (childLayer->setLayer(z)) {
836 mCurrentChildren.removeAt(idx);
837 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800838 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700839 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800840 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700841}
842
Robert Carr503c7042017-09-27 15:06:08 -0700843bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
844 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
845 ssize_t idx = mCurrentChildren.indexOf(childLayer);
846 if (idx < 0) {
847 return false;
848 }
849 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
850 mCurrentChildren.removeAt(idx);
851 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800852 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700853 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800854 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700855}
856
Robert Carrae060832016-11-28 10:51:00 -0800857bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700858 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
859 mDrawingState.sequence++;
860 mDrawingState.z = z;
861 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700862
Robert Carra70e91c2021-06-11 13:59:52 -0700863 mFlinger->mSomeChildrenChanged = true;
864
Robert Carrdb66e622017-04-10 16:55:57 -0700865 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700866 if (mDrawingState.zOrderRelativeOf != nullptr) {
867 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700868 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700869 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700870 }
chaviw606e5cf2019-03-01 10:12:10 -0800871 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700872 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800873 setTransactionFlags(eTransactionNeeded);
874 return true;
875}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700876
Robert Carrdb66e622017-04-10 16:55:57 -0700877void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700878 mDrawingState.zOrderRelatives.remove(relative);
879 mDrawingState.sequence++;
880 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700881 setTransactionFlags(eTransactionNeeded);
882}
883
884void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700885 mDrawingState.zOrderRelatives.add(relative);
886 mDrawingState.modified = true;
887 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700888 setTransactionFlags(eTransactionNeeded);
889}
890
chaviw606e5cf2019-03-01 10:12:10 -0800891void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700892 mDrawingState.zOrderRelativeOf = relativeOf;
893 mDrawingState.sequence++;
894 mDrawingState.modified = true;
895 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700896
chaviw606e5cf2019-03-01 10:12:10 -0800897 setTransactionFlags(eTransactionNeeded);
898}
899
Robert Carr503d2bd2017-12-04 15:49:47 -0800900bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000901 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700902 if (relative == nullptr) {
903 return false;
904 }
905
Robert Carr6a160312021-05-17 12:08:20 -0700906 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
907 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800908 return false;
909 }
910
Robert Carr88b85e12022-03-21 15:47:35 -0700911 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
912 (relative->mDrawingState.zOrderRelativeOf == this)) {
913 ALOGE("Detected relative layer loop between %s and %s",
914 mName.c_str(), relative->mName.c_str());
915 ALOGE("Ignoring new call to set relative layer");
916 return false;
917 }
918
Robert Carra70e91c2021-06-11 13:59:52 -0700919 mFlinger->mSomeChildrenChanged = true;
920
Robert Carr6a160312021-05-17 12:08:20 -0700921 mDrawingState.sequence++;
922 mDrawingState.modified = true;
923 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700924
Robert Carr6a160312021-05-17 12:08:20 -0700925 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700926 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700927 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700928 }
chaviw606e5cf2019-03-01 10:12:10 -0800929 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700930 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700931
932 setTransactionFlags(eTransactionNeeded);
933
934 return true;
935}
936
Winson Chunga30f7c92021-06-29 15:42:56 -0700937bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
938 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
939 mDrawingState.isTrustedOverlay = isTrustedOverlay;
940 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000941 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700942 setTransactionFlags(eTransactionNeeded);
943 return true;
944}
945
946bool Layer::isTrustedOverlay() const {
947 if (getDrawingState().isTrustedOverlay) {
948 return true;
949 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000950 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700951 return (p != nullptr) && p->isTrustedOverlay();
952}
953
Dan Stoza9e56aa02015-11-02 13:00:03 -0800954bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700955 if (mDrawingState.color.a == alpha) return false;
956 mDrawingState.sequence++;
957 mDrawingState.color.a = alpha;
958 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800959 setTransactionFlags(eTransactionNeeded);
960 return true;
961}
chaviw13fdc492017-06-27 12:40:18 -0700962
Valerie Haudd0b7572019-01-29 14:59:27 -0800963bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700964 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700965 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800966 }
Robert Carr6a160312021-05-17 12:08:20 -0700967 mDrawingState.sequence++;
968 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800969 setTransactionFlags(eTransactionNeeded);
970
Robert Carr6a160312021-05-17 12:08:20 -0700971 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -0800972 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -0800973 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700974 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -0700975 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800976 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700977 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -0700978
Valerie Haudd0b7572019-01-29 14:59:27 -0800979 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -0700980 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -0800981 mFlinger->mLayersAdded = true;
982 // set up SF to handle added color layer
983 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -0700984 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -0800985 }
986 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -0700987 } else if (mDrawingState.bgColorLayer && alpha == 0) {
988 mDrawingState.bgColorLayer->reparent(nullptr);
989 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -0800990 return true;
991 }
992
Robert Carr6a160312021-05-17 12:08:20 -0700993 mDrawingState.bgColorLayer->setColor(color);
994 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
995 mDrawingState.bgColorLayer->setAlpha(alpha);
996 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -0800997
chaviw13fdc492017-06-27 12:40:18 -0700998 return true;
999}
1000
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001001bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001002 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001003
Robert Carr6a160312021-05-17 12:08:20 -07001004 mDrawingState.sequence++;
1005 mDrawingState.cornerRadius = cornerRadius;
1006 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001007 setTransactionFlags(eTransactionNeeded);
1008 return true;
1009}
1010
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001011bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001012 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001013 // If we start or stop drawing blur then the layer's visibility state may change so increment
1014 // the magic sequence number.
1015 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1016 mDrawingState.sequence++;
1017 }
Robert Carr6a160312021-05-17 12:08:20 -07001018 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1019 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001020 setTransactionFlags(eTransactionNeeded);
1021 return true;
1022}
Marissa Wall61c58622018-07-18 10:12:20 -07001023
Mathias Agopian13127d82013-03-05 17:47:11 -08001024bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001025 mDrawingState.sequence++;
1026 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001027 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001028 setTransactionFlags(eTransactionNeeded);
1029 return true;
1030}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001031
Lucas Dupinc3800b82020-10-02 16:24:48 -07001032bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001033 // If we start or stop drawing blur then the layer's visibility state may change so increment
1034 // the magic sequence number.
1035 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1036 mDrawingState.sequence++;
1037 }
Robert Carr6a160312021-05-17 12:08:20 -07001038 mDrawingState.blurRegions = blurRegions;
1039 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001040 setTransactionFlags(eTransactionNeeded);
1041 return true;
1042}
1043
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001044bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001045 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1046 if (mDrawingState.flags == newFlags) return false;
1047 mDrawingState.sequence++;
1048 mDrawingState.flags = newFlags;
1049 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001050 setTransactionFlags(eTransactionNeeded);
1051 return true;
1052}
Robert Carr99e27f02016-06-16 15:18:02 -07001053
chaviw25714502021-02-11 10:01:08 -08001054bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001055 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001056 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001057 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001058
Robert Carr6a160312021-05-17 12:08:20 -07001059 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001060 setTransactionFlags(eTransactionNeeded);
1061 return true;
1062}
Robert Carr8d5227b2017-03-16 15:41:03 -07001063
Evan Roskyef876c92019-01-25 17:46:06 -08001064bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001065 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1066 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001067 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001068 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001069}
1070
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001071bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001072 if (mDrawingState.layerStack == layerStack) return false;
1073 mDrawingState.sequence++;
1074 mDrawingState.layerStack = layerStack;
1075 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001076 setTransactionFlags(eTransactionNeeded);
1077 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001078}
1079
Peiyong Linc502cb72019-03-01 15:00:23 -08001080bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001081 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001082 return false;
1083 }
Robert Carr6a160312021-05-17 12:08:20 -07001084 mDrawingState.sequence++;
1085 mDrawingState.colorSpaceAgnostic = agnostic;
1086 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001087 setTransactionFlags(eTransactionNeeded);
1088 return true;
1089}
1090
Sally Qi81d95e62022-03-21 19:41:33 -07001091bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1092 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1093
1094 mDrawingState.sequence++;
1095 mDrawingState.dimmingEnabled = dimmingEnabled;
1096 mDrawingState.modified = true;
1097 setTransactionFlags(eTransactionNeeded);
1098 return true;
1099}
1100
Ana Krulecc84d09b2019-11-02 23:10:29 +01001101bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001102 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1103 mDrawingState.frameRateSelectionPriority = priority;
1104 mDrawingState.sequence++;
1105 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001106 setTransactionFlags(eTransactionNeeded);
1107 return true;
1108}
1109
1110int32_t Layer::getFrameRateSelectionPriority() const {
1111 // Check if layer has priority set.
1112 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1113 return mDrawingState.frameRateSelectionPriority;
1114 }
1115 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001116 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001117 if (parent != nullptr) {
1118 return parent->getFrameRateSelectionPriority();
1119 }
1120
1121 return Layer::PRIORITY_UNSET;
1122}
1123
Andy Labrada096227e2022-06-15 16:58:11 +00001124bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1125 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1126 mDrawingState.defaultFrameRateCompatibility = compatibility;
1127 mDrawingState.modified = true;
1128 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1129 setTransactionFlags(eTransactionNeeded);
1130 return true;
1131}
1132
1133scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1134 return mDrawingState.defaultFrameRateCompatibility;
1135}
1136
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001137bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1138 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1139};
1140
Vishnu Nair73908d12022-10-24 21:46:42 -07001141ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1142 bool useDrawing = state == LayerVector::StateSet::Drawing;
1143 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1144 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001145 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001146 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001147 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001148}
1149
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001150bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001151 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001152 return false;
1153 }
1154
Robert Carr6a160312021-05-17 12:08:20 -07001155 mDrawingState.sequence++;
1156 mDrawingState.shadowRadius = shadowRadius;
1157 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001158 setTransactionFlags(eTransactionNeeded);
1159 return true;
1160}
1161
Vishnu Nair6213bd92020-05-08 17:42:25 -07001162bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001163 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001164 return false;
1165 }
1166
Robert Carr6a160312021-05-17 12:08:20 -07001167 mDrawingState.sequence++;
1168 mDrawingState.fixedTransformHint = fixedTransformHint;
1169 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001170 setTransactionFlags(eTransactionNeeded);
1171 return true;
1172}
1173
John Reckcdb4ed72021-02-04 13:39:33 -05001174bool Layer::setStretchEffect(const StretchEffect& effect) {
1175 StretchEffect temp = effect;
1176 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001177 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001178 return false;
1179 }
Robert Carr6a160312021-05-17 12:08:20 -07001180 mDrawingState.sequence++;
1181 mDrawingState.stretchEffect = temp;
1182 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001183 setTransactionFlags(eTransactionNeeded);
1184 return true;
1185}
1186
John Reckc00c6692021-02-16 11:37:33 -05001187StretchEffect Layer::getStretchEffect() const {
1188 if (mDrawingState.stretchEffect.hasEffect()) {
1189 return mDrawingState.stretchEffect;
1190 }
1191
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001192 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001193 if (parent != nullptr) {
1194 auto effect = parent->getStretchEffect();
1195 if (effect.hasEffect()) {
1196 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1197 return effect;
1198 }
1199 }
1200 return StretchEffect{};
1201}
1202
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001203bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1204 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001205 return false;
1206 }
1207 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001208 mBorderWidth = width;
1209 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001210 return true;
1211}
1212
1213bool Layer::isBorderEnabled() {
1214 return mBorderEnabled;
1215}
1216
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001217float Layer::getBorderWidth() {
1218 return mBorderWidth;
1219}
1220
1221const half4& Layer::getBorderColor() {
1222 return mBorderColor;
1223}
1224
Ady Abrahama850c182021-08-04 13:04:37 -07001225bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1226 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1227 const auto frameRate = [&] {
1228 if (mDrawingState.frameRate.rate.isValid() ||
1229 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1230 return mDrawingState.frameRate;
1231 }
1232
1233 return parentFrameRate;
1234 }();
1235
1236 *transactionNeeded |= setFrameRateForLayerTree(frameRate);
1237
1238 // The frame rate is propagated to the children
1239 bool childrenHaveFrameRate = false;
1240 for (const sp<Layer>& child : mCurrentChildren) {
1241 childrenHaveFrameRate |=
1242 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1243 }
1244
1245 // If we don't have a valid frame rate, but the children do, we set this
1246 // layer as NoVote to allow the children to control the refresh rate
1247 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1248 childrenHaveFrameRate) {
1249 *transactionNeeded |=
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001250 setFrameRateForLayerTree(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001251 }
1252
1253 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1254 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001255 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001256 const auto layerVotedWithDefaultCompatibility =
1257 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1258 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1259 const auto layerVotedWithExactCompatibility =
1260 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1261 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1262 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1263}
1264
Ady Abraham60e42ea2020-03-09 19:17:31 -07001265void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001266 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001267 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001268 while (auto parent = layer->getParent()) {
1269 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001270 }
Ady Abrahama850c182021-08-04 13:04:37 -07001271 return layer;
1272 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001273
Ady Abraham60e42ea2020-03-09 19:17:31 -07001274 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001275 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001276
Ady Abrahama850c182021-08-04 13:04:37 -07001277 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001278 if (transactionNeeded) {
1279 mFlinger->setTransactionFlags(eTraversalNeeded);
1280 }
1281}
1282
Ady Abraham71c437d2020-01-31 15:56:57 -08001283bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001284 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001285 return false;
1286 }
1287
Robert Carr6a160312021-05-17 12:08:20 -07001288 mDrawingState.sequence++;
1289 mDrawingState.frameRate = frameRate;
1290 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001291
1292 updateTreeHasFrameRateVote();
1293
Steven Thomas3172e202020-01-06 19:25:30 -08001294 setTransactionFlags(eTransactionNeeded);
1295 return true;
1296}
1297
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001298void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1299 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001300 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001301
1302 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1303 // there are two transactions with the same token, the first one without a buffer and the
1304 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1305 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001306 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1307 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001308 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001309 mDrawingState.bufferSurfaceFrameTX = it->second;
1310 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1311 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1312 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001313 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001314 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001315 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1316 }
1317}
1318
1319void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1320 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001321 mDrawingState.frameTimelineInfo = info;
1322 mDrawingState.postTime = postTime;
1323 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001324 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001325
Robert Carr6a160312021-05-17 12:08:20 -07001326 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001327 bufferSurfaceFrameTX != nullptr) {
1328 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1329 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1330 // being used for BufferSurfaceFrame, don't create a new one.
1331 return;
1332 }
1333 }
1334 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1335 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1336 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001337 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1338 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001339 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001340 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001341 } else {
1342 if (it->second->getPresentState() == PresentState::Presented) {
1343 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1344 // have been from previous vsync.
1345 it->second = createSurfaceFrameForTransaction(info, postTime);
1346 }
1347 }
1348}
1349
1350void Layer::addSurfaceFrameDroppedForBuffer(
1351 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001352 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001353 surfaceFrame->setPresentState(PresentState::Dropped);
1354 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1355}
1356
1357void Layer::addSurfaceFramePresentedForBuffer(
1358 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1359 nsecs_t currentLatchTime) {
1360 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1361 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1362 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1363 mLastLatchTime = currentLatchTime;
1364}
1365
1366std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1367 const FrameTimelineInfo& info, nsecs_t postTime) {
1368 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001369 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1370 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001371 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001372 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001373 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001374 // For Transactions, the post time is considered to be both queue and acquire fence time.
1375 surfaceFrame->setActualQueueTime(postTime);
1376 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001377 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1378 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001379 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001380 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001381 onSurfaceFrameCreated(surfaceFrame);
1382 return surfaceFrame;
1383}
1384
1385std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1386 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1387 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001388 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001389 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001390 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001391 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001392 // For buffers, acquire fence time will set during latch.
1393 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001394 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1395 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001396 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001397 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001398 onSurfaceFrameCreated(surfaceFrame);
1399 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001400}
1401
Ady Abrahama850c182021-08-04 13:04:37 -07001402bool Layer::setFrameRateForLayerTree(FrameRate frameRate) {
1403 if (mDrawingState.frameRateForLayerTree == frameRate) {
1404 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001405 }
1406
Ady Abrahama850c182021-08-04 13:04:37 -07001407 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001408
Ady Abrahama850c182021-08-04 13:04:37 -07001409 // TODO(b/195668952): we probably don't need to dirty visible regions here
1410 // or even store frameRateForLayerTree in mDrawingState
1411 mDrawingState.sequence++;
1412 mDrawingState.modified = true;
1413 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001414
Dominik Laskowski068173d2021-08-11 17:22:59 -07001415 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
1416 mFlinger->mScheduler->recordLayerHistory(this, systemTime(), LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001417
1418 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001419}
1420
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001421Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1422 return getDrawingState().frameRateForLayerTree;
1423}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001424
Robert Carr1f0a16a2016-10-24 16:27:39 -07001425bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001426 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001427 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001428 if (parent != nullptr && parent->isHiddenByPolicy()) {
1429 return true;
1430 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001431 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1432 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1433 if (zOrderRelativeOf != nullptr) {
1434 if (zOrderRelativeOf->isHiddenByPolicy()) {
1435 return true;
1436 }
1437 }
1438 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001439 if (CC_UNLIKELY(!isTransformValid())) {
1440 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1441 return true;
1442 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001443 return s.flags & layer_state_t::eLayerHidden;
1444}
1445
David Sodman41fdfc92017-11-06 16:09:56 -08001446uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001447 // TODO: should we do something special if mSecure is set?
1448 if (mProtectedByApp) {
1449 // need a hardware-protected path to external video sink
1450 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001451 }
Riley Andrews03414a12014-07-01 14:22:59 -07001452 if (mPotentialCursor) {
1453 usage |= GraphicBuffer::USAGE_CURSOR;
1454 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001455 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001456 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001457}
1458
Vishnu Nair71fcf912022-10-18 09:14:20 -07001459void Layer::skipReportingTransformHint() {
1460 mSkipReportingTransformHint = true;
1461}
1462
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001463void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1464 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1465 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001466 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001467
Vishnu Nair6213bd92020-05-08 17:42:25 -07001468 setTransformHint(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001469}
1470
Mathias Agopian13127d82013-03-05 17:47:11 -08001471// ----------------------------------------------------------------------------
1472// debugging
1473// ----------------------------------------------------------------------------
1474
Marissa Wall61c58622018-07-18 10:12:20 -07001475// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001476gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001477 using namespace std::string_literals;
1478
Huihong Luo05539a12022-02-23 10:29:40 -08001479 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001480 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001481 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001482 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001483 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001484 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001485
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001486 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001487 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001488 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001489 info.mX = ds.transform.tx();
1490 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001491 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001492 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001493 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001494 info.mFlags = ds.flags;
1495 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001496 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001497 info.mMatrix[0][0] = ds.transform[0][0];
1498 info.mMatrix[0][1] = ds.transform[0][1];
1499 info.mMatrix[1][0] = ds.transform[1][0];
1500 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001501 {
chaviwd62d3062019-09-04 14:48:02 -07001502 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001503 if (buffer != 0) {
1504 info.mActiveBufferWidth = buffer->getWidth();
1505 info.mActiveBufferHeight = buffer->getHeight();
1506 info.mActiveBufferStride = buffer->getStride();
1507 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001508 } else {
1509 info.mActiveBufferWidth = 0;
1510 info.mActiveBufferHeight = 0;
1511 info.mActiveBufferStride = 0;
1512 info.mActiveBufferFormat = 0;
1513 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001514 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001515 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001516 info.mIsOpaque = isOpaque(ds);
1517 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001518 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001519 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001520}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001521
Yiwei Zhang5434a782018-12-05 18:06:32 -08001522void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001523 result.append(kDumpTableRowLength, '-');
1524 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001525 result.append(" Layer name\n");
1526 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001527 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001528 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001529 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001530 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001531 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001532 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1533 result.append(kDumpTableRowLength, '-');
1534 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001535}
1536
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001537void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1538 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001539 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001540 return;
1541 }
1542
Yiwei Zhang5434a782018-12-05 18:06:32 -08001543 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001544 if (mName.length() > 77) {
1545 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001546 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001547 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001548 shortened.append(mName, mName.length() - 36);
1549 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001550 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001551 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001552 }
1553
Yiwei Zhang5434a782018-12-05 18:06:32 -08001554 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001555
Alec Mourib416efd2018-09-06 21:01:59 +00001556 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001557 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001558
Chia-I Wu1e043612018-03-01 09:45:09 -08001559 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001560 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001561 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001562 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001563 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001564 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001565 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001566 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1567 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001568 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001569 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001570 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001571 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001572 const auto frameRate = getFrameRateForLayerTree();
1573 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1574 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001575 ftl::enum_string(frameRate.type).c_str(),
1576 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001577 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001578 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001579 }
Dan Stozae22aec72016-08-01 13:20:59 -07001580
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001581 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1582 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1583
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001584 result.append(kDumpTableRowLength, '-');
1585 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001586}
Dan Stozae22aec72016-08-01 13:20:59 -07001587
Yiwei Zhang5434a782018-12-05 18:06:32 -08001588void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001589 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001590}
1591
Svetoslavd85084b2014-03-20 10:28:31 -07001592void Layer::clearFrameStats() {
1593 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001594}
1595
Jamie Gennis6547ff42013-07-16 20:12:42 -07001596void Layer::logFrameStats() {
1597 mFrameTracker.logAndResetStats(mName);
1598}
1599
Svetoslavd85084b2014-03-20 10:28:31 -07001600void Layer::getFrameStats(FrameStats* outStats) const {
1601 mFrameTracker.getStats(outStats);
1602}
1603
Vishnu Nair76554eb2022-12-09 03:38:36 +00001604void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1605 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
1606 StringAppendF(&result, "Layer %s%s pid:%d uid:%d\n", getName().c_str(), hasBuffer.c_str(),
Vishnu Naircb8be502022-10-12 19:03:23 +00001607 mOwnerPid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001608}
1609
Brian Anderson5ea5e592016-12-01 16:54:33 -08001610void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001611 const int32_t layerId = getSequence();
1612 mFlinger->mTimeStats->onDestroy(layerId);
1613 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001614}
1615
Chia-I Wu98f1c102017-05-30 14:54:08 -07001616size_t Layer::getChildrenCount() const {
1617 size_t count = 0;
1618 for (const sp<Layer>& child : mCurrentChildren) {
1619 count += 1 + child->getChildrenCount();
1620 }
1621 return count;
1622}
1623
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001624void Layer::setGameModeForTree(GameMode gameMode) {
1625 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001626 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1627 gameMode =
1628 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001629 }
1630 setGameMode(gameMode);
1631 for (const sp<Layer>& child : mCurrentChildren) {
1632 child->setGameModeForTree(gameMode);
1633 }
1634}
1635
Robert Carr1f0a16a2016-10-24 16:27:39 -07001636void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001637 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001638 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001639
Robert Carr1f0a16a2016-10-24 16:27:39 -07001640 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001641 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001642 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001643 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001644}
1645
1646ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001647 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001648 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001649
Robert Carr1323c952019-01-28 18:13:27 -08001650 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001651 const auto removeResult = mCurrentChildren.remove(layer);
1652
1653 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001654 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001655 layer->updateTreeHasFrameRateVote();
1656
1657 return removeResult;
1658}
1659
Robert Carr15eae092018-03-23 13:43:53 -07001660void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001661 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001662 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001663 const float parentShadowRadius =
1664 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001665 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001666 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001667 }
1668}
1669
chaviwf1961f72017-09-18 16:41:07 -07001670bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001671 sp<Layer> newParent;
1672 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001673 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001674 if (newParent == nullptr) {
1675 ALOGE("Unable to promote Layer handle");
1676 return false;
1677 }
1678 if (newParent == this) {
1679 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1680 return false;
1681 }
1682 }
1683
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001684 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001685 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001686 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001687 }
1688
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001689 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001690 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001691 if (!newParent->isRemovedFromCurrentState()) {
1692 addToCurrentState();
1693 } else {
1694 onRemovedFromCurrentState();
1695 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001696 } else {
1697 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001698 }
1699
chaviw06178942017-07-27 10:25:59 -07001700 return true;
1701}
1702
Peiyong Lind3788632018-09-18 16:01:31 -07001703bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001704 static const mat4 identityMatrix = mat4();
1705
Robert Carr6a160312021-05-17 12:08:20 -07001706 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001707 return false;
1708 }
Robert Carr6a160312021-05-17 12:08:20 -07001709 ++mDrawingState.sequence;
1710 mDrawingState.colorTransform = matrix;
1711 mDrawingState.hasColorTransform = matrix != identityMatrix;
1712 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001713 setTransactionFlags(eTransactionNeeded);
1714 return true;
1715}
1716
chaviwf66724d2018-11-28 16:35:21 -08001717mat4 Layer::getColorTransform() const {
1718 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001719 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001720 colorTransform = parent->getColorTransform() * colorTransform;
1721 }
1722 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001723}
1724
1725bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001726 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001727 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001728 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1729 }
1730 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001731}
1732
Chia-I Wu11481472018-05-04 10:43:19 -07001733bool Layer::isLegacyDataSpace() const {
1734 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001735 return !(getDataSpace() &
1736 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1737 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001738}
1739
Robert Carr1f0a16a2016-10-24 16:27:39 -07001740void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001741 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001742}
1743
Robert Carr6a160312021-05-17 12:08:20 -07001744int32_t Layer::getZ(LayerVector::StateSet) const {
1745 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001746}
1747
Robert Carr1c5481e2019-07-01 14:42:27 -07001748bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001749 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001750 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001751 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001752}
1753
David Sodman41fdfc92017-11-06 16:09:56 -08001754__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001755 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001756 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1757 "makeTraversalList received invalid stateSet");
1758 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1759 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001760 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001761
Robert Carr29abff82017-12-04 13:51:20 -08001762 if (state.zOrderRelatives.size() == 0) {
1763 *outSkipRelativeZUsers = true;
1764 return children;
1765 }
1766
chaviwfd462612018-05-31 16:11:27 -07001767 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001768 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001769 sp<Layer> strongRelative = weakRelative.promote();
1770 if (strongRelative != nullptr) {
1771 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001772 }
1773 }
1774
Dan Stoza412903f2017-04-27 13:42:17 -07001775 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001776 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001777 continue;
1778 }
Robert Carrdb66e622017-04-10 16:55:57 -07001779 traverse.add(child);
1780 }
1781
1782 return traverse;
1783}
1784
Robert Carr1f0a16a2016-10-24 16:27:39 -07001785/**
Robert Carrdb66e622017-04-10 16:55:57 -07001786 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001787 */
Dan Stoza412903f2017-04-27 13:42:17 -07001788void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001789 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1790 // produce a new list for traversing, including our relatives, and not including our children
1791 // who are relatives of another surface. In the case that there are no relative Z,
1792 // makeTraversalList returns our children directly to avoid significant overhead.
1793 // However in this case we need to take the responsibility for filtering children which
1794 // are relatives of another surface here.
1795 bool skipRelativeZUsers = false;
1796 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001797
Robert Carr1f0a16a2016-10-24 16:27:39 -07001798 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001799 for (; i < list.size(); i++) {
1800 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001801 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1802 continue;
1803 }
1804
chaviw301b1d82019-11-06 13:15:09 -08001805 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001806 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001807 }
Dan Stoza412903f2017-04-27 13:42:17 -07001808 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001809 }
Robert Carr29abff82017-12-04 13:51:20 -08001810
Dan Stoza412903f2017-04-27 13:42:17 -07001811 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001812 for (; i < list.size(); i++) {
1813 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001814
Robert Carr29abff82017-12-04 13:51:20 -08001815 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1816 continue;
1817 }
Dan Stoza412903f2017-04-27 13:42:17 -07001818 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001819 }
1820}
1821
1822/**
Robert Carrdb66e622017-04-10 16:55:57 -07001823 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001824 */
Dan Stoza412903f2017-04-27 13:42:17 -07001825void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1826 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001827 // See traverseInZOrder for documentation.
1828 bool skipRelativeZUsers = false;
1829 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001830
Robert Carr1f0a16a2016-10-24 16:27:39 -07001831 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001832 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001833 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001834
1835 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1836 continue;
1837 }
1838
chaviw301b1d82019-11-06 13:15:09 -08001839 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001840 break;
1841 }
Dan Stoza412903f2017-04-27 13:42:17 -07001842 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001843 }
Dan Stoza412903f2017-04-27 13:42:17 -07001844 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001845 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001846 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001847
1848 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1849 continue;
1850 }
1851
Dan Stoza412903f2017-04-27 13:42:17 -07001852 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001853 }
1854}
1855
Edgar Arriaga844fa672020-01-16 14:21:42 -08001856void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1857 visitor(this);
1858 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001859 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001860 for (const sp<Layer>& child : children) {
1861 child->traverse(state, visitor);
1862 }
1863}
1864
chaviw4b129c22018-04-09 16:19:43 -07001865LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1866 const std::vector<Layer*>& layersInTree) {
1867 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1868 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001869 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1870 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001871 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001872
chaviwfd462612018-05-31 16:11:27 -07001873 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001874 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1875 sp<Layer> strongRelative = weakRelative.promote();
1876 // Only add relative layers that are also descendents of the top most parent of the tree.
1877 // If a relative layer is not a descendent, then it should be ignored.
1878 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1879 traverse.add(strongRelative);
1880 }
1881 }
1882
1883 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001884 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001885 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1886 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1887 // the child here since it won't be added later as a relative.
1888 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1889 childState.zOrderRelativeOf.promote().get())) {
1890 continue;
1891 }
1892 traverse.add(child);
1893 }
1894
1895 return traverse;
1896}
1897
1898void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1899 LayerVector::StateSet stateSet,
1900 const LayerVector::Visitor& visitor) {
1901 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001902
1903 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001904 for (; i < list.size(); i++) {
1905 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001906 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001907 break;
1908 }
chaviw4b129c22018-04-09 16:19:43 -07001909 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001910 }
chaviw4b129c22018-04-09 16:19:43 -07001911
chaviwa76b2712017-09-20 12:02:26 -07001912 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001913 for (; i < list.size(); i++) {
1914 const auto& relative = list[i];
1915 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001916 }
1917}
1918
chaviw4b129c22018-04-09 16:19:43 -07001919std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1920 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1921 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1922
1923 std::vector<Layer*> layersInTree = {this};
1924 for (size_t i = 0; i < children.size(); i++) {
1925 const auto& child = children[i];
1926 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1927 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1928 }
1929
1930 return layersInTree;
1931}
1932
1933void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1934 const LayerVector::Visitor& visitor) {
1935 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1936 std::sort(layersInTree.begin(), layersInTree.end());
1937 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1938}
1939
Peiyong Linefefaac2018-08-17 12:27:51 -07001940ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001941 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001942}
1943
Garfield Tan2c1782c2022-02-16 15:25:05 -08001944bool Layer::isTransformValid() const {
1945 float transformDet = getTransform().det();
1946 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1947}
1948
chaviw13fdc492017-06-27 12:40:18 -07001949half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001950 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001951
chaviw13fdc492017-06-27 12:40:18 -07001952 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1953 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07001954}
Robert Carr6452f122017-03-21 10:41:29 -07001955
Vishnu Nair6213bd92020-05-08 17:42:25 -07001956ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07001957 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001958 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
1959 return fixedTransformHint;
1960 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001961 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07001962 if (!p) return fixedTransformHint;
1963 return p->getFixedTransformHint();
1964}
1965
chaviw13fdc492017-06-27 12:40:18 -07001966half4 Layer::getColor() const {
1967 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001968 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07001969}
Robert Carr6452f122017-03-21 10:41:29 -07001970
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001971int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00001972 if (getDrawingState().backgroundBlurRadius == 0) {
1973 return 0;
1974 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01001975
Vishnu Nair29810f72022-07-01 16:38:41 +00001976 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01001977 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1978 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001979}
1980
Galia Peychevae0acf382021-04-12 21:22:34 +02001981const std::vector<BlurRegion> Layer::getBlurRegions() const {
1982 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02001983 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02001984 for (auto& region : regionsCopy) {
1985 region.alpha = region.alpha * layerAlpha;
1986 }
1987 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001988}
1989
Vishnu Naire14c6b32022-08-06 04:20:15 +00001990RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001991 // Get parent settings
1992 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001993 const auto& parent = mDrawingParent.promote();
1994 if (parent != nullptr) {
1995 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001996 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001997 ui::Transform t = getActiveTransform(getDrawingState());
1998 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001999 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002000 parentSettings.radius.x *= t.getScaleX();
2001 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002002 }
2003 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002004
2005 // Get layer settings
2006 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002007 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002008 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002009 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002010
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002011 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002012 // If the parent and the layer have rounded corner settings, use the parent settings if the
2013 // parent crop is entirely inside the layer crop.
2014 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2015 if (parentSettings.cropRect.left > layerCropRect.left &&
2016 parentSettings.cropRect.top > layerCropRect.top &&
2017 parentSettings.cropRect.right < layerCropRect.right &&
2018 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2019 return parentSettings;
2020 } else {
2021 return layerSettings;
2022 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002023 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002024 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002025 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002026 return parentSettings;
2027 }
2028 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002029}
2030
Robert Carr88b85e12022-03-21 15:47:35 -07002031bool Layer::findInHierarchy(const sp<Layer>& l) {
2032 if (l == this) {
2033 return true;
2034 }
2035 for (auto& child : mDrawingChildren) {
2036 if (child->findInHierarchy(l)) {
2037 return true;
2038 }
2039 }
2040 return false;
2041}
2042
Robert Carr1f0a16a2016-10-24 16:27:39 -07002043void Layer::commitChildList() {
2044 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2045 const auto& child = mCurrentChildren[i];
2046 child->commitChildList();
2047 }
2048 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002049 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002050 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2051 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2052 if (zOrderRelativeOf == nullptr) return;
2053 if (findInHierarchy(zOrderRelativeOf)) {
2054 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2055 zOrderRelativeOf->mName.c_str());
2056 ALOGE("Severing rel Z loop, potentially dangerous");
2057 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002058 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002059 }
2060 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002061}
2062
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002063
chaviw3277faf2021-05-19 16:45:23 -05002064void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002065 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002066 mDrawingState.touchableRegionCrop =
2067 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002068 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002069 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002070 setTransactionFlags(eTransactionNeeded);
2071}
2072
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002073LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002074 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002075 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002076 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2077
Vishnu Nair00b90132021-11-05 14:03:40 -07002078 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002079 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2080
Vishnu Nair60db8c02020-04-02 11:55:16 -07002081 // Only populate for the primary display.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002082 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -05002083 const auto compositionType = getCompositionType(*display);
Vishnu Nair60db8c02020-04-02 11:55:16 -07002084 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002085 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2086 [&]() { return layerProto->mutable_visible_region(); });
Vishnu Nair60db8c02020-04-02 11:55:16 -07002087 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08002088 }
2089
chaviw08f3cb22020-01-13 13:17:21 -08002090 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002091 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002092 }
chaviw6d89e2d2020-01-14 14:42:01 -08002093
2094 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002095}
2096
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002097void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002098 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002099 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002100 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002101 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002102 [&]() { return layerInfo->mutable_active_buffer(); });
2103 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2104 layerInfo->mutable_buffer_transform());
2105 }
2106 layerInfo->set_invalidate(contentDirty);
2107 layerInfo->set_is_protected(isProtected());
2108 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2109 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002110 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002111 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002112 layerInfo->set_corner_radius(
2113 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002114 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2115 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2116 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2117 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2118 [&]() { return layerInfo->mutable_position(); });
2119 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002120 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2121 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002122
Vishnu Nair00b90132021-11-05 14:03:40 -07002123 if (hasColorTransform()) {
2124 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002125 }
2126
Vishnu Nair60db8c02020-04-02 11:55:16 -07002127 LayerProtoHelper::writeToProto(mSourceBounds,
2128 [&]() { return layerInfo->mutable_source_bounds(); });
2129 LayerProtoHelper::writeToProto(mScreenBounds,
2130 [&]() { return layerInfo->mutable_screen_bounds(); });
2131 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2132 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2133 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002134}
2135
2136void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002137 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002138 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2139 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002140 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002141
chaviw766c9c52021-02-10 17:36:47 -08002142 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002143
Vishnu Nair00b90132021-11-05 14:03:40 -07002144 layerInfo->set_id(sequence);
2145 layerInfo->set_name(getName().c_str());
2146 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002147
Vishnu Nair00b90132021-11-05 14:03:40 -07002148 for (const auto& child : children) {
2149 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002150 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002151
Vishnu Nair00b90132021-11-05 14:03:40 -07002152 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2153 sp<Layer> strongRelative = weakRelative.promote();
2154 if (strongRelative != nullptr) {
2155 layerInfo->add_relatives(strongRelative->sequence);
2156 }
2157 }
2158
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002159 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002160 [&]() { return layerInfo->mutable_transparent_region(); });
2161
2162 layerInfo->set_layer_stack(getLayerStack().id);
2163 layerInfo->set_z(state.z);
2164
2165 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2166 return layerInfo->mutable_requested_position();
2167 });
2168
Vishnu Nair00b90132021-11-05 14:03:40 -07002169 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2170
2171 layerInfo->set_is_opaque(isOpaque(state));
2172
2173 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2174 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2175 LayerProtoHelper::writeToProto(state.color,
2176 [&]() { return layerInfo->mutable_requested_color(); });
2177 layerInfo->set_flags(state.flags);
2178
2179 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2180 layerInfo->mutable_requested_transform());
2181
2182 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2183 if (parent != nullptr) {
2184 layerInfo->set_parent(parent->sequence);
2185 } else {
2186 layerInfo->set_parent(-1);
2187 }
2188
2189 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2190 if (zOrderRelativeOf != nullptr) {
2191 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2192 } else {
2193 layerInfo->set_z_order_relative_of(-1);
2194 }
2195
2196 layerInfo->set_is_relative_of(state.isRelativeOf);
2197
2198 layerInfo->set_owner_uid(mOwnerUid);
2199
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002200 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002201 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002202 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002203 info = fillInputInfo(
2204 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002205 } else {
2206 info = state.inputInfo;
2207 }
2208
2209 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002210 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002211 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002212
Vishnu Nair00b90132021-11-05 14:03:40 -07002213 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002214 auto protoMap = layerInfo->mutable_metadata();
2215 for (const auto& entry : state.metadata.mMap) {
2216 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2217 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002218 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002219
2220 LayerProtoHelper::writeToProto(state.destinationFrame,
2221 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002222}
2223
Robert Carr2e102c92018-10-23 12:11:15 -07002224bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002225 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002226}
2227
Prabir Pradhan33da9462022-06-14 14:55:57 +00002228// Applies the given transform to the region, while protecting against overflows caused by any
2229// offsets. If applying the offset in the transform to any of the Rects in the region would result
2230// in an overflow, they are not added to the output Region.
2231static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2232 const std::string& debugWindowName) {
2233 // Round the translation using the same rounding strategy used by ui::Transform.
2234 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2235 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2236
2237 ui::Transform transformWithoutOffset = t;
2238 transformWithoutOffset.set(0.f, 0.f);
2239
2240 const Region transformed = transformWithoutOffset.transform(r);
2241
2242 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2243 Region ret;
2244 for (const auto& rect : transformed) {
2245 Rect newRect;
2246 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2247 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2248 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2249 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2250 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2251 debugWindowName.c_str());
2252 continue;
2253 }
2254 ret.orSelf(newRect);
2255 }
2256 return ret;
2257}
2258
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002259void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
2260 Rect tmpBounds = getInputBounds();
2261 if (!tmpBounds.isValid()) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002262 info.touchableRegion.clear();
2263 // A layer could have invalid input bounds and still expect to receive touch input if it has
2264 // replaceTouchableRegionWithCrop. For that case, the input transform needs to be calculated
2265 // correctly to determine the coordinate space for input events. Use an empty rect so that
2266 // the layer will receive input in its own layer space.
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002267 tmpBounds = Rect::EMPTY_RECT;
chaviw7e72caf2020-12-02 16:50:43 -08002268 }
2269
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002270 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2271 // frame and transform used for the layer, which determines the bounds and the coordinate space
2272 // within which the layer will receive input.
2273 //
2274 // The coordinate space within which each of the bounds are specified is explicitly documented
2275 // in the variable name. For example "inputBoundsInLayer" is specified in layer space. A
2276 // Transform converts one coordinate space to another, which is apparent in its naming. For
2277 // example, "layerToDisplay" transforms layer space to display space.
2278 //
2279 // Coordinate space definitions:
2280 // - display: The display device's coordinate space. Correlates to pixels on the display.
2281 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2282 // - layer: The coordinate space of this layer.
2283 // - input: The coordinate space in which this layer will receive input events. This could be
2284 // different than layer space if a surfaceInset is used, which changes the origin
2285 // of the input space.
2286 const FloatRect inputBoundsInLayer = tmpBounds.toFloatRect();
chaviw7e72caf2020-12-02 16:50:43 -08002287
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002288 // Clamp surface inset to the input bounds.
2289 const auto surfaceInset = static_cast<float>(info.surfaceInset);
2290 const float xSurfaceInset =
2291 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getWidth() / 2.f));
2292 const float ySurfaceInset =
2293 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getHeight() / 2.f));
chaviw1ff3d1e2020-07-01 15:53:47 -07002294
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002295 // Apply the insets to the input bounds.
2296 const FloatRect insetBoundsInLayer(inputBoundsInLayer.left + xSurfaceInset,
2297 inputBoundsInLayer.top + ySurfaceInset,
2298 inputBoundsInLayer.right - xSurfaceInset,
2299 inputBoundsInLayer.bottom - ySurfaceInset);
Ady Abraham282f1d72019-07-24 18:05:56 -07002300
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002301 // Crop the input bounds to ensure it is within the parent's bounds.
2302 const FloatRect croppedInsetBoundsInLayer = mBounds.intersect(insetBoundsInLayer);
Ady Abraham282f1d72019-07-24 18:05:56 -07002303
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002304 const ui::Transform layerToScreen = getInputTransform();
2305 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
Vishnu Nair8033a492018-12-05 07:27:23 -08002306
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002307 const Rect roundedFrameInDisplay{layerToDisplay.transform(croppedInsetBoundsInLayer)};
2308 info.frameLeft = roundedFrameInDisplay.left;
2309 info.frameTop = roundedFrameInDisplay.top;
2310 info.frameRight = roundedFrameInDisplay.right;
2311 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002312
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002313 ui::Transform inputToLayer;
2314 inputToLayer.set(insetBoundsInLayer.left, insetBoundsInLayer.top);
2315 const ui::Transform inputToDisplay = layerToDisplay * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002316
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002317 // InputDispatcher expects a display-to-input transform.
2318 info.transform = inputToDisplay.inverse();
2319
2320 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002321 info.touchableRegion =
2322 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002323}
2324
chaviw3277faf2021-05-19 16:45:23 -05002325void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002326 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002327 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002328 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002329 }
2330 if (p != nullptr) {
2331 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2332 }
2333}
2334
Vishnu Naira066d902021-09-13 18:40:17 -07002335gui::DropInputMode Layer::getDropInputMode() const {
2336 gui::DropInputMode mode = mDrawingState.dropInputMode;
2337 if (mode == gui::DropInputMode::ALL) {
2338 return mode;
2339 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002340 sp<Layer> parent = mDrawingParent.promote();
2341 if (parent) {
2342 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002343 if (parentMode != gui::DropInputMode::NONE) {
2344 return parentMode;
2345 }
2346 }
2347 return mode;
2348}
2349
2350void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002351 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002352 return;
2353 }
2354
2355 // Check if we need to drop input unconditionally
2356 gui::DropInputMode dropInputMode = getDropInputMode();
2357 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002358 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002359 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2360 return;
2361 }
2362
2363 // Check if we need to check if the window is obscured by parent
2364 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2365 return;
2366 }
2367
2368 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002369 sp<Layer> parent = mDrawingParent.promote();
2370 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002371 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002372 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2373 static_cast<float>(getAlpha()));
2374 }
2375
2376 // Check if the parent has cropped the buffer
2377 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2378 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002379 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002380 return;
2381 }
2382
2383 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2384 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2385 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2386 // match then the layer has not been cropped by its parents.
2387 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2388 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2389
2390 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002391 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002392 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2393 getDebugName());
2394 } else {
2395 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2396 // input if the window is obscured. This check should be done in surfaceflinger but the
2397 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2398 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002399 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002400 }
2401}
2402
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002403WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002404 if (!hasInputInfo()) {
2405 mDrawingState.inputInfo.name = getName();
2406 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2407 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002408 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002409 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002410 }
2411
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002412 const ui::Transform& displayTransform =
2413 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2414
chaviw3277faf2021-05-19 16:45:23 -05002415 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002416 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002417 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002418
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002419 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002420
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002421 if (displayArgs.transform == nullptr) {
2422 // Do not let the window receive touches if it is not associated with a valid display
2423 // transform. We still allow the window to receive keys and prevent ANRs.
2424 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2425 }
2426
Robert Carr5dc426e2020-06-10 14:29:14 -07002427 // For compatibility reasons we let layers which can receive input
2428 // receive input before they have actually submitted a buffer. Because
2429 // of this we use canReceiveInput instead of isVisible to check the
2430 // policy-visibility, ignoring the buffer state. However for layers with
2431 // hasInputInfo()==false we can use the real visibility state.
2432 // We are just using these layers for occlusion detection in
2433 // InputDispatcher, and obviously if they aren't visible they can't occlude
2434 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002435 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2436 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2437
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002438 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002439 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002440 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002441
Vishnu Nair16a938f2021-09-24 07:14:54 -07002442 // If the window will be blacked out on a display because the display does not have the secure
2443 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002444 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002445 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002446 }
2447
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002448 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2449 if (info.replaceTouchableRegionWithCrop) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002450 const Rect bounds(cropLayer ? cropLayer->mScreenBounds : mScreenBounds);
2451 info.touchableRegion = Region(displayTransform.transform(bounds));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002452 } else if (cropLayer != nullptr) {
[1;3C2b9fc252021-02-04 16:16:50 -08002453 info.touchableRegion = info.touchableRegion.intersect(
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002454 displayTransform.transform(Rect{cropLayer->mScreenBounds}));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002455 }
2456
Winson Chunga30f7c92021-06-29 15:42:56 -07002457 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2458 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002459 if (isTrustedOverlay()) {
2460 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2461 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002462
chaviwaf87b3e2019-10-01 16:59:28 -07002463 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2464 // touches from going outside the cloned area.
2465 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002466 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002467 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2468 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002469 info.touchableRegion = info.touchableRegion.intersect(rect);
2470 }
2471 }
2472
Robert Carr720e5062018-07-30 17:45:14 -07002473 return info;
2474}
2475
chaviwaf87b3e2019-10-01 16:59:28 -07002476sp<Layer> Layer::getClonedRoot() {
2477 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002478 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002479 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002480 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002481 return nullptr;
2482 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002483 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002484}
2485
Robert Carredd13602020-04-13 17:24:34 -07002486bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002487 return mDrawingState.inputInfo.token != nullptr ||
2488 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002489}
2490
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002491compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002492 const DisplayDevice* display) const {
2493 if (!display) return nullptr;
Lloyd Piquede196652020-01-22 17:29:58 -08002494 return display->getCompositionDisplay()->getOutputLayerForLayer(getCompositionEngineLayerFE());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002495}
2496
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002497Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2498 const auto outputLayer = findOutputLayerForDisplay(display);
2499 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002500}
2501
chaviwb4c6e582019-08-16 14:35:07 -07002502void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002503 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002504 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002505 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2506 mPotentialCursor = clonedFrom->mPotentialCursor;
2507 mProtectedByApp = clonedFrom->mProtectedByApp;
2508 updateCloneBufferInfo();
2509}
2510
2511void Layer::updateCloneBufferInfo() {
2512 if (!isClone() || !isClonedFromAlive()) {
2513 return;
2514 }
2515
2516 sp<Layer> clonedFrom = getClonedFrom();
2517 mBufferInfo = clonedFrom->mBufferInfo;
2518 mSidebandStream = clonedFrom->mSidebandStream;
2519 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2520 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2521 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2522
2523 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2524 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2525 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2526 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2527 // the cloned drawingState again.
2528 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2529 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2530 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2531 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2532
2533 cloneDrawingState(clonedFrom.get());
2534
2535 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2536 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2537 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2538 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002539}
chaviw74b03172019-08-19 11:09:03 -07002540
2541void Layer::updateMirrorInfo() {
2542 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2543 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2544 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2545 // that case, we want to delete the reference to the clone since we want it to get
2546 // destroyed. The root, this layer, will still be around since the client can continue
2547 // to hold a reference, but no cloned layers will be displayed.
2548 mClonedChild = nullptr;
2549 return;
2550 }
2551
2552 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2553 // If the real layer exists and is in current state, add the clone as a child of the root.
2554 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2555 // copied to drawingState for the root layer. So the clonedChild is always removed from
2556 // drawingState and then needs to be added back each traversal.
2557 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2558 addChildToDrawing(mClonedChild);
2559 }
2560
2561 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002562 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002563 mClonedChild->updateClonedRelatives(clonedLayersMap);
2564}
2565
2566void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2567 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2568 // to the clone. If the real layer is no longer alive, continue traversing the children
2569 // since we may be able to pull out other children that are still alive.
2570 if (isClonedFromAlive()) {
2571 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002572 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002573 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002574 }
2575
2576 // The clone layer may have children in drawingState since they may have been created and
2577 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2578 // that already exist, since we can just re-use them.
2579 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2580 // not updated in the regular traversal. They are skipped since the root will lose the
2581 // reference to them when it copies its currentChildren to drawing.
2582 for (sp<Layer>& child : mDrawingChildren) {
2583 child->updateClonedDrawingState(clonedLayersMap);
2584 }
2585}
2586
2587void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2588 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2589 mDrawingChildren.clear();
2590
2591 if (!isClonedFromAlive()) {
2592 return;
2593 }
2594
2595 sp<Layer> clonedFrom = getClonedFrom();
2596 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2597 if (child == mirrorRoot) {
2598 // This is to avoid cyclical mirroring.
2599 continue;
2600 }
2601 sp<Layer> clonedChild = clonedLayersMap[child];
2602 if (clonedChild == nullptr) {
2603 clonedChild = child->createClone();
2604 clonedLayersMap[child] = clonedChild;
2605 }
2606 addChildToDrawing(clonedChild);
2607 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2608 }
2609}
2610
chaviwaf87b3e2019-10-01 16:59:28 -07002611void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2612 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2613 if (cropLayer != nullptr) {
2614 if (clonedLayersMap.count(cropLayer) == 0) {
2615 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2616 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002617 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002618 } else {
2619 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2620 mDrawingState.touchableRegionCrop = clonedCropLayer;
2621 }
2622 }
2623 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2624 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002625 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002626}
2627
2628void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002629 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002630 mDrawingState.zOrderRelatives.clear();
2631
2632 if (!isClonedFromAlive()) {
2633 return;
2634 }
2635
chaviwaf87b3e2019-10-01 16:59:28 -07002636 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002637 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002638 const sp<Layer>& relative = relativeWeak.promote();
2639 if (clonedLayersMap.count(relative) > 0) {
2640 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002641 mDrawingState.zOrderRelatives.add(clonedRelative);
2642 }
2643 }
2644
2645 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2646 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2647 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2648 // still traverse the children, but the layer with the missing relativeOf will not be shown
2649 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002650 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2651 if (clonedLayersMap.count(relativeOf) > 0) {
2652 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002653 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2654 }
2655
chaviwaf87b3e2019-10-01 16:59:28 -07002656 updateClonedInputInfo(clonedLayersMap);
2657
chaviw74b03172019-08-19 11:09:03 -07002658 for (sp<Layer>& child : mDrawingChildren) {
2659 child->updateClonedRelatives(clonedLayersMap);
2660 }
2661}
2662
2663void Layer::addChildToDrawing(const sp<Layer>& layer) {
2664 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002665 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002666}
2667
Steven Thomas62a4cf82020-01-31 12:04:03 -08002668Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2669 switch (compatibility) {
2670 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2671 return FrameRateCompatibility::Default;
2672 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2673 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002674 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2675 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002676 case ANATIVEWINDOW_FRAME_RATE_MIN:
2677 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002678 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2679 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002680 default:
2681 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2682 return FrameRateCompatibility::Default;
2683 }
2684}
2685
Marin Shalamanovc5986772021-03-16 16:09:49 +01002686scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2687 switch (strategy) {
2688 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2689 return Seamlessness::OnlySeamless;
2690 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2691 return Seamlessness::SeamedAndSeamless;
2692 default:
2693 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2694 return Seamlessness::Default;
2695 }
2696}
2697
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002698bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002699 const State& s(mDrawingState);
2700 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2701 return true;
2702 }
2703
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002704 sp<Layer> parent = mDrawingParent.promote();
2705 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002706}
2707
Robert Carr6a0382d2021-07-01 15:57:17 -07002708void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2709 mClonedChild = clonedChild;
2710 mHadClonedChild = true;
2711 mFlinger->mNumClones++;
2712}
2713
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002714bool Layer::setDropInputMode(gui::DropInputMode mode) {
2715 if (mDrawingState.dropInputMode == mode) {
2716 return false;
2717 }
2718 mDrawingState.dropInputMode = mode;
2719 return true;
2720}
2721
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002722void Layer::cloneDrawingState(const Layer* from) {
2723 mDrawingState = from->mDrawingState;
2724 // Skip callback info since they are not applicable for cloned layers.
2725 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002726 // TODO (b/238781169) currently broken for mirror layers because we do not
2727 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002728 mDrawingState.callbackHandles = {};
2729}
2730
Patrick Williamsbb25f802022-08-30 23:02:34 +00002731void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2732 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002733 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002734 if (!listener) {
2735 return;
2736 }
2737 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002738 uint32_t currentMaxAcquiredBufferCount =
2739 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002740 listener->onReleaseBuffer({buffer->getId(), framenumber},
2741 releaseFence ? releaseFence : Fence::NO_FENCE,
2742 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002743}
2744
2745void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2746 // If we are displayed on multiple displays in a single composition cycle then we would
2747 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2748 // For example we can only use it if all the displays are client comp, and we need
2749 // to merge all the client comp fences. We could do this, but for now we just
2750 // disable the optimization when a layer is composed on multiple displays.
2751 if (mClearClientCompositionFenceOnLayerDisplayed) {
2752 mLastClientCompositionFence = nullptr;
2753 } else {
2754 mClearClientCompositionFenceOnLayerDisplayed = true;
2755 }
2756
2757 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2758 // buffer that was presented on this layer. The first transaction that came in this frame that
2759 // replaced the previous buffer on this layer needs this release fence, because the fence will
2760 // let the client know when that previous buffer is removed from the screen.
2761 //
2762 // Every other transaction on this layer does not need a release fence because no other
2763 // Transactions that were set on this layer this frame are going to have their preceding buffer
2764 // removed from the display this frame.
2765 //
2766 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2767 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2768 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2769 // the previous buffer will be released this frame. The third transaction also contains a
2770 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2771 // transaction will now no longer be presented so it is released immediately and the third
2772 // transaction doesn't need a previous release fence.
2773 sp<CallbackHandle> ch;
2774 for (auto& handle : mDrawingState.callbackHandles) {
2775 if (handle->releasePreviousBuffer &&
2776 mDrawingState.releaseBufferEndpoint == handle->listener) {
2777 ch = handle;
2778 break;
2779 }
2780 }
2781
2782 // Prevent tracing the same release multiple times.
2783 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2784 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2785 }
2786
2787 if (ch != nullptr) {
2788 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2789 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2790 ch->name = mName;
2791 }
2792}
2793
2794void Layer::onSurfaceFrameCreated(
2795 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2796 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2797 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2798 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2799 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002800 if (hasBufferOrSidebandStreamInDrawing()) {
2801 // Only log for layers with a buffer, since we expect the jank data to be drained for
2802 // these, while there may be no jank listeners for bufferless layers.
2803 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2804 mName.c_str());
2805 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2806 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2807 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002808 mPendingJankClassifications.pop_front();
2809 }
2810 mPendingJankClassifications.emplace_back(surfaceFrame);
2811}
2812
2813void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2814 for (const auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair71fcf912022-10-18 09:14:20 -07002815 handle->transformHint = mSkipReportingTransformHint
2816 ? std::nullopt
2817 : std::make_optional<uint32_t>(mTransformHint);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002818 handle->dequeueReadyTime = dequeueReadyTime;
2819 handle->currentMaxAcquiredBufferCount =
2820 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2821 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2822 handle->previousReleaseCallbackId.framenumber);
2823 }
2824
2825 for (auto& handle : mDrawingState.callbackHandles) {
2826 if (handle->releasePreviousBuffer &&
2827 mDrawingState.releaseBufferEndpoint == handle->listener) {
2828 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2829 break;
2830 }
2831 }
2832
2833 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002834 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002835 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2836 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002837 mDrawingState.callbackHandles = {};
2838}
2839
2840bool Layer::willPresentCurrentTransaction() const {
2841 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2842 return (getSidebandStreamChanged() || getAutoRefresh() ||
2843 (mDrawingState.modified &&
2844 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2845}
2846
2847bool Layer::setTransform(uint32_t transform) {
2848 if (mDrawingState.bufferTransform == transform) return false;
2849 mDrawingState.bufferTransform = transform;
2850 mDrawingState.modified = true;
2851 setTransactionFlags(eTransactionNeeded);
2852 return true;
2853}
2854
2855bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2856 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2857 mDrawingState.sequence++;
2858 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2859 mDrawingState.modified = true;
2860 setTransactionFlags(eTransactionNeeded);
2861 return true;
2862}
2863
2864bool Layer::setBufferCrop(const Rect& bufferCrop) {
2865 if (mDrawingState.bufferCrop == bufferCrop) return false;
2866
2867 mDrawingState.sequence++;
2868 mDrawingState.bufferCrop = bufferCrop;
2869
2870 mDrawingState.modified = true;
2871 setTransactionFlags(eTransactionNeeded);
2872 return true;
2873}
2874
2875bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2876 if (mDrawingState.destinationFrame == destinationFrame) return false;
2877
2878 mDrawingState.sequence++;
2879 mDrawingState.destinationFrame = destinationFrame;
2880
2881 mDrawingState.modified = true;
2882 setTransactionFlags(eTransactionNeeded);
2883 return true;
2884}
2885
2886// Translate destination frame into scale and position. If a destination frame is not set, use the
2887// provided scale and position
2888bool Layer::updateGeometry() {
2889 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2890 mDrawingState.destinationFrame.isEmpty()) {
2891 // If destination frame is not set, use the requested transform set via
2892 // Layer::setPosition and Layer::setMatrix.
2893 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2894 }
2895
2896 Rect destRect = mDrawingState.destinationFrame;
2897 int32_t destW = destRect.width();
2898 int32_t destH = destRect.height();
2899 if (destRect.left < 0) {
2900 destRect.left = 0;
2901 destRect.right = destW;
2902 }
2903 if (destRect.top < 0) {
2904 destRect.top = 0;
2905 destRect.bottom = destH;
2906 }
2907
2908 if (!mDrawingState.buffer) {
2909 ui::Transform t;
2910 t.set(destRect.left, destRect.top);
2911 return assignTransform(&mDrawingState.transform, t);
2912 }
2913
2914 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2915 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2916 // Undo any transformations on the buffer.
2917 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2918 std::swap(bufferWidth, bufferHeight);
2919 }
2920 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
2921 if (mDrawingState.transformToDisplayInverse) {
2922 if (invTransform & ui::Transform::ROT_90) {
2923 std::swap(bufferWidth, bufferHeight);
2924 }
2925 }
2926
2927 float sx = destW / static_cast<float>(bufferWidth);
2928 float sy = destH / static_cast<float>(bufferHeight);
2929 ui::Transform t;
2930 t.set(sx, 0, 0, sy);
2931 t.set(destRect.left, destRect.top);
2932 return assignTransform(&mDrawingState.transform, t);
2933}
2934
2935bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
2936 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
2937 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
2938 return false;
2939 }
2940
2941 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
2942
2943 mDrawingState.sequence++;
2944 mDrawingState.modified = true;
2945 setTransactionFlags(eTransactionNeeded);
2946
2947 return true;
2948}
2949
2950bool Layer::setPosition(float x, float y) {
2951 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
2952 return false;
2953 }
2954
2955 mRequestedTransform.set(x, y);
2956
2957 mDrawingState.sequence++;
2958 mDrawingState.modified = true;
2959 setTransactionFlags(eTransactionNeeded);
2960
2961 return true;
2962}
2963
2964bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
2965 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
2966 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07002967 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00002968 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00002969 if (!buffer) {
2970 return false;
2971 }
2972
2973 const bool frameNumberChanged =
2974 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
2975 const uint64_t frameNumber =
2976 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00002977 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002978
2979 if (mDrawingState.buffer) {
2980 mReleasePreviousBuffer = true;
2981 if (!mBufferInfo.mBuffer ||
2982 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
2983 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
2984 // If mDrawingState has a buffer, and we are about to update again
2985 // before swapping to drawing state, then the first buffer will be
2986 // dropped and we should decrement the pending buffer count and
2987 // call any release buffer callbacks if set.
2988 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
2989 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08002990 mDrawingState.acquireFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002991 decrementPendingBufferCount();
2992 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
2993 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
2994 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
2995 mDrawingState.bufferSurfaceFrameTX.reset();
2996 }
2997 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
2998 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
2999 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003000 mLastClientCompositionFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003001 mLastClientCompositionFence = nullptr;
3002 }
3003 }
3004
liulijuneb489f62022-10-17 22:02:14 +08003005 mDrawingState.producerId = bufferData.producerId;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003006 mDrawingState.frameNumber = frameNumber;
3007 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3008 mDrawingState.buffer = std::move(buffer);
3009 mDrawingState.clientCacheId = bufferData.cachedBuffer;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003010 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3011 ? bufferData.acquireFence
3012 : Fence::NO_FENCE;
3013 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3014 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3015 // We latched this buffer unsiganled, so we need to pass the acquire fence
3016 // on the callback instead of just the acquire time, since it's unknown at
3017 // this point.
3018 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3019 } else {
3020 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3021 }
3022
3023 mDrawingState.modified = true;
3024 setTransactionFlags(eTransactionNeeded);
3025
3026 const int32_t layerId = getSequence();
3027 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3028 mOwnerUid, postTime, getGameMode());
3029 mDrawingState.desiredPresentTime = desiredPresentTime;
3030 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3031
3032 const nsecs_t presentTime = [&] {
3033 if (!isAutoTimestamp) return desiredPresentTime;
3034
3035 const auto prediction =
3036 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
3037 if (prediction.has_value()) return prediction->presentTime;
3038
3039 return static_cast<nsecs_t>(0);
3040 }();
3041
3042 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
3043 mFlinger->mScheduler->recordLayerHistory(this, presentTime, LayerUpdateType::Buffer);
3044
3045 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3046
3047 if (dequeueTime && *dequeueTime != 0) {
3048 const uint64_t bufferId = mDrawingState.buffer->getId();
3049 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3050 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3051 FrameTracer::FrameEvent::DEQUEUE);
3052 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3053 FrameTracer::FrameEvent::QUEUE);
3054 }
3055
3056 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3057 return true;
3058}
3059
3060bool Layer::setDataspace(ui::Dataspace dataspace) {
3061 mDrawingState.dataspaceRequested = true;
3062 if (mDrawingState.dataspace == dataspace) return false;
3063 mDrawingState.dataspace = dataspace;
3064 mDrawingState.modified = true;
3065 setTransactionFlags(eTransactionNeeded);
3066 return true;
3067}
3068
John Reck68796592023-01-25 13:47:12 -05003069bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
3070 if (mDrawingState.currentSdrHdrRatio == currentBufferRatio &&
3071 mDrawingState.desiredSdrHdrRatio == desiredRatio)
3072 return false;
3073 mDrawingState.currentSdrHdrRatio = currentBufferRatio;
3074 mDrawingState.desiredSdrHdrRatio = desiredRatio;
3075 mDrawingState.modified = true;
3076 setTransactionFlags(eTransactionNeeded);
3077 return true;
3078}
3079
Patrick Williamsbb25f802022-08-30 23:02:34 +00003080bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3081 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3082 mDrawingState.hdrMetadata = hdrMetadata;
3083 mDrawingState.modified = true;
3084 setTransactionFlags(eTransactionNeeded);
3085 return true;
3086}
3087
3088bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
3089 mDrawingState.surfaceDamageRegion = surfaceDamage;
3090 mDrawingState.modified = true;
3091 setTransactionFlags(eTransactionNeeded);
3092 return true;
3093}
3094
3095bool Layer::setApi(int32_t api) {
3096 if (mDrawingState.api == api) return false;
3097 mDrawingState.api = api;
3098 mDrawingState.modified = true;
3099 setTransactionFlags(eTransactionNeeded);
3100 return true;
3101}
3102
3103bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3104 if (mDrawingState.sidebandStream == sidebandStream) return false;
3105
3106 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3107 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3108 } else if (sidebandStream != nullptr) {
3109 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3110 }
3111
3112 mDrawingState.sidebandStream = sidebandStream;
3113 mDrawingState.modified = true;
3114 setTransactionFlags(eTransactionNeeded);
3115 if (!mSidebandStreamChanged.exchange(true)) {
3116 // mSidebandStreamChanged was false
3117 mFlinger->onLayerUpdate();
3118 }
3119 return true;
3120}
3121
Vishnu Naird6913222023-02-01 22:56:21 +00003122bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3123 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003124 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3125 if (handles.empty()) {
3126 mReleasePreviousBuffer = false;
3127 return false;
3128 }
3129
Pascal Muetschard81cef292023-02-06 12:18:52 +01003130 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003131 for (const auto& handle : handles) {
3132 // If this transaction set a buffer on this layer, release its previous buffer
3133 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3134
3135 // If this layer will be presented in this frame
3136 if (willPresent) {
3137 // If this transaction set an acquire fence on this layer, set its acquire time
3138 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3139 handle->frameNumber = mDrawingState.frameNumber;
3140
3141 // Store so latched time and release fence can be set
3142 mDrawingState.callbackHandles.push_back(handle);
3143
3144 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003145 // Queue this handle to be notified below.
3146 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003147 }
3148 }
3149
Pascal Muetschard81cef292023-02-06 12:18:52 +01003150 if (!remainingHandles.empty()) {
3151 // Notify the transaction completed threads these handles are done. These are only the
3152 // handles that were not added to the mDrawingState, which will be notified later.
3153 std::vector<JankData> jankData;
3154 transferAvailableJankData(remainingHandles, jankData);
3155 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3156 }
3157
Patrick Williamsbb25f802022-08-30 23:02:34 +00003158 mReleasePreviousBuffer = false;
3159 mCallbackHandleAcquireTimeOrFence = -1;
3160
3161 return willPresent;
3162}
3163
3164Rect Layer::getBufferSize(const State& /*s*/) const {
3165 // for buffer state layers we use the display frame size as the buffer size.
3166
3167 if (mBufferInfo.mBuffer == nullptr) {
3168 return Rect::INVALID_RECT;
3169 }
3170
3171 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3172 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3173
3174 // Undo any transformations on the buffer and return the result.
3175 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3176 std::swap(bufWidth, bufHeight);
3177 }
3178
3179 if (getTransformToDisplayInverse()) {
3180 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3181 if (invTransform & ui::Transform::ROT_90) {
3182 std::swap(bufWidth, bufHeight);
3183 }
3184 }
3185
3186 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3187}
3188
3189FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3190 if (mBufferInfo.mBuffer == nullptr) {
3191 return parentBounds;
3192 }
3193
3194 return getBufferSize(getDrawingState()).toFloatRect();
3195}
3196
3197bool Layer::fenceHasSignaled() const {
3198 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3199 return true;
3200 }
3201
3202 const bool fenceSignaled =
3203 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3204 if (!fenceSignaled) {
3205 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3206 TimeStats::LatchSkipReason::LateAcquire);
3207 }
3208
3209 return fenceSignaled;
3210}
3211
Vishnu Naird6913222023-02-01 22:56:21 +00003212void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003213 for (const auto& handle : mDrawingState.callbackHandles) {
3214 handle->refreshStartTime = refreshStartTime;
3215 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003216}
3217
3218void Layer::setAutoRefresh(bool autoRefresh) {
3219 mDrawingState.autoRefresh = autoRefresh;
3220}
3221
3222bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3223 // 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 +00003224 auto* snapshot = editLayerSnapshot();
3225 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003226
3227 if (mSidebandStreamChanged.exchange(false)) {
3228 const State& s(getDrawingState());
3229 // mSidebandStreamChanged was true
3230 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003231 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003232 if (mSidebandStream != nullptr) {
3233 setTransactionFlags(eTransactionNeeded);
3234 mFlinger->setTransactionFlags(eTraversalNeeded);
3235 }
3236 recomputeVisibleRegions = true;
3237
3238 return true;
3239 }
3240 return false;
3241}
3242
3243bool Layer::hasFrameUpdate() const {
3244 const State& c(getDrawingState());
3245 return (mDrawingStateModified || mDrawingState.modified) &&
3246 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3247}
3248
3249void Layer::updateTexImage(nsecs_t latchTime) {
3250 const State& s(getDrawingState());
3251
3252 if (!s.buffer) {
3253 if (s.bgColorLayer) {
3254 for (auto& handle : mDrawingState.callbackHandles) {
3255 handle->latchTime = latchTime;
3256 }
3257 }
3258 return;
3259 }
3260
3261 for (auto& handle : mDrawingState.callbackHandles) {
3262 if (handle->frameNumber == mDrawingState.frameNumber) {
3263 handle->latchTime = latchTime;
3264 }
3265 }
3266
3267 const int32_t layerId = getSequence();
3268 const uint64_t bufferId = mDrawingState.buffer->getId();
3269 const uint64_t frameNumber = mDrawingState.frameNumber;
3270 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3271 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3272 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3273
3274 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3275 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3276 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3277 FrameTracer::FrameEvent::LATCH);
3278
3279 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3280 if (bufferSurfaceFrame != nullptr &&
3281 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3282 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3283 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3284 // are processing the next state.
3285 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3286 mDrawingState.acquireFenceTime->getSignalTime(),
3287 latchTime);
3288 mDrawingState.bufferSurfaceFrameTX.reset();
3289 }
3290
3291 std::deque<sp<CallbackHandle>> remainingHandles;
3292 mFlinger->getTransactionCallbackInvoker()
3293 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3294 mDrawingState.callbackHandles = remainingHandles;
3295
3296 mDrawingStateModified = false;
3297}
3298
3299void Layer::gatherBufferInfo() {
3300 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3301 decrementPendingBufferCount();
3302 }
3303
3304 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3305 mBufferInfo.mBuffer = mDrawingState.buffer;
3306 mBufferInfo.mFence = mDrawingState.acquireFence;
3307 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3308 mBufferInfo.mPixelFormat =
3309 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3310 mBufferInfo.mFrameLatencyNeeded = true;
3311 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3312 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3313 mBufferInfo.mFence = mDrawingState.acquireFence;
3314 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3315 auto lastDataspace = mBufferInfo.mDataspace;
3316 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3317 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003318 mFlinger->mHdrLayerInfoChanged = true;
3319 }
3320 if (mBufferInfo.mDesiredSdrHdrRatio != mDrawingState.desiredSdrHdrRatio) {
3321 mBufferInfo.mDesiredSdrHdrRatio = mDrawingState.desiredSdrHdrRatio;
3322 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003323 }
3324 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3325 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3326 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3327 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3328 mBufferInfo.mApi = mDrawingState.api;
3329 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003330}
3331
3332Rect Layer::computeBufferCrop(const State& s) {
3333 if (s.buffer && !s.bufferCrop.isEmpty()) {
3334 Rect bufferCrop;
3335 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3336 return bufferCrop;
3337 } else if (s.buffer) {
3338 return s.buffer->getBounds();
3339 } else {
3340 return s.bufferCrop;
3341 }
3342}
3343
3344sp<Layer> Layer::createClone() {
3345 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3346 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003347 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003348 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3349 return layer;
3350}
3351
Patrick Williamsbb25f802022-08-30 23:02:34 +00003352void Layer::decrementPendingBufferCount() {
3353 int32_t pendingBuffers = --mPendingBufferTransactions;
3354 tracePendingBufferCount(pendingBuffers);
3355}
3356
3357void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3358 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3359}
3360
3361/*
3362 * We don't want to send the layer's transform to input, but rather the
3363 * parent's transform. This is because Layer's transform is
3364 * information about how the buffer is placed on screen. The parent's
3365 * transform makes more sense to send since it's information about how the
3366 * layer is placed on screen. This transform is used by input to determine
3367 * how to go from screen space back to window space.
3368 */
3369ui::Transform Layer::getInputTransform() const {
3370 if (!hasBufferOrSidebandStream()) {
3371 return getTransform();
3372 }
3373 sp<Layer> parent = mDrawingParent.promote();
3374 if (parent == nullptr) {
3375 return ui::Transform();
3376 }
3377
3378 return parent->getTransform();
3379}
3380
3381/**
3382 * Similar to getInputTransform, we need to update the bounds to include the transform.
3383 * This is because bounds don't include the buffer transform, where the input assumes
3384 * that's already included.
3385 */
3386Rect Layer::getInputBounds() const {
3387 if (!hasBufferOrSidebandStream()) {
3388 return getCroppedBufferSize(getDrawingState());
3389 }
3390
3391 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
3392 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
3393 return bufferBounds;
3394 }
3395 return mDrawingState.transform.transform(bufferBounds);
3396}
3397
3398bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3399 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3400
3401 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3402 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3403 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3404 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3405 layer_state_t::eReparent;
3406
3407 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3408 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3409 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3410 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3411 layer_state_t::eInputInfoChanged;
3412
3413 if ((s.what & requiredFlags) != requiredFlags) {
3414 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3415 (s.what | requiredFlags) & ~s.what);
3416 return false;
3417 }
3418
3419 if (s.what & deniedFlags) {
3420 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3421 return false;
3422 }
3423
3424 if (s.what & allowedFlags) {
3425 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3426 }
3427
3428 if (s.what & layer_state_t::ePositionChanged) {
3429 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3430 ALOGV("%s: false [ePositionChanged changed]", __func__);
3431 return false;
3432 }
3433 }
3434
3435 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003436 if (mDrawingState.color.a != s.color.a) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003437 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3438 return false;
3439 }
3440 }
3441
3442 if (s.what & layer_state_t::eColorTransformChanged) {
3443 if (mDrawingState.colorTransform != s.colorTransform) {
3444 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3445 return false;
3446 }
3447 }
3448
3449 if (s.what & layer_state_t::eBackgroundColorChanged) {
3450 if (mDrawingState.bgColorLayer || s.bgColorAlpha != 0) {
3451 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3452 return false;
3453 }
3454 }
3455
3456 if (s.what & layer_state_t::eMatrixChanged) {
3457 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3458 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3459 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3460 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3461 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3462 return false;
3463 }
3464 }
3465
3466 if (s.what & layer_state_t::eCornerRadiusChanged) {
3467 if (mDrawingState.cornerRadius != s.cornerRadius) {
3468 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3469 return false;
3470 }
3471 }
3472
3473 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3474 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3475 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3476 return false;
3477 }
3478 }
3479
Vishnu Nairbbceb462022-10-10 04:52:13 +00003480 if (s.what & layer_state_t::eBufferTransformChanged) {
3481 if (mDrawingState.bufferTransform != s.bufferTransform) {
3482 ALOGV("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003483 return false;
3484 }
3485 }
3486
3487 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3488 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3489 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3490 return false;
3491 }
3492 }
3493
3494 if (s.what & layer_state_t::eCropChanged) {
3495 if (mDrawingState.crop != s.crop) {
3496 ALOGV("%s: false [eCropChanged changed]", __func__);
3497 return false;
3498 }
3499 }
3500
3501 if (s.what & layer_state_t::eDataspaceChanged) {
3502 if (mDrawingState.dataspace != s.dataspace) {
3503 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3504 return false;
3505 }
3506 }
3507
3508 if (s.what & layer_state_t::eHdrMetadataChanged) {
3509 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3510 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3511 return false;
3512 }
3513 }
3514
3515 if (s.what & layer_state_t::eSidebandStreamChanged) {
3516 if (mDrawingState.sidebandStream != s.sidebandStream) {
3517 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3518 return false;
3519 }
3520 }
3521
3522 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3523 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3524 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3525 return false;
3526 }
3527 }
3528
3529 if (s.what & layer_state_t::eShadowRadiusChanged) {
3530 if (mDrawingState.shadowRadius != s.shadowRadius) {
3531 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3532 return false;
3533 }
3534 }
3535
3536 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3537 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3538 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3539 return false;
3540 }
3541 }
3542
3543 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3544 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3545 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3546 return false;
3547 }
3548 }
3549
3550 if (s.what & layer_state_t::eStretchChanged) {
3551 StretchEffect temp = s.stretchEffect;
3552 temp.sanitize();
3553 if (mDrawingState.stretchEffect != temp) {
3554 ALOGV("%s: false [eStretchChanged changed]", __func__);
3555 return false;
3556 }
3557 }
3558
3559 if (s.what & layer_state_t::eBufferCropChanged) {
3560 if (mDrawingState.bufferCrop != s.bufferCrop) {
3561 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3562 return false;
3563 }
3564 }
3565
3566 if (s.what & layer_state_t::eDestinationFrameChanged) {
3567 if (mDrawingState.destinationFrame != s.destinationFrame) {
3568 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3569 return false;
3570 }
3571 }
3572
3573 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3574 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3575 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3576 return false;
3577 }
3578 }
3579
John Reck68796592023-01-25 13:47:12 -05003580 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
3581 if (mDrawingState.currentSdrHdrRatio != s.currentSdrHdrRatio ||
3582 mDrawingState.desiredSdrHdrRatio != s.desiredSdrHdrRatio) {
3583 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3584 return false;
3585 }
3586 }
3587
Patrick Williamsbb25f802022-08-30 23:02:34 +00003588 ALOGV("%s: true", __func__);
3589 return true;
3590}
3591
3592bool Layer::isHdrY410() const {
3593 // pixel format is HDR Y410 masquerading as RGBA_1010102
3594 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3595 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3596 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3597}
3598
Vishnu Naire14c6b32022-08-06 04:20:15 +00003599sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003600 // There's no need to get a CE Layer if the layer isn't going to draw anything.
Vishnu Naird6913222023-02-01 22:56:21 +00003601 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003602}
3603
Vishnu Naire14c6b32022-08-06 04:20:15 +00003604const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003605 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003606}
3607
Vishnu Naire14c6b32022-08-06 04:20:15 +00003608LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003609 return mSnapshot.get();
3610}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003611
Vishnu Naird6913222023-02-01 22:56:21 +00003612std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3613 return std::move(mSnapshot);
3614}
3615
3616void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3617 mSnapshot = std::move(snapshot);
3618}
3619
Patrick Williamsbb25f802022-08-30 23:02:34 +00003620const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003621 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003622}
3623
Patrick Williams7584c6a2022-10-29 02:10:58 +00003624sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Naird6913222023-02-01 22:56:21 +00003625 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003626 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3627 return result;
3628}
3629
Vishnu Naird6913222023-02-01 22:56:21 +00003630sp<LayerFE> Layer::getCompositionEngineLayerFE(
3631 const frontend::LayerHierarchy::TraversalPath& path) {
3632 for (auto& [p, layerFE] : mLayerFEs) {
3633 if (p == path) {
3634 return layerFE;
3635 }
3636 }
3637 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3638 mLayerFEs.emplace_back(path, layerFE);
3639 return layerFE;
3640}
3641
Patrick Williamsbb25f802022-08-30 23:02:34 +00003642void Layer::useSurfaceDamage() {
3643 if (mFlinger->mForceFullDamage) {
3644 surfaceDamageRegion = Region::INVALID_REGION;
3645 } else {
3646 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3647 }
3648}
3649
3650void Layer::useEmptyDamage() {
3651 surfaceDamageRegion.clear();
3652}
3653
3654bool Layer::isOpaque(const Layer::State& s) const {
3655 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3656 // layer's opaque flag.
3657 if (!hasSomethingToDraw()) {
3658 return false;
3659 }
3660
3661 // if the layer has the opaque flag, then we're always opaque
3662 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3663 return true;
3664 }
3665
3666 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003667 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003668 return true;
3669 }
3670
3671 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3672 return fillsColor() && getAlpha() == 1.0_hf;
3673}
3674
3675bool Layer::canReceiveInput() const {
3676 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3677}
3678
3679bool Layer::isVisible() const {
3680 if (!hasSomethingToDraw()) {
3681 return false;
3682 }
3683
3684 if (isHiddenByPolicy()) {
3685 return false;
3686 }
3687
3688 return getAlpha() > 0.0f || hasBlur();
3689}
3690
3691void Layer::onPostComposition(const DisplayDevice* display,
3692 const std::shared_ptr<FenceTime>& glDoneFence,
3693 const std::shared_ptr<FenceTime>& presentFence,
3694 const CompositorTiming& compositorTiming) {
3695 // mFrameLatencyNeeded is true when a new frame was latched for the
3696 // composition.
3697 if (!mBufferInfo.mFrameLatencyNeeded) return;
3698
3699 for (const auto& handle : mDrawingState.callbackHandles) {
3700 handle->gpuCompositionDoneFence = glDoneFence;
3701 handle->compositorTiming = compositorTiming;
3702 }
3703
3704 // Update mFrameTracker.
3705 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3706 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3707
3708 const int32_t layerId = getSequence();
3709 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3710
3711 const auto outputLayer = findOutputLayerForDisplay(display);
3712 if (outputLayer && outputLayer->requiresClientComposition()) {
3713 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3714 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3715 clientCompositionTimestamp,
3716 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3717 // Update the SurfaceFrames in the drawing state
3718 if (mDrawingState.bufferSurfaceFrameTX) {
3719 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3720 }
3721 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3722 surfaceFrame->setGpuComposition();
3723 }
3724 }
3725
3726 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3727 if (frameReadyFence->isValid()) {
3728 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3729 } else {
3730 // There was no fence for this frame, so assume that it was ready
3731 // to be presented at the desired present time.
3732 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3733 }
3734
3735 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08003736 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003737 const std::optional<Fps> renderRate =
3738 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3739
3740 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3741 const auto gameMode = getGameMode();
3742
3743 if (presentFence->isValid()) {
3744 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3745 refreshRate, renderRate, vote, gameMode);
3746 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3747 presentFence,
3748 FrameTracer::FrameEvent::PRESENT_FENCE);
3749 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3750 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3751 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003752 // The HWC doesn't support present fences, so use the present timestamp instead.
3753 const nsecs_t presentTimestamp =
3754 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3755
3756 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3757 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3758 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3759
Patrick Williamsbb25f802022-08-30 23:02:34 +00003760 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3761 refreshRate, renderRate, vote, gameMode);
3762 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3763 mCurrentFrameNumber, actualPresentTime,
3764 FrameTracer::FrameEvent::PRESENT_FENCE);
3765 mFrameTracker.setActualPresentTime(actualPresentTime);
3766 }
3767 }
3768
3769 mFrameTracker.advanceFrame();
3770 mBufferInfo.mFrameLatencyNeeded = false;
3771}
3772
3773bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
3774 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3775 getDrawingState().frameNumber);
3776
3777 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3778
3779 if (refreshRequired) {
3780 return refreshRequired;
3781 }
3782
3783 // If the head buffer's acquire fence hasn't signaled yet, return and
3784 // try again later
3785 if (!fenceHasSignaled()) {
3786 ATRACE_NAME("!fenceHasSignaled()");
3787 mFlinger->onLayerUpdate();
3788 return false;
3789 }
3790
3791 updateTexImage(latchTime);
3792 if (mDrawingState.buffer == nullptr) {
3793 return false;
3794 }
3795
3796 // Capture the old state of the layer for comparisons later
3797 BufferInfo oldBufferInfo = mBufferInfo;
3798 const bool oldOpacity = isOpaque(mDrawingState);
3799 mPreviousFrameNumber = mCurrentFrameNumber;
3800 mCurrentFrameNumber = mDrawingState.frameNumber;
3801 gatherBufferInfo();
3802
3803 if (oldBufferInfo.mBuffer == nullptr) {
3804 // the first time we receive a buffer, we need to trigger a
3805 // geometry invalidation.
3806 recomputeVisibleRegions = true;
3807 }
3808
3809 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3810 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3811 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3812 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3813 recomputeVisibleRegions = true;
3814 }
3815
3816 if (oldBufferInfo.mBuffer != nullptr) {
3817 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3818 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3819 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3820 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3821 recomputeVisibleRegions = true;
3822 }
3823 }
3824
3825 if (oldOpacity != isOpaque(mDrawingState)) {
3826 recomputeVisibleRegions = true;
3827 }
3828
3829 return true;
3830}
3831
3832bool Layer::hasReadyFrame() const {
3833 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
3834}
3835
3836bool Layer::isProtected() const {
3837 return (mBufferInfo.mBuffer != nullptr) &&
3838 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
3839}
3840
Patrick Williamsbb25f802022-08-30 23:02:34 +00003841void Layer::latchAndReleaseBuffer() {
3842 if (hasReadyFrame()) {
3843 bool ignored = false;
3844 latchBuffer(ignored, systemTime());
3845 }
3846 releasePendingBuffer(systemTime());
3847}
3848
3849PixelFormat Layer::getPixelFormat() const {
3850 return mBufferInfo.mPixelFormat;
3851}
3852
3853bool Layer::getTransformToDisplayInverse() const {
3854 return mBufferInfo.mTransformToDisplayInverse;
3855}
3856
3857Rect Layer::getBufferCrop() const {
3858 // this is the crop rectangle that applies to the buffer
3859 // itself (as opposed to the window)
3860 if (!mBufferInfo.mCrop.isEmpty()) {
3861 // if the buffer crop is defined, we use that
3862 return mBufferInfo.mCrop;
3863 } else if (mBufferInfo.mBuffer != nullptr) {
3864 // otherwise we use the whole buffer
3865 return mBufferInfo.mBuffer->getBounds();
3866 } else {
3867 // if we don't have a buffer yet, we use an empty/invalid crop
3868 return Rect();
3869 }
3870}
3871
3872uint32_t Layer::getBufferTransform() const {
3873 return mBufferInfo.mTransform;
3874}
3875
3876ui::Dataspace Layer::getDataSpace() const {
3877 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
3878}
3879
3880ui::Dataspace Layer::getRequestedDataSpace() const {
3881 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
3882}
3883
3884ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
3885 ui::Dataspace updatedDataspace = dataspace;
3886 // translate legacy dataspaces to modern dataspaces
3887 switch (dataspace) {
3888 case ui::Dataspace::SRGB:
3889 updatedDataspace = ui::Dataspace::V0_SRGB;
3890 break;
3891 case ui::Dataspace::SRGB_LINEAR:
3892 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
3893 break;
3894 case ui::Dataspace::JFIF:
3895 updatedDataspace = ui::Dataspace::V0_JFIF;
3896 break;
3897 case ui::Dataspace::BT601_625:
3898 updatedDataspace = ui::Dataspace::V0_BT601_625;
3899 break;
3900 case ui::Dataspace::BT601_525:
3901 updatedDataspace = ui::Dataspace::V0_BT601_525;
3902 break;
3903 case ui::Dataspace::BT709:
3904 updatedDataspace = ui::Dataspace::V0_BT709;
3905 break;
3906 default:
3907 break;
3908 }
3909
3910 return updatedDataspace;
3911}
3912
3913sp<GraphicBuffer> Layer::getBuffer() const {
3914 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
3915}
3916
Patrick Williamsbb25f802022-08-30 23:02:34 +00003917void Layer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
3918 mTransformHint = getFixedTransformHint();
3919 if (mTransformHint == ui::Transform::ROT_INVALID) {
3920 mTransformHint = displayTransformHint;
3921 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07003922 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003923}
3924
3925const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
3926 return mBufferInfo.mBuffer;
3927}
3928
3929bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003930 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003931 return false;
3932 }
3933
3934 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00003935 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003936 mDrawingState.modified = true;
3937 setTransactionFlags(eTransactionNeeded);
3938 return true;
3939}
3940
3941bool Layer::fillsColor() const {
3942 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
3943 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
3944}
3945
3946bool Layer::hasBlur() const {
3947 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
3948}
3949
Vishnu Nairba354102022-08-01 00:14:18 +00003950void Layer::updateSnapshot(bool updateGeometry) {
3951 if (!getCompositionEngineLayerFE()) {
3952 return;
3953 }
3954
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003955 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00003956 if (updateGeometry) {
3957 prepareBasicGeometryCompositionState();
3958 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003959 snapshot->roundedCorner = getRoundedCornerState();
3960 snapshot->stretchEffect = getStretchEffect();
3961 snapshot->transformedBounds = mScreenBounds;
3962 if (mEffectiveShadowRadius > 0.f) {
3963 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
3964
3965 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
3966 // it if transparent regions are present. This may not be necessary since shadows are
3967 // typically cast by layers without transparent regions.
3968 snapshot->shadowSettings.boundaries = mBounds;
3969
3970 const float casterAlpha = snapshot->alpha;
3971 const bool casterIsOpaque =
3972 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
3973
3974 // If the casting layer is translucent, we need to fill in the shadow underneath the
3975 // layer. Otherwise the generated shadow will only be shown around the casting layer.
3976 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
3977 snapshot->shadowSettings.ambientColor *= casterAlpha;
3978 snapshot->shadowSettings.spotColor *= casterAlpha;
3979 }
3980 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00003981 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003982 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003983 snapshot->layerOpaqueFlagSet =
3984 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003985 snapshot->isHdrY410 = isHdrY410();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003986 sp<Layer> p = mDrawingParent.promote();
3987 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003988 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003989 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003990 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003991 }
3992 snapshot->bufferSize = getBufferSize(mDrawingState);
3993 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00003994 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00003995 preparePerFrameCompositionState();
3996}
3997
Vishnu Naire14c6b32022-08-06 04:20:15 +00003998void Layer::updateChildrenSnapshots(bool updateGeometry) {
3999 for (const sp<Layer>& child : mDrawingChildren) {
4000 child->updateSnapshot(updateGeometry);
4001 child->updateChildrenSnapshots(updateGeometry);
4002 }
4003}
4004
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004005void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4006 mSnapshot->layerMetadata = parentMetadata;
4007 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4008 for (const sp<Layer>& child : mDrawingChildren) {
4009 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4010 }
4011}
4012
4013void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4014 std::unordered_set<Layer*>& visited) {
4015 if (visited.find(this) != visited.end()) {
4016 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4017 return;
4018 }
4019 visited.insert(this);
4020
4021 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4022
4023 if (mDrawingState.zOrderRelatives.empty()) {
4024 return;
4025 }
4026 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4027 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4028 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4029 sp<Layer> relative = weakRelative.promote();
4030 if (!relative) {
4031 continue;
4032 }
4033 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4034 }
4035}
4036
Chavi Weingarten076acac2023-01-19 17:20:43 +00004037void Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
4038 TrustedPresentationListener const& listener) {
4039 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4040 mTrustedPresentationListener = listener;
4041 mTrustedPresentationThresholds = thresholds;
4042 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4043 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4044 mFlinger->mNumTrustedPresentationListeners++;
4045 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4046 mFlinger->mNumTrustedPresentationListeners--;
4047 }
4048}
4049
Mathias Agopian13127d82013-03-05 17:47:11 -08004050// ---------------------------------------------------------------------------
4051
Marin Shalamanov46084422020-10-13 12:33:42 +02004052std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004053 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4054 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004055}
4056
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004057} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004058
4059#if defined(__gl_h_)
4060#error "don't include gl/gl.h in this file"
4061#endif
4062
4063#if defined(__gl2_h_)
4064#error "don't include gl2/gl2.h in this file"
4065#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004066
4067// TODO(b/129481165): remove the #pragma below and fix conversion issues
4068#pragma clang diagnostic pop // ignored "-Wconversion"