blob: b60b3878747cbf6e819ff27b39c74976952745f4 [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 Nair3af0ec02023-02-10 04:13:48 +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
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500199 mFrameTracker.setDisplayRefreshPeriod(
200 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700201
Vishnu Naircb8be502022-10-12 19:03:23 +0000202 mOwnerUid = args.ownerUid;
203 mOwnerPid = args.ownerPid;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000204
205 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
206 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
207 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
208 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000209
210 mSnapshot->sequence = sequence;
211 mSnapshot->name = getDebugName();
212 mSnapshot->textureName = mTextureName;
213 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000214 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800215}
216
217void Layer::onFirstRef() {
218 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700219}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700220
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700221Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000222 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
223 "Layer destructor called off the main thread.");
224
Patrick Williamsbb25f802022-08-30 23:02:34 +0000225 // The original layer and the clone layer share the same texture and buffer. Therefore, only
226 // one of the layers, in this case the original layer, needs to handle the deletion. The
227 // original layer and the clone should be removed at the same time so there shouldn't be any
228 // issue with the clone layer trying to use the texture.
229 if (mBufferInfo.mBuffer != nullptr) {
230 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
231 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800232 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000233 }
234 if (!isClone()) {
235 // The original layer and the clone layer share the same texture. Therefore, only one of
236 // the layers, in this case the original layer, needs to handle the deletion. The original
237 // layer and the clone should be removed at the same time so there shouldn't be any issue
238 // with the clone layer trying to use the deleted texture.
239 mFlinger->deleteTextureAsync(mTextureName);
240 }
241 const int32_t layerId = getSequence();
242 mFlinger->mTimeStats->onDestroy(layerId);
243 mFlinger->mFrameTracer->onDestroy(layerId);
244
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000245 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700246 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700247
248 if (mDrawingState.sidebandStream != nullptr) {
249 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
250 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700251 if (mHadClonedChild) {
252 mFlinger->mNumClones--;
253 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000254 if (hasTrustedPresentationListener()) {
255 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000256 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000257 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700258}
259
Mathias Agopian13127d82013-03-05 17:47:11 -0800260// ---------------------------------------------------------------------------
261// callbacks
262// ---------------------------------------------------------------------------
263
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700264void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700265 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700266 return;
267 }
Robert Carr2e102c92018-10-23 12:11:15 -0700268
Robert Carr6a160312021-05-17 12:08:20 -0700269 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700270 if (strongRelative == nullptr) {
271 setZOrderRelativeOf(nullptr);
272 return;
273 }
274
275 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700276 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700277 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800278 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700279 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700280}
281
282void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700283 if (!mRemovedFromDrawingState) {
284 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700285 mFlinger->mScheduler->deregisterLayer(this);
286 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000287 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000288
Ady Abrahamd11bade2022-08-01 16:18:03 -0700289 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700290}
Chia-I Wu38512252017-05-17 14:36:16 -0700291
chaviw68d4dab2020-06-08 15:07:32 -0700292sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000293 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700294 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700295 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700296 }
297 return parent->getRootLayer();
298}
299
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700300void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700301 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
302 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700303 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700304
305 traverse(LayerVector::StateSet::Current, [&](Layer* layer) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700306 layer->removeFromCurrentState();
307 layer->removeRelativeZ(layersInTree);
chaviw68d4dab2020-06-08 15:07:32 -0700308 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700309}
310
chaviw61626f22018-11-15 16:26:27 -0800311void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700312 if (mRemovedFromDrawingState) {
313 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700314 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700315 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700316 }
chaviw61626f22018-11-15 16:26:27 -0800317
318 for (const auto& child : mCurrentChildren) {
319 child->addToCurrentState();
320 }
321}
322
Mathias Agopian13127d82013-03-05 17:47:11 -0800323// ---------------------------------------------------------------------------
324// set-up
325// ---------------------------------------------------------------------------
326
chaviw13fdc492017-06-27 12:40:18 -0700327bool Layer::getPremultipledAlpha() const {
328 return mPremultipliedAlpha;
329}
330
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700331sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800332 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700333 if (mGetHandleCalled) {
334 ALOGE("Get handle called twice" );
335 return nullptr;
336 }
337 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700338 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000339 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800340}
341
342// ---------------------------------------------------------------------------
343// h/w composer set-up
344// ---------------------------------------------------------------------------
345
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700346static Rect reduce(const Rect& win, const Region& exclude) {
347 if (CC_LIKELY(exclude.isEmpty())) {
348 return win;
349 }
350 if (exclude.isRect()) {
351 return win.reduce(exclude.getBounds());
352 }
353 return Region(win).subtract(exclude).getBounds();
354}
355
Dan Stoza80d61162017-12-20 15:57:52 -0800356static FloatRect reduce(const FloatRect& win, const Region& exclude) {
357 if (CC_LIKELY(exclude.isEmpty())) {
358 return win;
359 }
360 // Convert through Rect (by rounding) for lack of FloatRegion
361 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
362}
363
Vishnu Nair4351ad52019-02-11 14:13:02 -0800364Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800365 if (!reduceTransparentRegion) {
366 return Rect{mScreenBounds};
367 }
368
369 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800370 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800371 // Transform to screen space.
372 bounds = t.transform(bounds);
373 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700374}
375
Vishnu Nair4351ad52019-02-11 14:13:02 -0800376FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000377 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800378 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700379}
380
Vishnu Nairf0c28512019-02-08 12:40:28 -0800381FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
382 // Subtract the transparent region and snap to the bounds.
383 return reduce(mBounds, activeTransparentRegion);
384}
385
Chavi Weingarten076acac2023-01-19 17:20:43 +0000386// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000387void Layer::updateTrustedPresentationState(const DisplayDevice* display,
388 const frontend::LayerSnapshot* snapshot,
389 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000390 if (!hasTrustedPresentationListener()) {
391 return;
392 }
393 const bool lastState = mLastComputedTrustedPresentationState;
394 mLastComputedTrustedPresentationState = false;
395
396 if (!leaveState) {
397 const auto outputLayer = findOutputLayerForDisplay(display);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000398 if (outputLayer != nullptr) {
399 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
400 Region coveredRegion =
401 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
402 mLastComputedTrustedPresentationState =
403 computeTrustedPresentationState(snapshot->geomLayerBounds,
404 snapshot->sourceBounds(), coveredRegion,
405 snapshot->transformedBounds,
406 snapshot->alpha,
407 snapshot->geomLayerTransform,
408 mTrustedPresentationThresholds);
409 } else {
410 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
411 "TrustedPresentationState",
412 getDebugName());
413 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000414 }
415 }
416 const bool newState = mLastComputedTrustedPresentationState;
417 if (lastState && !newState) {
418 // We were in the trusted presentation state, but now we left it,
419 // emit the callback if needed
420 if (mLastReportedTrustedPresentationState) {
421 mLastReportedTrustedPresentationState = false;
422 mTrustedPresentationListener.invoke(false);
423 }
424 // Reset the timer
425 mEnteredTrustedPresentationStateTime = -1;
426 } else if (!lastState && newState) {
427 // We were not in the trusted presentation state, but we entered it, begin the timer
428 // and make sure this gets called at least once more!
429 mEnteredTrustedPresentationStateTime = time_in_ms;
430 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
431 }
432
433 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
434 if (!mLastReportedTrustedPresentationState && newState &&
435 (time_in_ms - mEnteredTrustedPresentationStateTime >
436 mTrustedPresentationThresholds.stabilityRequirementMs)) {
437 mLastReportedTrustedPresentationState = true;
438 mTrustedPresentationListener.invoke(true);
439 }
440}
441
442/**
443 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
444 * of how the parameters and thresholds are interpreted. The general spirit is
445 * to produce an upper bound on the amount of the buffer which was presented.
446 */
447bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
448 const Region& coveredRegion,
449 const FloatRect& screenBounds, float alpha,
450 const ui::Transform& effectiveTransform,
451 const TrustedPresentationThresholds& thresholds) {
452 if (alpha < thresholds.minAlpha) {
453 return false;
454 }
455 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
456 return false;
457 }
458 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
459 return false;
460 }
461
462 const float sx = effectiveTransform.dsdx();
463 const float sy = effectiveTransform.dsdy();
464 float fractionRendered = std::min(sx * sy, 1.0f);
465
466 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
467 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
468 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
469
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000470 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
471 // Compute the size of all the rects since they may be disconnected.
472 float coveredSize = 0;
473 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
474 float size = rect->width() * rect->height();
475 coveredSize += size;
476 }
477
478 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000479
480 if (fractionRendered < thresholds.minFractionRendered) {
481 return false;
482 }
483
484 return true;
485}
486
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700487void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
488 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800489 const State& s(getDrawingState());
490
491 // Calculate effective layer transform
492 mEffectiveTransform = parentTransform * getActiveTransform(s);
493
Garfield Tan2c1782c2022-02-16 15:25:05 -0800494 if (CC_UNLIKELY(!isTransformValid())) {
495 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
496 getDebugName());
497 return;
498 }
499
Vishnu Nair4351ad52019-02-11 14:13:02 -0800500 // Transform parent bounds to layer space
501 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
502
Vishnu Nairc652ff82019-03-15 12:48:54 -0700503 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800504 mSourceBounds = computeSourceBounds(parentBounds);
505
506 // Calculate bounds by croping diplay frame with layer crop and parent bounds
507 FloatRect bounds = mSourceBounds;
508 const Rect layerCrop = getCrop(s);
509 if (!layerCrop.isEmpty()) {
510 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
511 }
512 bounds = bounds.intersect(parentBounds);
513
514 mBounds = bounds;
515 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700516
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700517 // Use the layer's own shadow radius if set. Otherwise get the radius from
518 // parent.
519 if (s.shadowRadius > 0.f) {
520 mEffectiveShadowRadius = s.shadowRadius;
521 } else {
522 mEffectiveShadowRadius = parentShadowRadius;
523 }
524
525 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
526 // don't pass it to its children.
527 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
528
Vishnu Nair4351ad52019-02-11 14:13:02 -0800529 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700530 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800531 }
Vishnu Nairba354102022-08-01 00:14:18 +0000532
533 if (mPotentialCursor) {
534 prepareCursorCompositionState();
535 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800536}
537
Vishnu Nair60356342018-11-13 13:00:45 -0800538Rect Layer::getCroppedBufferSize(const State& s) const {
539 Rect size = getBufferSize(s);
540 Rect crop = getCrop(s);
541 if (!crop.isEmpty() && size.isValid()) {
542 size.intersect(crop, &size);
543 } else if (!crop.isEmpty()) {
544 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700545 }
Vishnu Nair60356342018-11-13 13:00:45 -0800546 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800547}
548
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700549void Layer::setupRoundedCornersCropCoordinates(Rect win,
550 const FloatRect& roundedCornersCrop) const {
551 // Translate win by the rounded corners rect coordinates, to have all values in
552 // layer coordinate space.
553 win.left -= roundedCornersCrop.left;
554 win.right -= roundedCornersCrop.left;
555 win.top -= roundedCornersCrop.top;
556 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700557}
558
Lloyd Piquede196652020-01-22 17:29:58 -0800559void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800560 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800561 const auto alpha = static_cast<float>(getAlpha());
562 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700563 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800564
565 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
566 if (!opaque || alpha != 1.0f) {
567 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
568 : Hwc2::IComposerClient::BlendMode::COVERAGE;
569 }
570
Alec Mourif4af03e2023-02-11 00:25:24 +0000571 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000572 auto* snapshot = editLayerSnapshot();
573 snapshot->outputFilter = getOutputFilter();
574 snapshot->isVisible = isVisible();
575 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
576 snapshot->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800577
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000578 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800579 contentDirty = false;
580
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000581 snapshot->geomLayerBounds = mBounds;
582 snapshot->geomLayerTransform = getTransform();
583 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
584 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000585 snapshot->localTransform = getActiveTransform(drawingState);
586 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000587 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
588 snapshot->alpha = alpha;
589 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
590 snapshot->blurRegions = drawingState.blurRegions;
591 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800592}
593
Lloyd Piquede196652020-01-22 17:29:58 -0800594void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800595 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000596 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700597
Alec Mourif4af03e2023-02-11 00:25:24 +0000598 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000599 snapshot->geomBufferSize = getBufferSize(drawingState);
600 snapshot->geomContentCrop = getBufferCrop();
601 snapshot->geomCrop = getCrop(drawingState);
602 snapshot->geomBufferTransform = getBufferTransform();
603 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
604 snapshot->geomUsesSourceCrop = usesSourceCrop();
605 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800606
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000607 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800608 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
609 for (const auto& [key, mandatory] : supportedMetadata) {
610 const auto& genericLayerMetadataCompatibilityMap =
611 mFlinger->getGenericLayerMetadataKeyMap();
612 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
613 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
614 continue;
615 }
616 const uint32_t id = compatIter->second;
617
618 auto it = drawingState.metadata.mMap.find(id);
619 if (it == std::end(drawingState.metadata.mMap)) {
620 continue;
621 }
622
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000623 snapshot->metadata.emplace(key,
624 compositionengine::GenericLayerMetadataEntry{mandatory,
625 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800626 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800627}
David Sodmanba340492018-08-05 21:51:33 -0700628
Lloyd Piquede196652020-01-22 17:29:58 -0800629void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800630 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000631 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000632 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800633
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000634 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800635
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000636 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
637 snapshot->dataspace = getDataSpace();
638 snapshot->colorTransform = getColorTransform();
639 snapshot->colorTransformIsIdentity = !hasColorTransform();
640 snapshot->surfaceDamage = surfaceDamageRegion;
641 snapshot->hasProtectedContent = isProtected();
642 snapshot->dimmingEnabled = isDimmingEnabled();
John Reck68796592023-01-25 13:47:12 -0500643 snapshot->currentSdrHdrRatio = getCurrentSdrHdrRatio();
644 snapshot->desiredSdrHdrRatio = getDesiredSdrHdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000645 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800646
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700647 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700648
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000649 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800650
651 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400652 // Rounded corners no longer force client composition, since we may use a
653 // hole punch so that the layer will appear to have rounded corners.
654 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000655 snapshot->stretchEffect.hasEffect()) {
656 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800657 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700658 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000659 snapshot->blurRegions = drawingState.blurRegions;
660 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400661
662 // Layer framerate is used in caching decisions.
663 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
664 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000665 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000666
667 if (hasBufferOrSidebandStream()) {
668 preparePerFrameBufferCompositionState();
669 } else {
670 preparePerFrameEffectsCompositionState();
671 }
672}
673
674void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000675 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000676 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000677 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000678 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
679 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000680 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
681 return;
682 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000683 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000684 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800685 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
686 snapshot->compositionType =
687 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000688 } else {
689 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000690 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
691 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000692 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
693 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
694 }
695
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000696 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000697 snapshot->acquireFence = mBufferInfo.mFence;
698 snapshot->frameNumber = mBufferInfo.mFrameNumber;
699 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000700}
701
702void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000703 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000704 auto* snapshot = editLayerSnapshot();
705 snapshot->color = getColor();
706 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000707 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800708}
709
Lloyd Piquede196652020-01-22 17:29:58 -0800710void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800711 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000712 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000713 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800714
715 // Apply the layer's transform, followed by the display's global transform
716 // Here we're guaranteed that the layer's transform preserves rects
717 Rect win = getCroppedBufferSize(drawingState);
718 // Subtract the transparent region and snap to the bounds
719 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
720 Rect frame(getTransform().transform(bounds));
721
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000722 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800723}
724
Lloyd Piquea83776c2019-01-29 18:42:32 -0800725const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700726 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800727}
728
Mathias Agopian13127d82013-03-05 17:47:11 -0800729// ---------------------------------------------------------------------------
730// drawing...
731// ---------------------------------------------------------------------------
732
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500733aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
734 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700735 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800736 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500737 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800738 }
739 if (outputLayer->getState().hwc) {
740 return (*outputLayer->getState().hwc).hwcCompositionType;
741 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500742 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800743 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800744}
745
Mathias Agopian13127d82013-03-05 17:47:11 -0800746// ----------------------------------------------------------------------------
747// local state
748// ----------------------------------------------------------------------------
749
David Sodman41fdfc92017-11-06 16:09:56 -0800750bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800751 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700752 if (s.flags & layer_state_t::eLayerSecure) {
753 return true;
754 }
755
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000756 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700757 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700758}
759
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100760void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
761 std::vector<JankData>& jankData) {
762 if (mPendingJankClassifications.empty() ||
763 !mPendingJankClassifications.front()->getJankType()) {
764 return;
765 }
766
767 bool includeJankData = false;
768 for (const auto& handle : handles) {
769 for (const auto& cb : handle->callbackIds) {
770 if (cb.includeJankData) {
771 includeJankData = true;
772 break;
773 }
774 }
775
776 if (includeJankData) {
777 jankData.reserve(mPendingJankClassifications.size());
778 break;
779 }
780 }
781
782 while (!mPendingJankClassifications.empty() &&
783 mPendingJankClassifications.front()->getJankType()) {
784 if (includeJankData) {
785 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
786 mPendingJankClassifications.front();
787 jankData.emplace_back(
788 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
789 }
790 mPendingJankClassifications.pop_front();
791 }
792}
793
Mathias Agopian13127d82013-03-05 17:47:11 -0800794// ----------------------------------------------------------------------------
795// transaction
796// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800797
Vishnu Naira156f482023-02-22 00:23:38 +0000798uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700799 ATRACE_CALL();
800
Robert Carr0758e5d2021-03-11 22:15:04 -0800801 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700802 mDrawingStateModified = mDrawingState.modified;
803 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700804
Alec Mourib416efd2018-09-06 21:01:59 +0000805 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700806
Robert Carr6a160312021-05-17 12:08:20 -0700807 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800808 // invalidate and recompute the visible regions if needed
809 flags |= Layer::eVisibleRegion;
810 }
811
Robert Carr6a160312021-05-17 12:08:20 -0700812 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800813 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000814 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800815 flags |= eVisibleRegion;
816 this->contentDirty = true;
817
818 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700819 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800820 }
821
Arthur Hung9ed43392022-05-27 06:31:57 +0000822 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
823 mFlinger->mUpdateInputInfo = true;
824 }
825
Vishnu Naira156f482023-02-22 00:23:38 +0000826 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800827
Mathias Agopian13127d82013-03-05 17:47:11 -0800828 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800829}
830
Vishnu Naira156f482023-02-22 00:23:38 +0000831void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000832 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
833 // bufferSurfaceFrameTX will be presented in latchBuffer.
834 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
835 if (surfaceFrame->getPresentState() != PresentState::Presented) {
836 // With applyPendingStates, we could end up having presented surfaceframes from previous
837 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800838 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000839 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
840 }
841 }
Robert Carr6a160312021-05-17 12:08:20 -0700842 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700843}
844
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700845uint32_t Layer::clearTransactionFlags(uint32_t mask) {
846 const auto flags = mTransactionFlags & mask;
847 mTransactionFlags &= ~mask;
848 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800849}
850
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700851void Layer::setTransactionFlags(uint32_t mask) {
852 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800853}
854
Robert Carr1f0a16a2016-10-24 16:27:39 -0700855bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
856 ssize_t idx = mCurrentChildren.indexOf(childLayer);
857 if (idx < 0) {
858 return false;
859 }
860 if (childLayer->setLayer(z)) {
861 mCurrentChildren.removeAt(idx);
862 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800863 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700864 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800865 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700866}
867
Robert Carr503c7042017-09-27 15:06:08 -0700868bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
869 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
870 ssize_t idx = mCurrentChildren.indexOf(childLayer);
871 if (idx < 0) {
872 return false;
873 }
874 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
875 mCurrentChildren.removeAt(idx);
876 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800877 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700878 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800879 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700880}
881
Robert Carrae060832016-11-28 10:51:00 -0800882bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700883 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
884 mDrawingState.sequence++;
885 mDrawingState.z = z;
886 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700887
Robert Carra70e91c2021-06-11 13:59:52 -0700888 mFlinger->mSomeChildrenChanged = true;
889
Robert Carrdb66e622017-04-10 16:55:57 -0700890 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700891 if (mDrawingState.zOrderRelativeOf != nullptr) {
892 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700893 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700894 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700895 }
chaviw606e5cf2019-03-01 10:12:10 -0800896 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700897 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800898 setTransactionFlags(eTransactionNeeded);
899 return true;
900}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700901
Robert Carrdb66e622017-04-10 16:55:57 -0700902void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700903 mDrawingState.zOrderRelatives.remove(relative);
904 mDrawingState.sequence++;
905 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700906 setTransactionFlags(eTransactionNeeded);
907}
908
909void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700910 mDrawingState.zOrderRelatives.add(relative);
911 mDrawingState.modified = true;
912 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700913 setTransactionFlags(eTransactionNeeded);
914}
915
chaviw606e5cf2019-03-01 10:12:10 -0800916void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700917 mDrawingState.zOrderRelativeOf = relativeOf;
918 mDrawingState.sequence++;
919 mDrawingState.modified = true;
920 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700921
chaviw606e5cf2019-03-01 10:12:10 -0800922 setTransactionFlags(eTransactionNeeded);
923}
924
Robert Carr503d2bd2017-12-04 15:49:47 -0800925bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000926 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700927 if (relative == nullptr) {
928 return false;
929 }
930
Robert Carr6a160312021-05-17 12:08:20 -0700931 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
932 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800933 return false;
934 }
935
Robert Carr88b85e12022-03-21 15:47:35 -0700936 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
937 (relative->mDrawingState.zOrderRelativeOf == this)) {
938 ALOGE("Detected relative layer loop between %s and %s",
939 mName.c_str(), relative->mName.c_str());
940 ALOGE("Ignoring new call to set relative layer");
941 return false;
942 }
943
Robert Carra70e91c2021-06-11 13:59:52 -0700944 mFlinger->mSomeChildrenChanged = true;
945
Robert Carr6a160312021-05-17 12:08:20 -0700946 mDrawingState.sequence++;
947 mDrawingState.modified = true;
948 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700949
Robert Carr6a160312021-05-17 12:08:20 -0700950 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700951 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700952 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700953 }
chaviw606e5cf2019-03-01 10:12:10 -0800954 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700955 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700956
957 setTransactionFlags(eTransactionNeeded);
958
959 return true;
960}
961
Winson Chunga30f7c92021-06-29 15:42:56 -0700962bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
963 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
964 mDrawingState.isTrustedOverlay = isTrustedOverlay;
965 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000966 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700967 setTransactionFlags(eTransactionNeeded);
968 return true;
969}
970
971bool Layer::isTrustedOverlay() const {
972 if (getDrawingState().isTrustedOverlay) {
973 return true;
974 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000975 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700976 return (p != nullptr) && p->isTrustedOverlay();
977}
978
Dan Stoza9e56aa02015-11-02 13:00:03 -0800979bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700980 if (mDrawingState.color.a == alpha) return false;
981 mDrawingState.sequence++;
982 mDrawingState.color.a = alpha;
983 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800984 setTransactionFlags(eTransactionNeeded);
985 return true;
986}
chaviw13fdc492017-06-27 12:40:18 -0700987
Valerie Haudd0b7572019-01-29 14:59:27 -0800988bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700989 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700990 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800991 }
Robert Carr6a160312021-05-17 12:08:20 -0700992 mDrawingState.sequence++;
993 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800994 setTransactionFlags(eTransactionNeeded);
995
Robert Carr6a160312021-05-17 12:08:20 -0700996 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -0800997 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -0800998 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700999 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001000 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08001001 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001002 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001003
Valerie Haudd0b7572019-01-29 14:59:27 -08001004 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001005 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001006 mFlinger->mLayersAdded = true;
1007 // set up SF to handle added color layer
1008 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -07001009 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001010 }
1011 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001012 } else if (mDrawingState.bgColorLayer && alpha == 0) {
1013 mDrawingState.bgColorLayer->reparent(nullptr);
1014 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001015 return true;
1016 }
1017
Robert Carr6a160312021-05-17 12:08:20 -07001018 mDrawingState.bgColorLayer->setColor(color);
1019 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1020 mDrawingState.bgColorLayer->setAlpha(alpha);
1021 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001022
chaviw13fdc492017-06-27 12:40:18 -07001023 return true;
1024}
1025
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001026bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001027 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001028
Robert Carr6a160312021-05-17 12:08:20 -07001029 mDrawingState.sequence++;
1030 mDrawingState.cornerRadius = cornerRadius;
1031 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001032 setTransactionFlags(eTransactionNeeded);
1033 return true;
1034}
1035
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001036bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001037 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001038 // If we start or stop drawing blur then the layer's visibility state may change so increment
1039 // the magic sequence number.
1040 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1041 mDrawingState.sequence++;
1042 }
Robert Carr6a160312021-05-17 12:08:20 -07001043 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1044 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001045 setTransactionFlags(eTransactionNeeded);
1046 return true;
1047}
Marissa Wall61c58622018-07-18 10:12:20 -07001048
Mathias Agopian13127d82013-03-05 17:47:11 -08001049bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001050 mDrawingState.sequence++;
1051 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001052 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001053 setTransactionFlags(eTransactionNeeded);
1054 return true;
1055}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001056
Lucas Dupinc3800b82020-10-02 16:24:48 -07001057bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001058 // If we start or stop drawing blur then the layer's visibility state may change so increment
1059 // the magic sequence number.
1060 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1061 mDrawingState.sequence++;
1062 }
Robert Carr6a160312021-05-17 12:08:20 -07001063 mDrawingState.blurRegions = blurRegions;
1064 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001065 setTransactionFlags(eTransactionNeeded);
1066 return true;
1067}
1068
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001069bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001070 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1071 if (mDrawingState.flags == newFlags) return false;
1072 mDrawingState.sequence++;
1073 mDrawingState.flags = newFlags;
1074 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001075 setTransactionFlags(eTransactionNeeded);
1076 return true;
1077}
Robert Carr99e27f02016-06-16 15:18:02 -07001078
chaviw25714502021-02-11 10:01:08 -08001079bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001080 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001081 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001082 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001083
Robert Carr6a160312021-05-17 12:08:20 -07001084 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001085 setTransactionFlags(eTransactionNeeded);
1086 return true;
1087}
Robert Carr8d5227b2017-03-16 15:41:03 -07001088
Evan Roskyef876c92019-01-25 17:46:06 -08001089bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001090 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1091 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001092 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001093 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001094}
1095
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001096bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001097 if (mDrawingState.layerStack == layerStack) return false;
1098 mDrawingState.sequence++;
1099 mDrawingState.layerStack = layerStack;
1100 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001101 setTransactionFlags(eTransactionNeeded);
1102 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001103}
1104
Peiyong Linc502cb72019-03-01 15:00:23 -08001105bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001106 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001107 return false;
1108 }
Robert Carr6a160312021-05-17 12:08:20 -07001109 mDrawingState.sequence++;
1110 mDrawingState.colorSpaceAgnostic = agnostic;
1111 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001112 setTransactionFlags(eTransactionNeeded);
1113 return true;
1114}
1115
Sally Qi81d95e62022-03-21 19:41:33 -07001116bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1117 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1118
1119 mDrawingState.sequence++;
1120 mDrawingState.dimmingEnabled = dimmingEnabled;
1121 mDrawingState.modified = true;
1122 setTransactionFlags(eTransactionNeeded);
1123 return true;
1124}
1125
Ana Krulecc84d09b2019-11-02 23:10:29 +01001126bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001127 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1128 mDrawingState.frameRateSelectionPriority = priority;
1129 mDrawingState.sequence++;
1130 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001131 setTransactionFlags(eTransactionNeeded);
1132 return true;
1133}
1134
1135int32_t Layer::getFrameRateSelectionPriority() const {
1136 // Check if layer has priority set.
1137 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1138 return mDrawingState.frameRateSelectionPriority;
1139 }
1140 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001141 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001142 if (parent != nullptr) {
1143 return parent->getFrameRateSelectionPriority();
1144 }
1145
1146 return Layer::PRIORITY_UNSET;
1147}
1148
Andy Labrada096227e2022-06-15 16:58:11 +00001149bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1150 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1151 mDrawingState.defaultFrameRateCompatibility = compatibility;
1152 mDrawingState.modified = true;
1153 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1154 setTransactionFlags(eTransactionNeeded);
1155 return true;
1156}
1157
1158scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1159 return mDrawingState.defaultFrameRateCompatibility;
1160}
1161
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001162bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1163 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1164};
1165
Vishnu Nair73908d12022-10-24 21:46:42 -07001166ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1167 bool useDrawing = state == LayerVector::StateSet::Drawing;
1168 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1169 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001170 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001171 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001172 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001173}
1174
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001175bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001176 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001177 return false;
1178 }
1179
Robert Carr6a160312021-05-17 12:08:20 -07001180 mDrawingState.sequence++;
1181 mDrawingState.shadowRadius = shadowRadius;
1182 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001183 setTransactionFlags(eTransactionNeeded);
1184 return true;
1185}
1186
Vishnu Nair6213bd92020-05-08 17:42:25 -07001187bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001188 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001189 return false;
1190 }
1191
Robert Carr6a160312021-05-17 12:08:20 -07001192 mDrawingState.sequence++;
1193 mDrawingState.fixedTransformHint = fixedTransformHint;
1194 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001195 setTransactionFlags(eTransactionNeeded);
1196 return true;
1197}
1198
John Reckcdb4ed72021-02-04 13:39:33 -05001199bool Layer::setStretchEffect(const StretchEffect& effect) {
1200 StretchEffect temp = effect;
1201 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001202 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001203 return false;
1204 }
Robert Carr6a160312021-05-17 12:08:20 -07001205 mDrawingState.sequence++;
1206 mDrawingState.stretchEffect = temp;
1207 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001208 setTransactionFlags(eTransactionNeeded);
1209 return true;
1210}
1211
John Reckc00c6692021-02-16 11:37:33 -05001212StretchEffect Layer::getStretchEffect() const {
1213 if (mDrawingState.stretchEffect.hasEffect()) {
1214 return mDrawingState.stretchEffect;
1215 }
1216
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001217 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001218 if (parent != nullptr) {
1219 auto effect = parent->getStretchEffect();
1220 if (effect.hasEffect()) {
1221 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1222 return effect;
1223 }
1224 }
1225 return StretchEffect{};
1226}
1227
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001228bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1229 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001230 return false;
1231 }
1232 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001233 mBorderWidth = width;
1234 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001235 return true;
1236}
1237
1238bool Layer::isBorderEnabled() {
1239 return mBorderEnabled;
1240}
1241
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001242float Layer::getBorderWidth() {
1243 return mBorderWidth;
1244}
1245
1246const half4& Layer::getBorderColor() {
1247 return mBorderColor;
1248}
1249
Ady Abrahama850c182021-08-04 13:04:37 -07001250bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1251 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1252 const auto frameRate = [&] {
1253 if (mDrawingState.frameRate.rate.isValid() ||
1254 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1255 return mDrawingState.frameRate;
1256 }
1257
1258 return parentFrameRate;
1259 }();
1260
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001261 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001262
1263 // The frame rate is propagated to the children
1264 bool childrenHaveFrameRate = false;
1265 for (const sp<Layer>& child : mCurrentChildren) {
1266 childrenHaveFrameRate |=
1267 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1268 }
1269
1270 // If we don't have a valid frame rate, but the children do, we set this
1271 // layer as NoVote to allow the children to control the refresh rate
1272 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1273 childrenHaveFrameRate) {
1274 *transactionNeeded |=
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001275 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001276 }
1277
1278 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1279 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001280 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001281 const auto layerVotedWithDefaultCompatibility =
1282 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1283 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1284 const auto layerVotedWithExactCompatibility =
1285 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1286 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1287 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1288}
1289
Ady Abraham60e42ea2020-03-09 19:17:31 -07001290void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001291 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001292 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001293 while (auto parent = layer->getParent()) {
1294 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001295 }
Ady Abrahama850c182021-08-04 13:04:37 -07001296 return layer;
1297 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001298
Ady Abraham60e42ea2020-03-09 19:17:31 -07001299 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001300 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001301
Ady Abrahama850c182021-08-04 13:04:37 -07001302 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001303 if (transactionNeeded) {
1304 mFlinger->setTransactionFlags(eTraversalNeeded);
1305 }
1306}
1307
Ady Abraham71c437d2020-01-31 15:56:57 -08001308bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001309 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001310 return false;
1311 }
1312
Robert Carr6a160312021-05-17 12:08:20 -07001313 mDrawingState.sequence++;
1314 mDrawingState.frameRate = frameRate;
1315 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001316
1317 updateTreeHasFrameRateVote();
1318
Steven Thomas3172e202020-01-06 19:25:30 -08001319 setTransactionFlags(eTransactionNeeded);
1320 return true;
1321}
1322
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001323void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1324 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001325 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001326
1327 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1328 // there are two transactions with the same token, the first one without a buffer and the
1329 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1330 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001331 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1332 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001333 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001334 mDrawingState.bufferSurfaceFrameTX = it->second;
1335 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1336 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1337 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001338 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001339 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001340 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1341 }
1342}
1343
1344void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1345 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001346 mDrawingState.frameTimelineInfo = info;
1347 mDrawingState.postTime = postTime;
1348 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001349 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001350
Robert Carr6a160312021-05-17 12:08:20 -07001351 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001352 bufferSurfaceFrameTX != nullptr) {
1353 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1354 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1355 // being used for BufferSurfaceFrame, don't create a new one.
1356 return;
1357 }
1358 }
1359 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1360 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1361 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001362 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1363 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001364 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001365 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001366 } else {
1367 if (it->second->getPresentState() == PresentState::Presented) {
1368 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1369 // have been from previous vsync.
1370 it->second = createSurfaceFrameForTransaction(info, postTime);
1371 }
1372 }
1373}
1374
1375void Layer::addSurfaceFrameDroppedForBuffer(
1376 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001377 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001378 surfaceFrame->setPresentState(PresentState::Dropped);
1379 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1380}
1381
1382void Layer::addSurfaceFramePresentedForBuffer(
1383 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1384 nsecs_t currentLatchTime) {
1385 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1386 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1387 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001388 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001389}
1390
1391std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1392 const FrameTimelineInfo& info, nsecs_t postTime) {
1393 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001394 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1395 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001396 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001397 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001398 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001399 // For Transactions, the post time is considered to be both queue and acquire fence time.
1400 surfaceFrame->setActualQueueTime(postTime);
1401 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001402 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1403 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001404 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001405 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001406 onSurfaceFrameCreated(surfaceFrame);
1407 return surfaceFrame;
1408}
1409
1410std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1411 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1412 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001413 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001414 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001415 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001416 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001417 // For buffers, acquire fence time will set during latch.
1418 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001419 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1420 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001421 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001422 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001423 onSurfaceFrameCreated(surfaceFrame);
1424 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001425}
1426
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001427bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001428 if (mDrawingState.frameRateForLayerTree == frameRate) {
1429 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001430 }
1431
Ady Abrahama850c182021-08-04 13:04:37 -07001432 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001433
Ady Abrahama850c182021-08-04 13:04:37 -07001434 // TODO(b/195668952): we probably don't need to dirty visible regions here
1435 // or even store frameRateForLayerTree in mDrawingState
1436 mDrawingState.sequence++;
1437 mDrawingState.modified = true;
1438 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001439
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001440 mFlinger->mScheduler
1441 ->recordLayerHistory(sequence, getLayerProps(), systemTime(),
1442 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1443 return true;
1444}
Ady Abrahama850c182021-08-04 13:04:37 -07001445
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001446bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps) {
1447 if (mDrawingState.frameRateForLayerTree == frameRate) {
1448 return false;
1449 }
1450
1451 mDrawingState.frameRateForLayerTree = frameRate;
1452 mFlinger->mScheduler
1453 ->recordLayerHistory(sequence, layerProps, systemTime(),
1454 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001455 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001456}
1457
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001458Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1459 return getDrawingState().frameRateForLayerTree;
1460}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001461
Robert Carr1f0a16a2016-10-24 16:27:39 -07001462bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001463 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001464 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001465 if (parent != nullptr && parent->isHiddenByPolicy()) {
1466 return true;
1467 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001468 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1469 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1470 if (zOrderRelativeOf != nullptr) {
1471 if (zOrderRelativeOf->isHiddenByPolicy()) {
1472 return true;
1473 }
1474 }
1475 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001476 if (CC_UNLIKELY(!isTransformValid())) {
1477 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1478 return true;
1479 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001480 return s.flags & layer_state_t::eLayerHidden;
1481}
1482
David Sodman41fdfc92017-11-06 16:09:56 -08001483uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001484 // TODO: should we do something special if mSecure is set?
1485 if (mProtectedByApp) {
1486 // need a hardware-protected path to external video sink
1487 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001488 }
Riley Andrews03414a12014-07-01 14:22:59 -07001489 if (mPotentialCursor) {
1490 usage |= GraphicBuffer::USAGE_CURSOR;
1491 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001492 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001493 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001494}
1495
Vishnu Nair71fcf912022-10-18 09:14:20 -07001496void Layer::skipReportingTransformHint() {
1497 mSkipReportingTransformHint = true;
1498}
1499
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001500void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1501 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1502 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001503 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001504
Vishnu Nair6213bd92020-05-08 17:42:25 -07001505 setTransformHint(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001506}
1507
Mathias Agopian13127d82013-03-05 17:47:11 -08001508// ----------------------------------------------------------------------------
1509// debugging
1510// ----------------------------------------------------------------------------
1511
Marissa Wall61c58622018-07-18 10:12:20 -07001512// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001513gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001514 using namespace std::string_literals;
1515
Huihong Luo05539a12022-02-23 10:29:40 -08001516 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001517 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001518 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001519 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001520 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001521 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001522
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001523 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001524 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001525 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001526 info.mX = ds.transform.tx();
1527 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001528 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001529 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001530 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001531 info.mFlags = ds.flags;
1532 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001533 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001534 info.mMatrix[0][0] = ds.transform[0][0];
1535 info.mMatrix[0][1] = ds.transform[0][1];
1536 info.mMatrix[1][0] = ds.transform[1][0];
1537 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001538 {
chaviwd62d3062019-09-04 14:48:02 -07001539 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001540 if (buffer != 0) {
1541 info.mActiveBufferWidth = buffer->getWidth();
1542 info.mActiveBufferHeight = buffer->getHeight();
1543 info.mActiveBufferStride = buffer->getStride();
1544 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001545 } else {
1546 info.mActiveBufferWidth = 0;
1547 info.mActiveBufferHeight = 0;
1548 info.mActiveBufferStride = 0;
1549 info.mActiveBufferFormat = 0;
1550 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001551 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001552 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001553 info.mIsOpaque = isOpaque(ds);
1554 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001555 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001556 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001557}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001558
Yiwei Zhang5434a782018-12-05 18:06:32 -08001559void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001560 result.append(kDumpTableRowLength, '-');
1561 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001562 result.append(" Layer name\n");
1563 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001564 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001565 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001566 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001567 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001568 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001569 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1570 result.append(kDumpTableRowLength, '-');
1571 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001572}
1573
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001574void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1575 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001576 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001577 return;
1578 }
1579
Yiwei Zhang5434a782018-12-05 18:06:32 -08001580 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001581 if (mName.length() > 77) {
1582 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001583 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001584 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001585 shortened.append(mName, mName.length() - 36);
1586 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001587 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001588 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001589 }
1590
Yiwei Zhang5434a782018-12-05 18:06:32 -08001591 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001592
Alec Mourib416efd2018-09-06 21:01:59 +00001593 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001594 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001595
Chia-I Wu1e043612018-03-01 09:45:09 -08001596 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001597 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001598 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001599 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001600 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001601 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001602 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001603 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1604 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001605 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001606 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001607 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001608 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001609 const auto frameRate = getFrameRateForLayerTree();
1610 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1611 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001612 ftl::enum_string(frameRate.type).c_str(),
1613 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001614 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001615 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001616 }
Dan Stozae22aec72016-08-01 13:20:59 -07001617
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001618 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1619 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1620
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001621 result.append(kDumpTableRowLength, '-');
1622 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001623}
Dan Stozae22aec72016-08-01 13:20:59 -07001624
Yiwei Zhang5434a782018-12-05 18:06:32 -08001625void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001626 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001627}
1628
Svetoslavd85084b2014-03-20 10:28:31 -07001629void Layer::clearFrameStats() {
1630 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001631}
1632
Jamie Gennis6547ff42013-07-16 20:12:42 -07001633void Layer::logFrameStats() {
1634 mFrameTracker.logAndResetStats(mName);
1635}
1636
Svetoslavd85084b2014-03-20 10:28:31 -07001637void Layer::getFrameStats(FrameStats* outStats) const {
1638 mFrameTracker.getStats(outStats);
1639}
1640
Vishnu Nair76554eb2022-12-09 03:38:36 +00001641void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1642 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
1643 StringAppendF(&result, "Layer %s%s pid:%d uid:%d\n", getName().c_str(), hasBuffer.c_str(),
Vishnu Naircb8be502022-10-12 19:03:23 +00001644 mOwnerPid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001645}
1646
Brian Anderson5ea5e592016-12-01 16:54:33 -08001647void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001648 const int32_t layerId = getSequence();
1649 mFlinger->mTimeStats->onDestroy(layerId);
1650 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001651}
1652
Vishnu Nair787aa782023-03-17 13:46:46 -07001653size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001654 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001655 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001656 count += 1 + child->getChildrenCount();
1657 }
1658 return count;
1659}
1660
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001661void Layer::setGameModeForTree(GameMode gameMode) {
1662 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001663 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1664 gameMode =
1665 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001666 }
1667 setGameMode(gameMode);
1668 for (const sp<Layer>& child : mCurrentChildren) {
1669 child->setGameModeForTree(gameMode);
1670 }
1671}
1672
Robert Carr1f0a16a2016-10-24 16:27:39 -07001673void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001674 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001675 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001676
Robert Carr1f0a16a2016-10-24 16:27:39 -07001677 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001678 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001679 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001680 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001681}
1682
1683ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001684 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001685 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001686
Robert Carr1323c952019-01-28 18:13:27 -08001687 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001688 const auto removeResult = mCurrentChildren.remove(layer);
1689
1690 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001691 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001692 layer->updateTreeHasFrameRateVote();
1693
1694 return removeResult;
1695}
1696
Robert Carr15eae092018-03-23 13:43:53 -07001697void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001698 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001699 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001700 const float parentShadowRadius =
1701 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001702 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001703 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001704 }
1705}
1706
chaviwf1961f72017-09-18 16:41:07 -07001707bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001708 sp<Layer> newParent;
1709 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001710 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001711 if (newParent == nullptr) {
1712 ALOGE("Unable to promote Layer handle");
1713 return false;
1714 }
1715 if (newParent == this) {
1716 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1717 return false;
1718 }
1719 }
1720
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001721 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001722 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001723 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001724 }
1725
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001726 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001727 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001728 if (!newParent->isRemovedFromCurrentState()) {
1729 addToCurrentState();
1730 } else {
1731 onRemovedFromCurrentState();
1732 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001733 } else {
1734 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001735 }
1736
chaviw06178942017-07-27 10:25:59 -07001737 return true;
1738}
1739
Peiyong Lind3788632018-09-18 16:01:31 -07001740bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001741 static const mat4 identityMatrix = mat4();
1742
Robert Carr6a160312021-05-17 12:08:20 -07001743 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001744 return false;
1745 }
Robert Carr6a160312021-05-17 12:08:20 -07001746 ++mDrawingState.sequence;
1747 mDrawingState.colorTransform = matrix;
1748 mDrawingState.hasColorTransform = matrix != identityMatrix;
1749 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001750 setTransactionFlags(eTransactionNeeded);
1751 return true;
1752}
1753
chaviwf66724d2018-11-28 16:35:21 -08001754mat4 Layer::getColorTransform() const {
1755 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001756 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001757 colorTransform = parent->getColorTransform() * colorTransform;
1758 }
1759 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001760}
1761
1762bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001763 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001764 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001765 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1766 }
1767 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001768}
1769
Chia-I Wu11481472018-05-04 10:43:19 -07001770bool Layer::isLegacyDataSpace() const {
1771 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001772 return !(getDataSpace() &
1773 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1774 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001775}
1776
Robert Carr1f0a16a2016-10-24 16:27:39 -07001777void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001778 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001779}
1780
Robert Carr6a160312021-05-17 12:08:20 -07001781int32_t Layer::getZ(LayerVector::StateSet) const {
1782 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001783}
1784
Robert Carr1c5481e2019-07-01 14:42:27 -07001785bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001786 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001787 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001788 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001789}
1790
David Sodman41fdfc92017-11-06 16:09:56 -08001791__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001792 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001793 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1794 "makeTraversalList received invalid stateSet");
1795 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1796 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001797 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001798
Robert Carr29abff82017-12-04 13:51:20 -08001799 if (state.zOrderRelatives.size() == 0) {
1800 *outSkipRelativeZUsers = true;
1801 return children;
1802 }
1803
chaviwfd462612018-05-31 16:11:27 -07001804 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001805 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001806 sp<Layer> strongRelative = weakRelative.promote();
1807 if (strongRelative != nullptr) {
1808 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001809 }
1810 }
1811
Dan Stoza412903f2017-04-27 13:42:17 -07001812 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001813 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001814 continue;
1815 }
Robert Carrdb66e622017-04-10 16:55:57 -07001816 traverse.add(child);
1817 }
1818
1819 return traverse;
1820}
1821
Robert Carr1f0a16a2016-10-24 16:27:39 -07001822/**
Robert Carrdb66e622017-04-10 16:55:57 -07001823 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001824 */
Dan Stoza412903f2017-04-27 13:42:17 -07001825void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001826 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1827 // produce a new list for traversing, including our relatives, and not including our children
1828 // who are relatives of another surface. In the case that there are no relative Z,
1829 // makeTraversalList returns our children directly to avoid significant overhead.
1830 // However in this case we need to take the responsibility for filtering children which
1831 // are relatives of another surface here.
1832 bool skipRelativeZUsers = false;
1833 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001834
Robert Carr1f0a16a2016-10-24 16:27:39 -07001835 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001836 for (; i < list.size(); i++) {
1837 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001838 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1839 continue;
1840 }
1841
chaviw301b1d82019-11-06 13:15:09 -08001842 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001843 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001844 }
Dan Stoza412903f2017-04-27 13:42:17 -07001845 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001846 }
Robert Carr29abff82017-12-04 13:51:20 -08001847
Dan Stoza412903f2017-04-27 13:42:17 -07001848 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001849 for (; i < list.size(); i++) {
1850 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001851
Robert Carr29abff82017-12-04 13:51:20 -08001852 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1853 continue;
1854 }
Dan Stoza412903f2017-04-27 13:42:17 -07001855 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001856 }
1857}
1858
1859/**
Robert Carrdb66e622017-04-10 16:55:57 -07001860 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001861 */
Dan Stoza412903f2017-04-27 13:42:17 -07001862void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1863 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001864 // See traverseInZOrder for documentation.
1865 bool skipRelativeZUsers = false;
1866 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001867
Robert Carr1f0a16a2016-10-24 16:27:39 -07001868 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001869 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001870 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001871
1872 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1873 continue;
1874 }
1875
chaviw301b1d82019-11-06 13:15:09 -08001876 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001877 break;
1878 }
Dan Stoza412903f2017-04-27 13:42:17 -07001879 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001880 }
Dan Stoza412903f2017-04-27 13:42:17 -07001881 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001882 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001883 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001884
1885 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1886 continue;
1887 }
1888
Dan Stoza412903f2017-04-27 13:42:17 -07001889 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001890 }
1891}
1892
Edgar Arriaga844fa672020-01-16 14:21:42 -08001893void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1894 visitor(this);
1895 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001896 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001897 for (const sp<Layer>& child : children) {
1898 child->traverse(state, visitor);
1899 }
1900}
1901
Vishnu Nair787aa782023-03-17 13:46:46 -07001902void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
1903 for (const sp<Layer>& child : mDrawingChildren) {
1904 visitor(child.get());
1905 }
1906}
1907
chaviw4b129c22018-04-09 16:19:43 -07001908LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1909 const std::vector<Layer*>& layersInTree) {
1910 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1911 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001912 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1913 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001914 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001915
chaviwfd462612018-05-31 16:11:27 -07001916 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001917 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1918 sp<Layer> strongRelative = weakRelative.promote();
1919 // Only add relative layers that are also descendents of the top most parent of the tree.
1920 // If a relative layer is not a descendent, then it should be ignored.
1921 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1922 traverse.add(strongRelative);
1923 }
1924 }
1925
1926 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001927 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001928 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1929 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1930 // the child here since it won't be added later as a relative.
1931 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1932 childState.zOrderRelativeOf.promote().get())) {
1933 continue;
1934 }
1935 traverse.add(child);
1936 }
1937
1938 return traverse;
1939}
1940
1941void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1942 LayerVector::StateSet stateSet,
1943 const LayerVector::Visitor& visitor) {
1944 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001945
1946 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001947 for (; i < list.size(); i++) {
1948 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001949 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001950 break;
1951 }
chaviw4b129c22018-04-09 16:19:43 -07001952 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001953 }
chaviw4b129c22018-04-09 16:19:43 -07001954
chaviwa76b2712017-09-20 12:02:26 -07001955 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001956 for (; i < list.size(); i++) {
1957 const auto& relative = list[i];
1958 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001959 }
1960}
1961
chaviw4b129c22018-04-09 16:19:43 -07001962std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1963 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1964 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1965
1966 std::vector<Layer*> layersInTree = {this};
1967 for (size_t i = 0; i < children.size(); i++) {
1968 const auto& child = children[i];
1969 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1970 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1971 }
1972
1973 return layersInTree;
1974}
1975
1976void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1977 const LayerVector::Visitor& visitor) {
1978 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1979 std::sort(layersInTree.begin(), layersInTree.end());
1980 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1981}
1982
Peiyong Linefefaac2018-08-17 12:27:51 -07001983ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001984 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001985}
1986
Garfield Tan2c1782c2022-02-16 15:25:05 -08001987bool Layer::isTransformValid() const {
1988 float transformDet = getTransform().det();
1989 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1990}
1991
chaviw13fdc492017-06-27 12:40:18 -07001992half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001993 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001994
chaviw13fdc492017-06-27 12:40:18 -07001995 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1996 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07001997}
Robert Carr6452f122017-03-21 10:41:29 -07001998
Vishnu Nair6213bd92020-05-08 17:42:25 -07001999ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002000 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002001 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2002 return fixedTransformHint;
2003 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002004 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002005 if (!p) return fixedTransformHint;
2006 return p->getFixedTransformHint();
2007}
2008
chaviw13fdc492017-06-27 12:40:18 -07002009half4 Layer::getColor() const {
2010 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002011 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002012}
Robert Carr6452f122017-03-21 10:41:29 -07002013
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002014int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002015 if (getDrawingState().backgroundBlurRadius == 0) {
2016 return 0;
2017 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002018
Vishnu Nair29810f72022-07-01 16:38:41 +00002019 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002020 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2021 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002022}
2023
Galia Peychevae0acf382021-04-12 21:22:34 +02002024const std::vector<BlurRegion> Layer::getBlurRegions() const {
2025 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002026 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002027 for (auto& region : regionsCopy) {
2028 region.alpha = region.alpha * layerAlpha;
2029 }
2030 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002031}
2032
Vishnu Naire14c6b32022-08-06 04:20:15 +00002033RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002034 // Get parent settings
2035 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002036 const auto& parent = mDrawingParent.promote();
2037 if (parent != nullptr) {
2038 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002039 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002040 ui::Transform t = getActiveTransform(getDrawingState());
2041 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002042 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002043 parentSettings.radius.x *= t.getScaleX();
2044 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002045 }
2046 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002047
2048 // Get layer settings
2049 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002050 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002051 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002052 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002053
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002054 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002055 // If the parent and the layer have rounded corner settings, use the parent settings if the
2056 // parent crop is entirely inside the layer crop.
2057 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2058 if (parentSettings.cropRect.left > layerCropRect.left &&
2059 parentSettings.cropRect.top > layerCropRect.top &&
2060 parentSettings.cropRect.right < layerCropRect.right &&
2061 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2062 return parentSettings;
2063 } else {
2064 return layerSettings;
2065 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002066 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002067 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002068 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002069 return parentSettings;
2070 }
2071 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002072}
2073
Robert Carr88b85e12022-03-21 15:47:35 -07002074bool Layer::findInHierarchy(const sp<Layer>& l) {
2075 if (l == this) {
2076 return true;
2077 }
2078 for (auto& child : mDrawingChildren) {
2079 if (child->findInHierarchy(l)) {
2080 return true;
2081 }
2082 }
2083 return false;
2084}
2085
Robert Carr1f0a16a2016-10-24 16:27:39 -07002086void Layer::commitChildList() {
2087 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2088 const auto& child = mCurrentChildren[i];
2089 child->commitChildList();
2090 }
2091 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002092 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002093 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2094 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2095 if (zOrderRelativeOf == nullptr) return;
2096 if (findInHierarchy(zOrderRelativeOf)) {
2097 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2098 zOrderRelativeOf->mName.c_str());
2099 ALOGE("Severing rel Z loop, potentially dangerous");
2100 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002101 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002102 }
2103 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002104}
2105
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002106
chaviw3277faf2021-05-19 16:45:23 -05002107void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002108 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002109 mDrawingState.touchableRegionCrop =
2110 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002111 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002112 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002113 setTransactionFlags(eTransactionNeeded);
2114}
2115
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002116LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002117 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002118 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002119 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2120
Vishnu Nair00b90132021-11-05 14:03:40 -07002121 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002122 writeCompositionStateToProto(layerProto);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002123 }
2124
chaviw08f3cb22020-01-13 13:17:21 -08002125 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002126 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002127 }
chaviw6d89e2d2020-01-14 14:42:01 -08002128
2129 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002130}
2131
Vishnu Nairea6ff812023-02-27 17:41:39 +00002132void Layer::writeCompositionStateToProto(LayerProto* layerProto) {
2133 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2134
2135 // Only populate for the primary display.
2136 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
2137 const auto compositionType = getCompositionType(*display);
2138 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
2139 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2140 [&]() { return layerProto->mutable_visible_region(); });
2141 }
2142}
2143
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002144void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002145 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002146 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002147 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002148 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002149 [&]() { return layerInfo->mutable_active_buffer(); });
2150 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2151 layerInfo->mutable_buffer_transform());
2152 }
2153 layerInfo->set_invalidate(contentDirty);
2154 layerInfo->set_is_protected(isProtected());
2155 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2156 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002157 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002158 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002159 layerInfo->set_corner_radius(
2160 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002161 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2162 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2163 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2164 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2165 [&]() { return layerInfo->mutable_position(); });
2166 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002167 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2168 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002169
Vishnu Nair00b90132021-11-05 14:03:40 -07002170 if (hasColorTransform()) {
2171 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002172 }
2173
Vishnu Nair60db8c02020-04-02 11:55:16 -07002174 LayerProtoHelper::writeToProto(mSourceBounds,
2175 [&]() { return layerInfo->mutable_source_bounds(); });
2176 LayerProtoHelper::writeToProto(mScreenBounds,
2177 [&]() { return layerInfo->mutable_screen_bounds(); });
2178 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2179 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2180 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002181}
2182
2183void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002184 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002185 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2186 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002187 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002188
chaviw766c9c52021-02-10 17:36:47 -08002189 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002190
Vishnu Nair00b90132021-11-05 14:03:40 -07002191 layerInfo->set_id(sequence);
2192 layerInfo->set_name(getName().c_str());
2193 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002194
Vishnu Nair00b90132021-11-05 14:03:40 -07002195 for (const auto& child : children) {
2196 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002197 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002198
Vishnu Nair00b90132021-11-05 14:03:40 -07002199 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2200 sp<Layer> strongRelative = weakRelative.promote();
2201 if (strongRelative != nullptr) {
2202 layerInfo->add_relatives(strongRelative->sequence);
2203 }
2204 }
2205
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002206 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002207 [&]() { return layerInfo->mutable_transparent_region(); });
2208
2209 layerInfo->set_layer_stack(getLayerStack().id);
2210 layerInfo->set_z(state.z);
2211
2212 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2213 return layerInfo->mutable_requested_position();
2214 });
2215
Vishnu Nair00b90132021-11-05 14:03:40 -07002216 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2217
2218 layerInfo->set_is_opaque(isOpaque(state));
2219
2220 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2221 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2222 LayerProtoHelper::writeToProto(state.color,
2223 [&]() { return layerInfo->mutable_requested_color(); });
2224 layerInfo->set_flags(state.flags);
2225
2226 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2227 layerInfo->mutable_requested_transform());
2228
2229 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2230 if (parent != nullptr) {
2231 layerInfo->set_parent(parent->sequence);
2232 } else {
2233 layerInfo->set_parent(-1);
2234 }
2235
2236 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2237 if (zOrderRelativeOf != nullptr) {
2238 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2239 } else {
2240 layerInfo->set_z_order_relative_of(-1);
2241 }
2242
2243 layerInfo->set_is_relative_of(state.isRelativeOf);
2244
2245 layerInfo->set_owner_uid(mOwnerUid);
2246
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002247 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002248 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002249 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002250 info = fillInputInfo(
2251 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002252 } else {
2253 info = state.inputInfo;
2254 }
2255
2256 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002257 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002258 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002259
Vishnu Nair00b90132021-11-05 14:03:40 -07002260 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002261 auto protoMap = layerInfo->mutable_metadata();
2262 for (const auto& entry : state.metadata.mMap) {
2263 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2264 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002265 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002266
2267 LayerProtoHelper::writeToProto(state.destinationFrame,
2268 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002269}
2270
Robert Carr2e102c92018-10-23 12:11:15 -07002271bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002272 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002273}
2274
Prabir Pradhan33da9462022-06-14 14:55:57 +00002275// Applies the given transform to the region, while protecting against overflows caused by any
2276// offsets. If applying the offset in the transform to any of the Rects in the region would result
2277// in an overflow, they are not added to the output Region.
2278static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2279 const std::string& debugWindowName) {
2280 // Round the translation using the same rounding strategy used by ui::Transform.
2281 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2282 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2283
2284 ui::Transform transformWithoutOffset = t;
2285 transformWithoutOffset.set(0.f, 0.f);
2286
2287 const Region transformed = transformWithoutOffset.transform(r);
2288
2289 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2290 Region ret;
2291 for (const auto& rect : transformed) {
2292 Rect newRect;
2293 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2294 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2295 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2296 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2297 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2298 debugWindowName.c_str());
2299 continue;
2300 }
2301 ret.orSelf(newRect);
2302 }
2303 return ret;
2304}
2305
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002306void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
2307 Rect tmpBounds = getInputBounds();
2308 if (!tmpBounds.isValid()) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002309 info.touchableRegion.clear();
2310 // A layer could have invalid input bounds and still expect to receive touch input if it has
2311 // replaceTouchableRegionWithCrop. For that case, the input transform needs to be calculated
2312 // correctly to determine the coordinate space for input events. Use an empty rect so that
2313 // the layer will receive input in its own layer space.
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002314 tmpBounds = Rect::EMPTY_RECT;
chaviw7e72caf2020-12-02 16:50:43 -08002315 }
2316
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002317 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2318 // frame and transform used for the layer, which determines the bounds and the coordinate space
2319 // within which the layer will receive input.
2320 //
2321 // The coordinate space within which each of the bounds are specified is explicitly documented
2322 // in the variable name. For example "inputBoundsInLayer" is specified in layer space. A
2323 // Transform converts one coordinate space to another, which is apparent in its naming. For
2324 // example, "layerToDisplay" transforms layer space to display space.
2325 //
2326 // Coordinate space definitions:
2327 // - display: The display device's coordinate space. Correlates to pixels on the display.
2328 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2329 // - layer: The coordinate space of this layer.
2330 // - input: The coordinate space in which this layer will receive input events. This could be
2331 // different than layer space if a surfaceInset is used, which changes the origin
2332 // of the input space.
2333 const FloatRect inputBoundsInLayer = tmpBounds.toFloatRect();
chaviw7e72caf2020-12-02 16:50:43 -08002334
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002335 // Clamp surface inset to the input bounds.
2336 const auto surfaceInset = static_cast<float>(info.surfaceInset);
2337 const float xSurfaceInset =
2338 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getWidth() / 2.f));
2339 const float ySurfaceInset =
2340 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getHeight() / 2.f));
chaviw1ff3d1e2020-07-01 15:53:47 -07002341
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002342 // Apply the insets to the input bounds.
2343 const FloatRect insetBoundsInLayer(inputBoundsInLayer.left + xSurfaceInset,
2344 inputBoundsInLayer.top + ySurfaceInset,
2345 inputBoundsInLayer.right - xSurfaceInset,
2346 inputBoundsInLayer.bottom - ySurfaceInset);
Ady Abraham282f1d72019-07-24 18:05:56 -07002347
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002348 // Crop the input bounds to ensure it is within the parent's bounds.
2349 const FloatRect croppedInsetBoundsInLayer = mBounds.intersect(insetBoundsInLayer);
Ady Abraham282f1d72019-07-24 18:05:56 -07002350
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002351 const ui::Transform layerToScreen = getInputTransform();
2352 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
Vishnu Nair8033a492018-12-05 07:27:23 -08002353
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002354 const Rect roundedFrameInDisplay{layerToDisplay.transform(croppedInsetBoundsInLayer)};
2355 info.frameLeft = roundedFrameInDisplay.left;
2356 info.frameTop = roundedFrameInDisplay.top;
2357 info.frameRight = roundedFrameInDisplay.right;
2358 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002359
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002360 ui::Transform inputToLayer;
2361 inputToLayer.set(insetBoundsInLayer.left, insetBoundsInLayer.top);
2362 const ui::Transform inputToDisplay = layerToDisplay * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002363
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002364 // InputDispatcher expects a display-to-input transform.
2365 info.transform = inputToDisplay.inverse();
2366
2367 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002368 info.touchableRegion =
2369 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002370}
2371
chaviw3277faf2021-05-19 16:45:23 -05002372void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002373 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002374 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002375 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002376 }
2377 if (p != nullptr) {
2378 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2379 }
2380}
2381
Vishnu Naira066d902021-09-13 18:40:17 -07002382gui::DropInputMode Layer::getDropInputMode() const {
2383 gui::DropInputMode mode = mDrawingState.dropInputMode;
2384 if (mode == gui::DropInputMode::ALL) {
2385 return mode;
2386 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002387 sp<Layer> parent = mDrawingParent.promote();
2388 if (parent) {
2389 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002390 if (parentMode != gui::DropInputMode::NONE) {
2391 return parentMode;
2392 }
2393 }
2394 return mode;
2395}
2396
2397void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002398 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002399 return;
2400 }
2401
2402 // Check if we need to drop input unconditionally
2403 gui::DropInputMode dropInputMode = getDropInputMode();
2404 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002405 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002406 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2407 return;
2408 }
2409
2410 // Check if we need to check if the window is obscured by parent
2411 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2412 return;
2413 }
2414
2415 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002416 sp<Layer> parent = mDrawingParent.promote();
2417 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002418 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002419 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2420 static_cast<float>(getAlpha()));
2421 }
2422
2423 // Check if the parent has cropped the buffer
2424 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2425 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002426 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002427 return;
2428 }
2429
2430 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2431 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2432 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2433 // match then the layer has not been cropped by its parents.
2434 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2435 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2436
2437 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002438 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002439 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2440 getDebugName());
2441 } else {
2442 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2443 // input if the window is obscured. This check should be done in surfaceflinger but the
2444 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2445 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002446 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002447 }
2448}
2449
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002450WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002451 if (!hasInputInfo()) {
2452 mDrawingState.inputInfo.name = getName();
2453 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2454 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002455 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002456 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002457 }
2458
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002459 const ui::Transform& displayTransform =
2460 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2461
chaviw3277faf2021-05-19 16:45:23 -05002462 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002463 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002464 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002465
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002466 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002467
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002468 if (displayArgs.transform == nullptr) {
2469 // Do not let the window receive touches if it is not associated with a valid display
2470 // transform. We still allow the window to receive keys and prevent ANRs.
2471 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2472 }
2473
Robert Carr5dc426e2020-06-10 14:29:14 -07002474 // For compatibility reasons we let layers which can receive input
2475 // receive input before they have actually submitted a buffer. Because
2476 // of this we use canReceiveInput instead of isVisible to check the
2477 // policy-visibility, ignoring the buffer state. However for layers with
2478 // hasInputInfo()==false we can use the real visibility state.
2479 // We are just using these layers for occlusion detection in
2480 // InputDispatcher, and obviously if they aren't visible they can't occlude
2481 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002482 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2483 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2484
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002485 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002486 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002487 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002488
Vishnu Nair16a938f2021-09-24 07:14:54 -07002489 // If the window will be blacked out on a display because the display does not have the secure
2490 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002491 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002492 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002493 }
2494
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002495 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2496 if (info.replaceTouchableRegionWithCrop) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002497 const Rect bounds(cropLayer ? cropLayer->mScreenBounds : mScreenBounds);
2498 info.touchableRegion = Region(displayTransform.transform(bounds));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002499 } else if (cropLayer != nullptr) {
[1;3C2b9fc252021-02-04 16:16:50 -08002500 info.touchableRegion = info.touchableRegion.intersect(
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002501 displayTransform.transform(Rect{cropLayer->mScreenBounds}));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002502 }
2503
Winson Chunga30f7c92021-06-29 15:42:56 -07002504 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2505 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002506 if (isTrustedOverlay()) {
2507 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2508 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002509
chaviwaf87b3e2019-10-01 16:59:28 -07002510 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2511 // touches from going outside the cloned area.
2512 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002513 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002514 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2515 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002516 info.touchableRegion = info.touchableRegion.intersect(rect);
2517 }
2518 }
2519
Robert Carr720e5062018-07-30 17:45:14 -07002520 return info;
2521}
2522
chaviwaf87b3e2019-10-01 16:59:28 -07002523sp<Layer> Layer::getClonedRoot() {
2524 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002525 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002526 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002527 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002528 return nullptr;
2529 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002530 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002531}
2532
Robert Carredd13602020-04-13 17:24:34 -07002533bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002534 return mDrawingState.inputInfo.token != nullptr ||
2535 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002536}
2537
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002538compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002539 const DisplayDevice* display) const {
2540 if (!display) return nullptr;
Vishnu Naird47bcee2023-02-24 18:08:51 +00002541 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2542 return display->getCompositionDisplay()->getOutputLayerForLayer(
2543 getCompositionEngineLayerFE());
2544 }
2545 sp<LayerFE> layerFE;
2546 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2547 for (auto& [p, layer] : mLayerFEs) {
2548 if (p == path) {
2549 layerFE = layer;
2550 }
2551 }
2552
2553 if (!layerFE) return nullptr;
2554 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002555}
2556
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002557Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2558 const auto outputLayer = findOutputLayerForDisplay(display);
2559 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002560}
2561
chaviwb4c6e582019-08-16 14:35:07 -07002562void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002563 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002564 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002565 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2566 mPotentialCursor = clonedFrom->mPotentialCursor;
2567 mProtectedByApp = clonedFrom->mProtectedByApp;
2568 updateCloneBufferInfo();
2569}
2570
2571void Layer::updateCloneBufferInfo() {
2572 if (!isClone() || !isClonedFromAlive()) {
2573 return;
2574 }
2575
2576 sp<Layer> clonedFrom = getClonedFrom();
2577 mBufferInfo = clonedFrom->mBufferInfo;
2578 mSidebandStream = clonedFrom->mSidebandStream;
2579 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2580 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2581 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2582
2583 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2584 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2585 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2586 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2587 // the cloned drawingState again.
2588 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2589 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2590 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2591 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2592
2593 cloneDrawingState(clonedFrom.get());
2594
2595 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2596 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2597 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2598 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002599}
chaviw74b03172019-08-19 11:09:03 -07002600
2601void Layer::updateMirrorInfo() {
2602 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2603 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2604 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2605 // that case, we want to delete the reference to the clone since we want it to get
2606 // destroyed. The root, this layer, will still be around since the client can continue
2607 // to hold a reference, but no cloned layers will be displayed.
2608 mClonedChild = nullptr;
2609 return;
2610 }
2611
2612 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2613 // If the real layer exists and is in current state, add the clone as a child of the root.
2614 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2615 // copied to drawingState for the root layer. So the clonedChild is always removed from
2616 // drawingState and then needs to be added back each traversal.
2617 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2618 addChildToDrawing(mClonedChild);
2619 }
2620
2621 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002622 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002623 mClonedChild->updateClonedRelatives(clonedLayersMap);
2624}
2625
2626void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2627 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2628 // to the clone. If the real layer is no longer alive, continue traversing the children
2629 // since we may be able to pull out other children that are still alive.
2630 if (isClonedFromAlive()) {
2631 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002632 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002633 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002634 }
2635
2636 // The clone layer may have children in drawingState since they may have been created and
2637 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2638 // that already exist, since we can just re-use them.
2639 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2640 // not updated in the regular traversal. They are skipped since the root will lose the
2641 // reference to them when it copies its currentChildren to drawing.
2642 for (sp<Layer>& child : mDrawingChildren) {
2643 child->updateClonedDrawingState(clonedLayersMap);
2644 }
2645}
2646
2647void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2648 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2649 mDrawingChildren.clear();
2650
2651 if (!isClonedFromAlive()) {
2652 return;
2653 }
2654
2655 sp<Layer> clonedFrom = getClonedFrom();
2656 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2657 if (child == mirrorRoot) {
2658 // This is to avoid cyclical mirroring.
2659 continue;
2660 }
2661 sp<Layer> clonedChild = clonedLayersMap[child];
2662 if (clonedChild == nullptr) {
2663 clonedChild = child->createClone();
2664 clonedLayersMap[child] = clonedChild;
2665 }
2666 addChildToDrawing(clonedChild);
2667 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2668 }
2669}
2670
chaviwaf87b3e2019-10-01 16:59:28 -07002671void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2672 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2673 if (cropLayer != nullptr) {
2674 if (clonedLayersMap.count(cropLayer) == 0) {
2675 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2676 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002677 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002678 } else {
2679 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2680 mDrawingState.touchableRegionCrop = clonedCropLayer;
2681 }
2682 }
2683 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2684 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002685 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002686}
2687
2688void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002689 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002690 mDrawingState.zOrderRelatives.clear();
2691
2692 if (!isClonedFromAlive()) {
2693 return;
2694 }
2695
chaviwaf87b3e2019-10-01 16:59:28 -07002696 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002697 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002698 const sp<Layer>& relative = relativeWeak.promote();
2699 if (clonedLayersMap.count(relative) > 0) {
2700 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002701 mDrawingState.zOrderRelatives.add(clonedRelative);
2702 }
2703 }
2704
2705 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2706 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2707 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2708 // still traverse the children, but the layer with the missing relativeOf will not be shown
2709 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002710 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2711 if (clonedLayersMap.count(relativeOf) > 0) {
2712 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002713 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2714 }
2715
chaviwaf87b3e2019-10-01 16:59:28 -07002716 updateClonedInputInfo(clonedLayersMap);
2717
chaviw74b03172019-08-19 11:09:03 -07002718 for (sp<Layer>& child : mDrawingChildren) {
2719 child->updateClonedRelatives(clonedLayersMap);
2720 }
2721}
2722
2723void Layer::addChildToDrawing(const sp<Layer>& layer) {
2724 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002725 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002726}
2727
Steven Thomas62a4cf82020-01-31 12:04:03 -08002728Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2729 switch (compatibility) {
2730 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2731 return FrameRateCompatibility::Default;
2732 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2733 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002734 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2735 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002736 case ANATIVEWINDOW_FRAME_RATE_MIN:
2737 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002738 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2739 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002740 default:
2741 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2742 return FrameRateCompatibility::Default;
2743 }
2744}
2745
Marin Shalamanovc5986772021-03-16 16:09:49 +01002746scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2747 switch (strategy) {
2748 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2749 return Seamlessness::OnlySeamless;
2750 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2751 return Seamlessness::SeamedAndSeamless;
2752 default:
2753 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2754 return Seamlessness::Default;
2755 }
2756}
2757
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002758bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002759 const State& s(mDrawingState);
2760 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2761 return true;
2762 }
2763
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002764 sp<Layer> parent = mDrawingParent.promote();
2765 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002766}
2767
Robert Carr6a0382d2021-07-01 15:57:17 -07002768void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2769 mClonedChild = clonedChild;
2770 mHadClonedChild = true;
2771 mFlinger->mNumClones++;
2772}
2773
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002774bool Layer::setDropInputMode(gui::DropInputMode mode) {
2775 if (mDrawingState.dropInputMode == mode) {
2776 return false;
2777 }
2778 mDrawingState.dropInputMode = mode;
2779 return true;
2780}
2781
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002782void Layer::cloneDrawingState(const Layer* from) {
2783 mDrawingState = from->mDrawingState;
2784 // Skip callback info since they are not applicable for cloned layers.
2785 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002786 // TODO (b/238781169) currently broken for mirror layers because we do not
2787 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002788 mDrawingState.callbackHandles = {};
2789}
2790
Patrick Williamsbb25f802022-08-30 23:02:34 +00002791void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2792 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002793 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002794 if (!listener) {
2795 return;
2796 }
2797 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002798 uint32_t currentMaxAcquiredBufferCount =
2799 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002800 listener->onReleaseBuffer({buffer->getId(), framenumber},
2801 releaseFence ? releaseFence : Fence::NO_FENCE,
2802 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002803}
2804
2805void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2806 // If we are displayed on multiple displays in a single composition cycle then we would
2807 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2808 // For example we can only use it if all the displays are client comp, and we need
2809 // to merge all the client comp fences. We could do this, but for now we just
2810 // disable the optimization when a layer is composed on multiple displays.
2811 if (mClearClientCompositionFenceOnLayerDisplayed) {
2812 mLastClientCompositionFence = nullptr;
2813 } else {
2814 mClearClientCompositionFenceOnLayerDisplayed = true;
2815 }
2816
2817 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2818 // buffer that was presented on this layer. The first transaction that came in this frame that
2819 // replaced the previous buffer on this layer needs this release fence, because the fence will
2820 // let the client know when that previous buffer is removed from the screen.
2821 //
2822 // Every other transaction on this layer does not need a release fence because no other
2823 // Transactions that were set on this layer this frame are going to have their preceding buffer
2824 // removed from the display this frame.
2825 //
2826 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2827 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2828 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2829 // the previous buffer will be released this frame. The third transaction also contains a
2830 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2831 // transaction will now no longer be presented so it is released immediately and the third
2832 // transaction doesn't need a previous release fence.
2833 sp<CallbackHandle> ch;
2834 for (auto& handle : mDrawingState.callbackHandles) {
2835 if (handle->releasePreviousBuffer &&
2836 mDrawingState.releaseBufferEndpoint == handle->listener) {
2837 ch = handle;
2838 break;
2839 }
2840 }
2841
2842 // Prevent tracing the same release multiple times.
2843 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2844 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2845 }
2846
2847 if (ch != nullptr) {
2848 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2849 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2850 ch->name = mName;
2851 }
2852}
2853
2854void Layer::onSurfaceFrameCreated(
2855 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2856 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2857 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2858 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2859 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002860 if (hasBufferOrSidebandStreamInDrawing()) {
2861 // Only log for layers with a buffer, since we expect the jank data to be drained for
2862 // these, while there may be no jank listeners for bufferless layers.
2863 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2864 mName.c_str());
2865 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2866 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2867 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002868 mPendingJankClassifications.pop_front();
2869 }
2870 mPendingJankClassifications.emplace_back(surfaceFrame);
2871}
2872
2873void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2874 for (const auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair71fcf912022-10-18 09:14:20 -07002875 handle->transformHint = mSkipReportingTransformHint
2876 ? std::nullopt
2877 : std::make_optional<uint32_t>(mTransformHint);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002878 handle->dequeueReadyTime = dequeueReadyTime;
2879 handle->currentMaxAcquiredBufferCount =
2880 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2881 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2882 handle->previousReleaseCallbackId.framenumber);
2883 }
2884
2885 for (auto& handle : mDrawingState.callbackHandles) {
2886 if (handle->releasePreviousBuffer &&
2887 mDrawingState.releaseBufferEndpoint == handle->listener) {
2888 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2889 break;
2890 }
2891 }
2892
2893 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002894 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002895 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2896 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002897 mDrawingState.callbackHandles = {};
2898}
2899
2900bool Layer::willPresentCurrentTransaction() const {
2901 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2902 return (getSidebandStreamChanged() || getAutoRefresh() ||
2903 (mDrawingState.modified &&
2904 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2905}
2906
2907bool Layer::setTransform(uint32_t transform) {
2908 if (mDrawingState.bufferTransform == transform) return false;
2909 mDrawingState.bufferTransform = transform;
2910 mDrawingState.modified = true;
2911 setTransactionFlags(eTransactionNeeded);
2912 return true;
2913}
2914
2915bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2916 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2917 mDrawingState.sequence++;
2918 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2919 mDrawingState.modified = true;
2920 setTransactionFlags(eTransactionNeeded);
2921 return true;
2922}
2923
2924bool Layer::setBufferCrop(const Rect& bufferCrop) {
2925 if (mDrawingState.bufferCrop == bufferCrop) return false;
2926
2927 mDrawingState.sequence++;
2928 mDrawingState.bufferCrop = bufferCrop;
2929
2930 mDrawingState.modified = true;
2931 setTransactionFlags(eTransactionNeeded);
2932 return true;
2933}
2934
2935bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2936 if (mDrawingState.destinationFrame == destinationFrame) return false;
2937
2938 mDrawingState.sequence++;
2939 mDrawingState.destinationFrame = destinationFrame;
2940
2941 mDrawingState.modified = true;
2942 setTransactionFlags(eTransactionNeeded);
2943 return true;
2944}
2945
2946// Translate destination frame into scale and position. If a destination frame is not set, use the
2947// provided scale and position
2948bool Layer::updateGeometry() {
2949 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2950 mDrawingState.destinationFrame.isEmpty()) {
2951 // If destination frame is not set, use the requested transform set via
2952 // Layer::setPosition and Layer::setMatrix.
2953 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2954 }
2955
2956 Rect destRect = mDrawingState.destinationFrame;
2957 int32_t destW = destRect.width();
2958 int32_t destH = destRect.height();
2959 if (destRect.left < 0) {
2960 destRect.left = 0;
2961 destRect.right = destW;
2962 }
2963 if (destRect.top < 0) {
2964 destRect.top = 0;
2965 destRect.bottom = destH;
2966 }
2967
2968 if (!mDrawingState.buffer) {
2969 ui::Transform t;
2970 t.set(destRect.left, destRect.top);
2971 return assignTransform(&mDrawingState.transform, t);
2972 }
2973
2974 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2975 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2976 // Undo any transformations on the buffer.
2977 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2978 std::swap(bufferWidth, bufferHeight);
2979 }
2980 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
2981 if (mDrawingState.transformToDisplayInverse) {
2982 if (invTransform & ui::Transform::ROT_90) {
2983 std::swap(bufferWidth, bufferHeight);
2984 }
2985 }
2986
2987 float sx = destW / static_cast<float>(bufferWidth);
2988 float sy = destH / static_cast<float>(bufferHeight);
2989 ui::Transform t;
2990 t.set(sx, 0, 0, sy);
2991 t.set(destRect.left, destRect.top);
2992 return assignTransform(&mDrawingState.transform, t);
2993}
2994
2995bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
2996 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
2997 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
2998 return false;
2999 }
3000
3001 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3002
3003 mDrawingState.sequence++;
3004 mDrawingState.modified = true;
3005 setTransactionFlags(eTransactionNeeded);
3006
3007 return true;
3008}
3009
3010bool Layer::setPosition(float x, float y) {
3011 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3012 return false;
3013 }
3014
3015 mRequestedTransform.set(x, y);
3016
3017 mDrawingState.sequence++;
3018 mDrawingState.modified = true;
3019 setTransactionFlags(eTransactionNeeded);
3020
3021 return true;
3022}
3023
3024bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3025 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3026 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003027 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003028 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003029 if (!buffer) {
3030 return false;
3031 }
3032
3033 const bool frameNumberChanged =
3034 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3035 const uint64_t frameNumber =
3036 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003037 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003038
3039 if (mDrawingState.buffer) {
3040 mReleasePreviousBuffer = true;
3041 if (!mBufferInfo.mBuffer ||
3042 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3043 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3044 // If mDrawingState has a buffer, and we are about to update again
3045 // before swapping to drawing state, then the first buffer will be
3046 // dropped and we should decrement the pending buffer count and
3047 // call any release buffer callbacks if set.
3048 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3049 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003050 mDrawingState.acquireFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003051 decrementPendingBufferCount();
3052 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3053 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3054 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
3055 mDrawingState.bufferSurfaceFrameTX.reset();
3056 }
3057 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3058 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3059 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003060 mLastClientCompositionFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003061 mLastClientCompositionFence = nullptr;
3062 }
Vishnu Nairc09c0232023-03-02 03:22:35 +00003063 } else {
3064 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3065 // we don't want to incorrectly classify a frame if we miss the desired present time.
3066 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003067 }
3068
liulijuneb489f62022-10-17 22:02:14 +08003069 mDrawingState.producerId = bufferData.producerId;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003070 mDrawingState.frameNumber = frameNumber;
3071 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3072 mDrawingState.buffer = std::move(buffer);
3073 mDrawingState.clientCacheId = bufferData.cachedBuffer;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003074 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3075 ? bufferData.acquireFence
3076 : Fence::NO_FENCE;
3077 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3078 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3079 // We latched this buffer unsiganled, so we need to pass the acquire fence
3080 // on the callback instead of just the acquire time, since it's unknown at
3081 // this point.
3082 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3083 } else {
3084 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3085 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003086 mDrawingState.latchedVsyncId = info.vsyncId;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003087 mDrawingState.modified = true;
3088 setTransactionFlags(eTransactionNeeded);
3089
3090 const int32_t layerId = getSequence();
3091 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3092 mOwnerUid, postTime, getGameMode());
3093 mDrawingState.desiredPresentTime = desiredPresentTime;
3094 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3095
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003096 if (mFlinger->mLegacyFrontEndEnabled) {
3097 recordLayerHistoryBufferUpdate(getLayerProps());
3098 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003099
3100 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3101
3102 if (dequeueTime && *dequeueTime != 0) {
3103 const uint64_t bufferId = mDrawingState.buffer->getId();
3104 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3105 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3106 FrameTracer::FrameEvent::DEQUEUE);
3107 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3108 FrameTracer::FrameEvent::QUEUE);
3109 }
3110
3111 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3112 return true;
3113}
3114
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003115void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3116 mDrawingState.desiredPresentTime = desiredPresentTime;
3117 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3118}
3119
3120void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps) {
3121 const nsecs_t presentTime = [&] {
3122 if (!mDrawingState.isAutoTimestamp) return mDrawingState.desiredPresentTime;
3123
3124 const auto prediction = mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3125 mDrawingState.latchedVsyncId);
3126 if (prediction.has_value()) return prediction->presentTime;
3127
3128 return static_cast<nsecs_t>(0);
3129 }();
3130 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3131 scheduler::LayerHistory::LayerUpdateType::Buffer);
3132}
3133
3134void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps) {
3135 const nsecs_t presentTime =
3136 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
3137 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3138 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3139}
3140
Patrick Williamsbb25f802022-08-30 23:02:34 +00003141bool Layer::setDataspace(ui::Dataspace dataspace) {
3142 mDrawingState.dataspaceRequested = true;
3143 if (mDrawingState.dataspace == dataspace) return false;
3144 mDrawingState.dataspace = dataspace;
3145 mDrawingState.modified = true;
3146 setTransactionFlags(eTransactionNeeded);
3147 return true;
3148}
3149
John Reck68796592023-01-25 13:47:12 -05003150bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
3151 if (mDrawingState.currentSdrHdrRatio == currentBufferRatio &&
3152 mDrawingState.desiredSdrHdrRatio == desiredRatio)
3153 return false;
3154 mDrawingState.currentSdrHdrRatio = currentBufferRatio;
3155 mDrawingState.desiredSdrHdrRatio = desiredRatio;
3156 mDrawingState.modified = true;
3157 setTransactionFlags(eTransactionNeeded);
3158 return true;
3159}
3160
Alec Mourif4af03e2023-02-11 00:25:24 +00003161bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3162 if (mDrawingState.cachingHint == cachingHint) return false;
3163 mDrawingState.cachingHint = cachingHint;
3164 mDrawingState.modified = true;
3165 setTransactionFlags(eTransactionNeeded);
3166 return true;
3167}
3168
Patrick Williamsbb25f802022-08-30 23:02:34 +00003169bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3170 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3171 mDrawingState.hdrMetadata = hdrMetadata;
3172 mDrawingState.modified = true;
3173 setTransactionFlags(eTransactionNeeded);
3174 return true;
3175}
3176
3177bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
3178 mDrawingState.surfaceDamageRegion = surfaceDamage;
3179 mDrawingState.modified = true;
3180 setTransactionFlags(eTransactionNeeded);
3181 return true;
3182}
3183
3184bool Layer::setApi(int32_t api) {
3185 if (mDrawingState.api == api) return false;
3186 mDrawingState.api = api;
3187 mDrawingState.modified = true;
3188 setTransactionFlags(eTransactionNeeded);
3189 return true;
3190}
3191
3192bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3193 if (mDrawingState.sidebandStream == sidebandStream) return false;
3194
3195 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3196 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3197 } else if (sidebandStream != nullptr) {
3198 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3199 }
3200
3201 mDrawingState.sidebandStream = sidebandStream;
3202 mDrawingState.modified = true;
3203 setTransactionFlags(eTransactionNeeded);
3204 if (!mSidebandStreamChanged.exchange(true)) {
3205 // mSidebandStreamChanged was false
3206 mFlinger->onLayerUpdate();
3207 }
3208 return true;
3209}
3210
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003211bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3212 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003213 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3214 if (handles.empty()) {
3215 mReleasePreviousBuffer = false;
3216 return false;
3217 }
3218
Pascal Muetschard81cef292023-02-06 12:18:52 +01003219 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003220 for (const auto& handle : handles) {
3221 // If this transaction set a buffer on this layer, release its previous buffer
3222 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3223
3224 // If this layer will be presented in this frame
3225 if (willPresent) {
3226 // If this transaction set an acquire fence on this layer, set its acquire time
3227 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3228 handle->frameNumber = mDrawingState.frameNumber;
3229
3230 // Store so latched time and release fence can be set
3231 mDrawingState.callbackHandles.push_back(handle);
3232
3233 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003234 // Queue this handle to be notified below.
3235 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003236 }
3237 }
3238
Pascal Muetschard81cef292023-02-06 12:18:52 +01003239 if (!remainingHandles.empty()) {
3240 // Notify the transaction completed threads these handles are done. These are only the
3241 // handles that were not added to the mDrawingState, which will be notified later.
3242 std::vector<JankData> jankData;
3243 transferAvailableJankData(remainingHandles, jankData);
3244 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3245 }
3246
Patrick Williamsbb25f802022-08-30 23:02:34 +00003247 mReleasePreviousBuffer = false;
3248 mCallbackHandleAcquireTimeOrFence = -1;
3249
3250 return willPresent;
3251}
3252
3253Rect Layer::getBufferSize(const State& /*s*/) const {
3254 // for buffer state layers we use the display frame size as the buffer size.
3255
3256 if (mBufferInfo.mBuffer == nullptr) {
3257 return Rect::INVALID_RECT;
3258 }
3259
3260 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3261 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3262
3263 // Undo any transformations on the buffer and return the result.
3264 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3265 std::swap(bufWidth, bufHeight);
3266 }
3267
3268 if (getTransformToDisplayInverse()) {
3269 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3270 if (invTransform & ui::Transform::ROT_90) {
3271 std::swap(bufWidth, bufHeight);
3272 }
3273 }
3274
3275 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3276}
3277
3278FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3279 if (mBufferInfo.mBuffer == nullptr) {
3280 return parentBounds;
3281 }
3282
3283 return getBufferSize(getDrawingState()).toFloatRect();
3284}
3285
3286bool Layer::fenceHasSignaled() const {
3287 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3288 return true;
3289 }
3290
3291 const bool fenceSignaled =
3292 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3293 if (!fenceSignaled) {
3294 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3295 TimeStats::LatchSkipReason::LateAcquire);
3296 }
3297
3298 return fenceSignaled;
3299}
3300
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003301void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003302 for (const auto& handle : mDrawingState.callbackHandles) {
3303 handle->refreshStartTime = refreshStartTime;
3304 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003305}
3306
3307void Layer::setAutoRefresh(bool autoRefresh) {
3308 mDrawingState.autoRefresh = autoRefresh;
3309}
3310
3311bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3312 // 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 +00003313 auto* snapshot = editLayerSnapshot();
3314 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003315
3316 if (mSidebandStreamChanged.exchange(false)) {
3317 const State& s(getDrawingState());
3318 // mSidebandStreamChanged was true
3319 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003320 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003321 if (mSidebandStream != nullptr) {
3322 setTransactionFlags(eTransactionNeeded);
3323 mFlinger->setTransactionFlags(eTraversalNeeded);
3324 }
3325 recomputeVisibleRegions = true;
3326
3327 return true;
3328 }
3329 return false;
3330}
3331
3332bool Layer::hasFrameUpdate() const {
3333 const State& c(getDrawingState());
3334 return (mDrawingStateModified || mDrawingState.modified) &&
3335 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3336}
3337
Vishnu Naird47bcee2023-02-24 18:08:51 +00003338void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003339 const State& s(getDrawingState());
3340
3341 if (!s.buffer) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003342 if (bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003343 for (auto& handle : mDrawingState.callbackHandles) {
3344 handle->latchTime = latchTime;
3345 }
3346 }
3347 return;
3348 }
3349
3350 for (auto& handle : mDrawingState.callbackHandles) {
3351 if (handle->frameNumber == mDrawingState.frameNumber) {
3352 handle->latchTime = latchTime;
3353 }
3354 }
3355
3356 const int32_t layerId = getSequence();
3357 const uint64_t bufferId = mDrawingState.buffer->getId();
3358 const uint64_t frameNumber = mDrawingState.frameNumber;
3359 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3360 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3361 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3362
3363 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3364 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3365 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3366 FrameTracer::FrameEvent::LATCH);
3367
3368 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3369 if (bufferSurfaceFrame != nullptr &&
3370 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3371 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3372 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3373 // are processing the next state.
3374 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3375 mDrawingState.acquireFenceTime->getSignalTime(),
3376 latchTime);
3377 mDrawingState.bufferSurfaceFrameTX.reset();
3378 }
3379
3380 std::deque<sp<CallbackHandle>> remainingHandles;
3381 mFlinger->getTransactionCallbackInvoker()
3382 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3383 mDrawingState.callbackHandles = remainingHandles;
3384
3385 mDrawingStateModified = false;
3386}
3387
3388void Layer::gatherBufferInfo() {
3389 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3390 decrementPendingBufferCount();
3391 }
3392
3393 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3394 mBufferInfo.mBuffer = mDrawingState.buffer;
3395 mBufferInfo.mFence = mDrawingState.acquireFence;
3396 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3397 mBufferInfo.mPixelFormat =
3398 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3399 mBufferInfo.mFrameLatencyNeeded = true;
3400 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3401 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3402 mBufferInfo.mFence = mDrawingState.acquireFence;
3403 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3404 auto lastDataspace = mBufferInfo.mDataspace;
3405 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3406 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003407 mFlinger->mHdrLayerInfoChanged = true;
3408 }
3409 if (mBufferInfo.mDesiredSdrHdrRatio != mDrawingState.desiredSdrHdrRatio) {
3410 mBufferInfo.mDesiredSdrHdrRatio = mDrawingState.desiredSdrHdrRatio;
3411 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003412 }
3413 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3414 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3415 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3416 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3417 mBufferInfo.mApi = mDrawingState.api;
3418 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003419}
3420
3421Rect Layer::computeBufferCrop(const State& s) {
3422 if (s.buffer && !s.bufferCrop.isEmpty()) {
3423 Rect bufferCrop;
3424 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3425 return bufferCrop;
3426 } else if (s.buffer) {
3427 return s.buffer->getBounds();
3428 } else {
3429 return s.bufferCrop;
3430 }
3431}
3432
3433sp<Layer> Layer::createClone() {
3434 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3435 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003436 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003437 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3438 return layer;
3439}
3440
Patrick Williamsbb25f802022-08-30 23:02:34 +00003441void Layer::decrementPendingBufferCount() {
3442 int32_t pendingBuffers = --mPendingBufferTransactions;
3443 tracePendingBufferCount(pendingBuffers);
3444}
3445
3446void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3447 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3448}
3449
3450/*
3451 * We don't want to send the layer's transform to input, but rather the
3452 * parent's transform. This is because Layer's transform is
3453 * information about how the buffer is placed on screen. The parent's
3454 * transform makes more sense to send since it's information about how the
3455 * layer is placed on screen. This transform is used by input to determine
3456 * how to go from screen space back to window space.
3457 */
3458ui::Transform Layer::getInputTransform() const {
3459 if (!hasBufferOrSidebandStream()) {
3460 return getTransform();
3461 }
3462 sp<Layer> parent = mDrawingParent.promote();
3463 if (parent == nullptr) {
3464 return ui::Transform();
3465 }
3466
3467 return parent->getTransform();
3468}
3469
3470/**
3471 * Similar to getInputTransform, we need to update the bounds to include the transform.
3472 * This is because bounds don't include the buffer transform, where the input assumes
3473 * that's already included.
3474 */
3475Rect Layer::getInputBounds() const {
3476 if (!hasBufferOrSidebandStream()) {
3477 return getCroppedBufferSize(getDrawingState());
3478 }
3479
3480 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
3481 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
3482 return bufferBounds;
3483 }
3484 return mDrawingState.transform.transform(bufferBounds);
3485}
3486
3487bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3488 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3489
3490 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3491 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3492 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3493 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3494 layer_state_t::eReparent;
3495
3496 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3497 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3498 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3499 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3500 layer_state_t::eInputInfoChanged;
3501
3502 if ((s.what & requiredFlags) != requiredFlags) {
3503 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3504 (s.what | requiredFlags) & ~s.what);
3505 return false;
3506 }
3507
3508 if (s.what & deniedFlags) {
3509 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3510 return false;
3511 }
3512
3513 if (s.what & allowedFlags) {
3514 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3515 }
3516
3517 if (s.what & layer_state_t::ePositionChanged) {
3518 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3519 ALOGV("%s: false [ePositionChanged changed]", __func__);
3520 return false;
3521 }
3522 }
3523
3524 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003525 if (mDrawingState.color.a != s.color.a) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003526 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3527 return false;
3528 }
3529 }
3530
3531 if (s.what & layer_state_t::eColorTransformChanged) {
3532 if (mDrawingState.colorTransform != s.colorTransform) {
3533 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3534 return false;
3535 }
3536 }
3537
3538 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003539 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003540 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3541 return false;
3542 }
3543 }
3544
3545 if (s.what & layer_state_t::eMatrixChanged) {
3546 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3547 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3548 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3549 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3550 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3551 return false;
3552 }
3553 }
3554
3555 if (s.what & layer_state_t::eCornerRadiusChanged) {
3556 if (mDrawingState.cornerRadius != s.cornerRadius) {
3557 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3558 return false;
3559 }
3560 }
3561
3562 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3563 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3564 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3565 return false;
3566 }
3567 }
3568
Vishnu Nairbbceb462022-10-10 04:52:13 +00003569 if (s.what & layer_state_t::eBufferTransformChanged) {
3570 if (mDrawingState.bufferTransform != s.bufferTransform) {
3571 ALOGV("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003572 return false;
3573 }
3574 }
3575
3576 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3577 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3578 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3579 return false;
3580 }
3581 }
3582
3583 if (s.what & layer_state_t::eCropChanged) {
3584 if (mDrawingState.crop != s.crop) {
3585 ALOGV("%s: false [eCropChanged changed]", __func__);
3586 return false;
3587 }
3588 }
3589
3590 if (s.what & layer_state_t::eDataspaceChanged) {
3591 if (mDrawingState.dataspace != s.dataspace) {
3592 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3593 return false;
3594 }
3595 }
3596
3597 if (s.what & layer_state_t::eHdrMetadataChanged) {
3598 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3599 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3600 return false;
3601 }
3602 }
3603
3604 if (s.what & layer_state_t::eSidebandStreamChanged) {
3605 if (mDrawingState.sidebandStream != s.sidebandStream) {
3606 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3607 return false;
3608 }
3609 }
3610
3611 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3612 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3613 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3614 return false;
3615 }
3616 }
3617
3618 if (s.what & layer_state_t::eShadowRadiusChanged) {
3619 if (mDrawingState.shadowRadius != s.shadowRadius) {
3620 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3621 return false;
3622 }
3623 }
3624
3625 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3626 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3627 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3628 return false;
3629 }
3630 }
3631
3632 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3633 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3634 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3635 return false;
3636 }
3637 }
3638
3639 if (s.what & layer_state_t::eStretchChanged) {
3640 StretchEffect temp = s.stretchEffect;
3641 temp.sanitize();
3642 if (mDrawingState.stretchEffect != temp) {
3643 ALOGV("%s: false [eStretchChanged changed]", __func__);
3644 return false;
3645 }
3646 }
3647
3648 if (s.what & layer_state_t::eBufferCropChanged) {
3649 if (mDrawingState.bufferCrop != s.bufferCrop) {
3650 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3651 return false;
3652 }
3653 }
3654
3655 if (s.what & layer_state_t::eDestinationFrameChanged) {
3656 if (mDrawingState.destinationFrame != s.destinationFrame) {
3657 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3658 return false;
3659 }
3660 }
3661
3662 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3663 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3664 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3665 return false;
3666 }
3667 }
3668
John Reck68796592023-01-25 13:47:12 -05003669 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
3670 if (mDrawingState.currentSdrHdrRatio != s.currentSdrHdrRatio ||
3671 mDrawingState.desiredSdrHdrRatio != s.desiredSdrHdrRatio) {
3672 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3673 return false;
3674 }
3675 }
3676
Patrick Williamsbb25f802022-08-30 23:02:34 +00003677 ALOGV("%s: true", __func__);
3678 return true;
3679}
3680
3681bool Layer::isHdrY410() const {
3682 // pixel format is HDR Y410 masquerading as RGBA_1010102
3683 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3684 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3685 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3686}
3687
Vishnu Naire14c6b32022-08-06 04:20:15 +00003688sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003689 // There's no need to get a CE Layer if the layer isn't going to draw anything.
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003690 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003691}
3692
Vishnu Naire14c6b32022-08-06 04:20:15 +00003693const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003694 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003695}
3696
Vishnu Naire14c6b32022-08-06 04:20:15 +00003697LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003698 return mSnapshot.get();
3699}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003700
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003701std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3702 return std::move(mSnapshot);
3703}
3704
3705void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3706 mSnapshot = std::move(snapshot);
3707}
3708
Patrick Williamsbb25f802022-08-30 23:02:34 +00003709const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003710 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003711}
3712
Patrick Williams7584c6a2022-10-29 02:10:58 +00003713sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003714 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003715 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3716 return result;
3717}
3718
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003719sp<LayerFE> Layer::getCompositionEngineLayerFE(
3720 const frontend::LayerHierarchy::TraversalPath& path) {
3721 for (auto& [p, layerFE] : mLayerFEs) {
3722 if (p == path) {
3723 return layerFE;
3724 }
3725 }
3726 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3727 mLayerFEs.emplace_back(path, layerFE);
3728 return layerFE;
3729}
3730
Patrick Williamsbb25f802022-08-30 23:02:34 +00003731void Layer::useSurfaceDamage() {
3732 if (mFlinger->mForceFullDamage) {
3733 surfaceDamageRegion = Region::INVALID_REGION;
3734 } else {
3735 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3736 }
3737}
3738
3739void Layer::useEmptyDamage() {
3740 surfaceDamageRegion.clear();
3741}
3742
3743bool Layer::isOpaque(const Layer::State& s) const {
3744 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3745 // layer's opaque flag.
3746 if (!hasSomethingToDraw()) {
3747 return false;
3748 }
3749
3750 // if the layer has the opaque flag, then we're always opaque
3751 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3752 return true;
3753 }
3754
3755 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003756 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003757 return true;
3758 }
3759
3760 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3761 return fillsColor() && getAlpha() == 1.0_hf;
3762}
3763
3764bool Layer::canReceiveInput() const {
3765 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3766}
3767
3768bool Layer::isVisible() const {
3769 if (!hasSomethingToDraw()) {
3770 return false;
3771 }
3772
3773 if (isHiddenByPolicy()) {
3774 return false;
3775 }
3776
3777 return getAlpha() > 0.0f || hasBlur();
3778}
3779
3780void Layer::onPostComposition(const DisplayDevice* display,
3781 const std::shared_ptr<FenceTime>& glDoneFence,
3782 const std::shared_ptr<FenceTime>& presentFence,
3783 const CompositorTiming& compositorTiming) {
3784 // mFrameLatencyNeeded is true when a new frame was latched for the
3785 // composition.
3786 if (!mBufferInfo.mFrameLatencyNeeded) return;
3787
3788 for (const auto& handle : mDrawingState.callbackHandles) {
3789 handle->gpuCompositionDoneFence = glDoneFence;
3790 handle->compositorTiming = compositorTiming;
3791 }
3792
3793 // Update mFrameTracker.
3794 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3795 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3796
3797 const int32_t layerId = getSequence();
3798 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3799
3800 const auto outputLayer = findOutputLayerForDisplay(display);
3801 if (outputLayer && outputLayer->requiresClientComposition()) {
3802 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3803 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3804 clientCompositionTimestamp,
3805 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3806 // Update the SurfaceFrames in the drawing state
3807 if (mDrawingState.bufferSurfaceFrameTX) {
3808 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3809 }
3810 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3811 surfaceFrame->setGpuComposition();
3812 }
3813 }
3814
3815 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3816 if (frameReadyFence->isValid()) {
3817 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3818 } else {
3819 // There was no fence for this frame, so assume that it was ready
3820 // to be presented at the desired present time.
3821 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3822 }
3823
3824 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08003825 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003826 const std::optional<Fps> renderRate =
3827 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3828
3829 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3830 const auto gameMode = getGameMode();
3831
3832 if (presentFence->isValid()) {
3833 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3834 refreshRate, renderRate, vote, gameMode);
3835 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3836 presentFence,
3837 FrameTracer::FrameEvent::PRESENT_FENCE);
3838 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3839 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3840 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003841 // The HWC doesn't support present fences, so use the present timestamp instead.
3842 const nsecs_t presentTimestamp =
3843 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3844
3845 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3846 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3847 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3848
Patrick Williamsbb25f802022-08-30 23:02:34 +00003849 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3850 refreshRate, renderRate, vote, gameMode);
3851 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3852 mCurrentFrameNumber, actualPresentTime,
3853 FrameTracer::FrameEvent::PRESENT_FENCE);
3854 mFrameTracker.setActualPresentTime(actualPresentTime);
3855 }
3856 }
3857
3858 mFrameTracker.advanceFrame();
3859 mBufferInfo.mFrameLatencyNeeded = false;
3860}
3861
3862bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003863 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
3864 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
3865}
3866
3867bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003868 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3869 getDrawingState().frameNumber);
3870
3871 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3872
3873 if (refreshRequired) {
3874 return refreshRequired;
3875 }
3876
3877 // If the head buffer's acquire fence hasn't signaled yet, return and
3878 // try again later
3879 if (!fenceHasSignaled()) {
3880 ATRACE_NAME("!fenceHasSignaled()");
3881 mFlinger->onLayerUpdate();
3882 return false;
3883 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00003884 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003885 if (mDrawingState.buffer == nullptr) {
3886 return false;
3887 }
3888
3889 // Capture the old state of the layer for comparisons later
3890 BufferInfo oldBufferInfo = mBufferInfo;
3891 const bool oldOpacity = isOpaque(mDrawingState);
3892 mPreviousFrameNumber = mCurrentFrameNumber;
3893 mCurrentFrameNumber = mDrawingState.frameNumber;
3894 gatherBufferInfo();
3895
3896 if (oldBufferInfo.mBuffer == nullptr) {
3897 // the first time we receive a buffer, we need to trigger a
3898 // geometry invalidation.
3899 recomputeVisibleRegions = true;
3900 }
3901
3902 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3903 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3904 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3905 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3906 recomputeVisibleRegions = true;
3907 }
3908
3909 if (oldBufferInfo.mBuffer != nullptr) {
3910 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3911 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3912 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3913 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3914 recomputeVisibleRegions = true;
3915 }
3916 }
3917
3918 if (oldOpacity != isOpaque(mDrawingState)) {
3919 recomputeVisibleRegions = true;
3920 }
3921
3922 return true;
3923}
3924
3925bool Layer::hasReadyFrame() const {
3926 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
3927}
3928
3929bool Layer::isProtected() const {
3930 return (mBufferInfo.mBuffer != nullptr) &&
3931 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
3932}
3933
Patrick Williamsbb25f802022-08-30 23:02:34 +00003934void Layer::latchAndReleaseBuffer() {
3935 if (hasReadyFrame()) {
3936 bool ignored = false;
3937 latchBuffer(ignored, systemTime());
3938 }
3939 releasePendingBuffer(systemTime());
3940}
3941
3942PixelFormat Layer::getPixelFormat() const {
3943 return mBufferInfo.mPixelFormat;
3944}
3945
3946bool Layer::getTransformToDisplayInverse() const {
3947 return mBufferInfo.mTransformToDisplayInverse;
3948}
3949
3950Rect Layer::getBufferCrop() const {
3951 // this is the crop rectangle that applies to the buffer
3952 // itself (as opposed to the window)
3953 if (!mBufferInfo.mCrop.isEmpty()) {
3954 // if the buffer crop is defined, we use that
3955 return mBufferInfo.mCrop;
3956 } else if (mBufferInfo.mBuffer != nullptr) {
3957 // otherwise we use the whole buffer
3958 return mBufferInfo.mBuffer->getBounds();
3959 } else {
3960 // if we don't have a buffer yet, we use an empty/invalid crop
3961 return Rect();
3962 }
3963}
3964
3965uint32_t Layer::getBufferTransform() const {
3966 return mBufferInfo.mTransform;
3967}
3968
3969ui::Dataspace Layer::getDataSpace() const {
3970 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
3971}
3972
3973ui::Dataspace Layer::getRequestedDataSpace() const {
3974 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
3975}
3976
3977ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
3978 ui::Dataspace updatedDataspace = dataspace;
3979 // translate legacy dataspaces to modern dataspaces
3980 switch (dataspace) {
3981 case ui::Dataspace::SRGB:
3982 updatedDataspace = ui::Dataspace::V0_SRGB;
3983 break;
3984 case ui::Dataspace::SRGB_LINEAR:
3985 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
3986 break;
3987 case ui::Dataspace::JFIF:
3988 updatedDataspace = ui::Dataspace::V0_JFIF;
3989 break;
3990 case ui::Dataspace::BT601_625:
3991 updatedDataspace = ui::Dataspace::V0_BT601_625;
3992 break;
3993 case ui::Dataspace::BT601_525:
3994 updatedDataspace = ui::Dataspace::V0_BT601_525;
3995 break;
3996 case ui::Dataspace::BT709:
3997 updatedDataspace = ui::Dataspace::V0_BT709;
3998 break;
3999 default:
4000 break;
4001 }
4002
4003 return updatedDataspace;
4004}
4005
4006sp<GraphicBuffer> Layer::getBuffer() const {
4007 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4008}
4009
Patrick Williamsbb25f802022-08-30 23:02:34 +00004010void Layer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
4011 mTransformHint = getFixedTransformHint();
4012 if (mTransformHint == ui::Transform::ROT_INVALID) {
4013 mTransformHint = displayTransformHint;
4014 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004015 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004016}
4017
4018const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4019 return mBufferInfo.mBuffer;
4020}
4021
4022bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004023 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004024 return false;
4025 }
4026
4027 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004028 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004029 mDrawingState.modified = true;
4030 setTransactionFlags(eTransactionNeeded);
4031 return true;
4032}
4033
4034bool Layer::fillsColor() const {
4035 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4036 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4037}
4038
4039bool Layer::hasBlur() const {
4040 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4041}
4042
Vishnu Nairba354102022-08-01 00:14:18 +00004043void Layer::updateSnapshot(bool updateGeometry) {
4044 if (!getCompositionEngineLayerFE()) {
4045 return;
4046 }
4047
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004048 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004049 if (updateGeometry) {
4050 prepareBasicGeometryCompositionState();
4051 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004052 snapshot->roundedCorner = getRoundedCornerState();
4053 snapshot->stretchEffect = getStretchEffect();
4054 snapshot->transformedBounds = mScreenBounds;
4055 if (mEffectiveShadowRadius > 0.f) {
4056 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4057
4058 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4059 // it if transparent regions are present. This may not be necessary since shadows are
4060 // typically cast by layers without transparent regions.
4061 snapshot->shadowSettings.boundaries = mBounds;
4062
4063 const float casterAlpha = snapshot->alpha;
4064 const bool casterIsOpaque =
4065 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4066
4067 // If the casting layer is translucent, we need to fill in the shadow underneath the
4068 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4069 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4070 snapshot->shadowSettings.ambientColor *= casterAlpha;
4071 snapshot->shadowSettings.spotColor *= casterAlpha;
4072 }
4073 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004074 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004075 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004076 snapshot->layerOpaqueFlagSet =
4077 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004078 snapshot->isHdrY410 = isHdrY410();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004079 sp<Layer> p = mDrawingParent.promote();
4080 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004081 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004082 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004083 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004084 }
4085 snapshot->bufferSize = getBufferSize(mDrawingState);
4086 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004087 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004088 preparePerFrameCompositionState();
4089}
4090
Vishnu Naire14c6b32022-08-06 04:20:15 +00004091void Layer::updateChildrenSnapshots(bool updateGeometry) {
4092 for (const sp<Layer>& child : mDrawingChildren) {
4093 child->updateSnapshot(updateGeometry);
4094 child->updateChildrenSnapshots(updateGeometry);
4095 }
4096}
4097
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004098void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4099 mSnapshot->layerMetadata = parentMetadata;
4100 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4101 for (const sp<Layer>& child : mDrawingChildren) {
4102 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4103 }
4104}
4105
4106void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4107 std::unordered_set<Layer*>& visited) {
4108 if (visited.find(this) != visited.end()) {
4109 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4110 return;
4111 }
4112 visited.insert(this);
4113
4114 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4115
4116 if (mDrawingState.zOrderRelatives.empty()) {
4117 return;
4118 }
4119 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4120 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4121 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4122 sp<Layer> relative = weakRelative.promote();
4123 if (!relative) {
4124 continue;
4125 }
4126 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4127 }
4128}
4129
Chavi Weingarten328a8312023-01-26 21:17:52 +00004130bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004131 TrustedPresentationListener const& listener) {
4132 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4133 mTrustedPresentationListener = listener;
4134 mTrustedPresentationThresholds = thresholds;
4135 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4136 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4137 mFlinger->mNumTrustedPresentationListeners++;
4138 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4139 mFlinger->mNumTrustedPresentationListeners--;
4140 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004141
4142 // Reset trusted presentation states to ensure we start the time again.
4143 mEnteredTrustedPresentationStateTime = -1;
4144 mLastReportedTrustedPresentationState = false;
4145 mLastComputedTrustedPresentationState = false;
4146
4147 // If there's a new trusted presentation listener, the code needs to go through the composite
4148 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4149 // we're already in the requested state.
4150 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004151}
4152
Vishnu Naira156f482023-02-22 00:23:38 +00004153void Layer::updateLastLatchTime(nsecs_t latchTime) {
4154 mLastLatchTime = latchTime;
4155}
4156
Mathias Agopian13127d82013-03-05 17:47:11 -08004157// ---------------------------------------------------------------------------
4158
Marin Shalamanov46084422020-10-13 12:33:42 +02004159std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004160 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4161 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004162}
4163
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004164} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004165
4166#if defined(__gl_h_)
4167#error "don't include gl/gl.h in this file"
4168#endif
4169
4170#if defined(__gl2_h_)
4171#error "don't include gl2/gl2.h in this file"
4172#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004173
4174// TODO(b/129481165): remove the #pragma below and fix conversion issues
4175#pragma clang diagnostic pop // ignored "-Wconversion"