blob: ded607eb49c2cc81de006b141b7183f2454cec6e [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
Dominik Laskowski933f8de2023-01-20 13:15:51 -0500199 mFrameTracker.setDisplayRefreshPeriod(args.flinger->mScheduler->getLeaderVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700200
Vishnu Naircb8be502022-10-12 19:03:23 +0000201 mOwnerUid = args.ownerUid;
202 mOwnerPid = args.ownerPid;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000203
204 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
205 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
206 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
207 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000208
209 mSnapshot->sequence = sequence;
210 mSnapshot->name = getDebugName();
211 mSnapshot->textureName = mTextureName;
212 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000213 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800214}
215
216void Layer::onFirstRef() {
217 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700218}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700219
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700220Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000221 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
222 "Layer destructor called off the main thread.");
223
Patrick Williamsbb25f802022-08-30 23:02:34 +0000224 // The original layer and the clone layer share the same texture and buffer. Therefore, only
225 // one of the layers, in this case the original layer, needs to handle the deletion. The
226 // original layer and the clone should be removed at the same time so there shouldn't be any
227 // issue with the clone layer trying to use the texture.
228 if (mBufferInfo.mBuffer != nullptr) {
229 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
230 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800231 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000232 }
233 if (!isClone()) {
234 // The original layer and the clone layer share the same texture. Therefore, only one of
235 // the layers, in this case the original layer, needs to handle the deletion. The original
236 // layer and the clone should be removed at the same time so there shouldn't be any issue
237 // with the clone layer trying to use the deleted texture.
238 mFlinger->deleteTextureAsync(mTextureName);
239 }
240 const int32_t layerId = getSequence();
241 mFlinger->mTimeStats->onDestroy(layerId);
242 mFlinger->mFrameTracer->onDestroy(layerId);
243
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000244 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700245 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700246
247 if (mDrawingState.sidebandStream != nullptr) {
248 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
249 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700250 if (mHadClonedChild) {
251 mFlinger->mNumClones--;
252 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000253 if (hasTrustedPresentationListener()) {
254 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000255 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000256 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700257}
258
Mathias Agopian13127d82013-03-05 17:47:11 -0800259// ---------------------------------------------------------------------------
260// callbacks
261// ---------------------------------------------------------------------------
262
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700263void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700264 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700265 return;
266 }
Robert Carr2e102c92018-10-23 12:11:15 -0700267
Robert Carr6a160312021-05-17 12:08:20 -0700268 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700269 if (strongRelative == nullptr) {
270 setZOrderRelativeOf(nullptr);
271 return;
272 }
273
274 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700275 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700276 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800277 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700278 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700279}
280
281void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700282 if (!mRemovedFromDrawingState) {
283 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700284 mFlinger->mScheduler->deregisterLayer(this);
285 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000286 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000287
Ady Abrahamd11bade2022-08-01 16:18:03 -0700288 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700289}
Chia-I Wu38512252017-05-17 14:36:16 -0700290
chaviw68d4dab2020-06-08 15:07:32 -0700291sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000292 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700293 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700294 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700295 }
296 return parent->getRootLayer();
297}
298
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700299void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700300 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
301 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700302 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700303
304 traverse(LayerVector::StateSet::Current, [&](Layer* layer) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700305 layer->removeFromCurrentState();
306 layer->removeRelativeZ(layersInTree);
chaviw68d4dab2020-06-08 15:07:32 -0700307 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700308}
309
chaviw61626f22018-11-15 16:26:27 -0800310void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700311 if (mRemovedFromDrawingState) {
312 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700313 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700314 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700315 }
chaviw61626f22018-11-15 16:26:27 -0800316
317 for (const auto& child : mCurrentChildren) {
318 child->addToCurrentState();
319 }
320}
321
Mathias Agopian13127d82013-03-05 17:47:11 -0800322// ---------------------------------------------------------------------------
323// set-up
324// ---------------------------------------------------------------------------
325
chaviw13fdc492017-06-27 12:40:18 -0700326bool Layer::getPremultipledAlpha() const {
327 return mPremultipliedAlpha;
328}
329
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700330sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800331 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700332 if (mGetHandleCalled) {
333 ALOGE("Get handle called twice" );
334 return nullptr;
335 }
336 mGetHandleCalled = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000337 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800338}
339
340// ---------------------------------------------------------------------------
341// h/w composer set-up
342// ---------------------------------------------------------------------------
343
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700344static Rect reduce(const Rect& win, const Region& exclude) {
345 if (CC_LIKELY(exclude.isEmpty())) {
346 return win;
347 }
348 if (exclude.isRect()) {
349 return win.reduce(exclude.getBounds());
350 }
351 return Region(win).subtract(exclude).getBounds();
352}
353
Dan Stoza80d61162017-12-20 15:57:52 -0800354static FloatRect reduce(const FloatRect& win, const Region& exclude) {
355 if (CC_LIKELY(exclude.isEmpty())) {
356 return win;
357 }
358 // Convert through Rect (by rounding) for lack of FloatRegion
359 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
360}
361
Vishnu Nair4351ad52019-02-11 14:13:02 -0800362Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800363 if (!reduceTransparentRegion) {
364 return Rect{mScreenBounds};
365 }
366
367 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800368 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800369 // Transform to screen space.
370 bounds = t.transform(bounds);
371 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700372}
373
Vishnu Nair4351ad52019-02-11 14:13:02 -0800374FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000375 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800376 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700377}
378
Vishnu Nairf0c28512019-02-08 12:40:28 -0800379FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
380 // Subtract the transparent region and snap to the bounds.
381 return reduce(mBounds, activeTransparentRegion);
382}
383
Chavi Weingarten076acac2023-01-19 17:20:43 +0000384// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000385void Layer::updateTrustedPresentationState(const DisplayDevice* display,
386 const frontend::LayerSnapshot* snapshot,
387 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000388 if (!hasTrustedPresentationListener()) {
389 return;
390 }
391 const bool lastState = mLastComputedTrustedPresentationState;
392 mLastComputedTrustedPresentationState = false;
393
394 if (!leaveState) {
395 const auto outputLayer = findOutputLayerForDisplay(display);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000396 if (outputLayer != nullptr) {
397 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
398 Region coveredRegion =
399 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
400 mLastComputedTrustedPresentationState =
401 computeTrustedPresentationState(snapshot->geomLayerBounds,
402 snapshot->sourceBounds(), coveredRegion,
403 snapshot->transformedBounds,
404 snapshot->alpha,
405 snapshot->geomLayerTransform,
406 mTrustedPresentationThresholds);
407 } else {
408 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
409 "TrustedPresentationState",
410 getDebugName());
411 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000412 }
413 }
414 const bool newState = mLastComputedTrustedPresentationState;
415 if (lastState && !newState) {
416 // We were in the trusted presentation state, but now we left it,
417 // emit the callback if needed
418 if (mLastReportedTrustedPresentationState) {
419 mLastReportedTrustedPresentationState = false;
420 mTrustedPresentationListener.invoke(false);
421 }
422 // Reset the timer
423 mEnteredTrustedPresentationStateTime = -1;
424 } else if (!lastState && newState) {
425 // We were not in the trusted presentation state, but we entered it, begin the timer
426 // and make sure this gets called at least once more!
427 mEnteredTrustedPresentationStateTime = time_in_ms;
428 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
429 }
430
431 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
432 if (!mLastReportedTrustedPresentationState && newState &&
433 (time_in_ms - mEnteredTrustedPresentationStateTime >
434 mTrustedPresentationThresholds.stabilityRequirementMs)) {
435 mLastReportedTrustedPresentationState = true;
436 mTrustedPresentationListener.invoke(true);
437 }
438}
439
440/**
441 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
442 * of how the parameters and thresholds are interpreted. The general spirit is
443 * to produce an upper bound on the amount of the buffer which was presented.
444 */
445bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
446 const Region& coveredRegion,
447 const FloatRect& screenBounds, float alpha,
448 const ui::Transform& effectiveTransform,
449 const TrustedPresentationThresholds& thresholds) {
450 if (alpha < thresholds.minAlpha) {
451 return false;
452 }
453 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
454 return false;
455 }
456 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
457 return false;
458 }
459
460 const float sx = effectiveTransform.dsdx();
461 const float sy = effectiveTransform.dsdy();
462 float fractionRendered = std::min(sx * sy, 1.0f);
463
464 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
465 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
466 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
467
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000468 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
469 // Compute the size of all the rects since they may be disconnected.
470 float coveredSize = 0;
471 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
472 float size = rect->width() * rect->height();
473 coveredSize += size;
474 }
475
476 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000477
478 if (fractionRendered < thresholds.minFractionRendered) {
479 return false;
480 }
481
482 return true;
483}
484
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700485void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
486 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800487 const State& s(getDrawingState());
488
489 // Calculate effective layer transform
490 mEffectiveTransform = parentTransform * getActiveTransform(s);
491
Garfield Tan2c1782c2022-02-16 15:25:05 -0800492 if (CC_UNLIKELY(!isTransformValid())) {
493 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
494 getDebugName());
495 return;
496 }
497
Vishnu Nair4351ad52019-02-11 14:13:02 -0800498 // Transform parent bounds to layer space
499 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
500
Vishnu Nairc652ff82019-03-15 12:48:54 -0700501 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800502 mSourceBounds = computeSourceBounds(parentBounds);
503
504 // Calculate bounds by croping diplay frame with layer crop and parent bounds
505 FloatRect bounds = mSourceBounds;
506 const Rect layerCrop = getCrop(s);
507 if (!layerCrop.isEmpty()) {
508 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
509 }
510 bounds = bounds.intersect(parentBounds);
511
512 mBounds = bounds;
513 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700514
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700515 // Use the layer's own shadow radius if set. Otherwise get the radius from
516 // parent.
517 if (s.shadowRadius > 0.f) {
518 mEffectiveShadowRadius = s.shadowRadius;
519 } else {
520 mEffectiveShadowRadius = parentShadowRadius;
521 }
522
523 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
524 // don't pass it to its children.
525 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
526
Vishnu Nair4351ad52019-02-11 14:13:02 -0800527 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700528 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800529 }
Vishnu Nairba354102022-08-01 00:14:18 +0000530
531 if (mPotentialCursor) {
532 prepareCursorCompositionState();
533 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800534}
535
Vishnu Nair60356342018-11-13 13:00:45 -0800536Rect Layer::getCroppedBufferSize(const State& s) const {
537 Rect size = getBufferSize(s);
538 Rect crop = getCrop(s);
539 if (!crop.isEmpty() && size.isValid()) {
540 size.intersect(crop, &size);
541 } else if (!crop.isEmpty()) {
542 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700543 }
Vishnu Nair60356342018-11-13 13:00:45 -0800544 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800545}
546
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700547void Layer::setupRoundedCornersCropCoordinates(Rect win,
548 const FloatRect& roundedCornersCrop) const {
549 // Translate win by the rounded corners rect coordinates, to have all values in
550 // layer coordinate space.
551 win.left -= roundedCornersCrop.left;
552 win.right -= roundedCornersCrop.left;
553 win.top -= roundedCornersCrop.top;
554 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700555}
556
Lloyd Piquede196652020-01-22 17:29:58 -0800557void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800558 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800559 const auto alpha = static_cast<float>(getAlpha());
560 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700561 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800562
563 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
564 if (!opaque || alpha != 1.0f) {
565 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
566 : Hwc2::IComposerClient::BlendMode::COVERAGE;
567 }
568
Alec Mourif4af03e2023-02-11 00:25:24 +0000569 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000570 auto* snapshot = editLayerSnapshot();
571 snapshot->outputFilter = getOutputFilter();
572 snapshot->isVisible = isVisible();
573 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
574 snapshot->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800575
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000576 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800577 contentDirty = false;
578
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000579 snapshot->geomLayerBounds = mBounds;
580 snapshot->geomLayerTransform = getTransform();
581 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
582 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000583 snapshot->localTransform = getActiveTransform(drawingState);
584 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000585 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
586 snapshot->alpha = alpha;
587 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
588 snapshot->blurRegions = drawingState.blurRegions;
589 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800590}
591
Lloyd Piquede196652020-01-22 17:29:58 -0800592void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800593 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000594 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700595
Alec Mourif4af03e2023-02-11 00:25:24 +0000596 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000597 snapshot->geomBufferSize = getBufferSize(drawingState);
598 snapshot->geomContentCrop = getBufferCrop();
599 snapshot->geomCrop = getCrop(drawingState);
600 snapshot->geomBufferTransform = getBufferTransform();
601 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
602 snapshot->geomUsesSourceCrop = usesSourceCrop();
603 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800604
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000605 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800606 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
607 for (const auto& [key, mandatory] : supportedMetadata) {
608 const auto& genericLayerMetadataCompatibilityMap =
609 mFlinger->getGenericLayerMetadataKeyMap();
610 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
611 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
612 continue;
613 }
614 const uint32_t id = compatIter->second;
615
616 auto it = drawingState.metadata.mMap.find(id);
617 if (it == std::end(drawingState.metadata.mMap)) {
618 continue;
619 }
620
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000621 snapshot->metadata.emplace(key,
622 compositionengine::GenericLayerMetadataEntry{mandatory,
623 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800624 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800625}
David Sodmanba340492018-08-05 21:51:33 -0700626
Lloyd Piquede196652020-01-22 17:29:58 -0800627void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800628 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000629 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000630 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800631
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000632 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800633
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000634 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
635 snapshot->dataspace = getDataSpace();
636 snapshot->colorTransform = getColorTransform();
637 snapshot->colorTransformIsIdentity = !hasColorTransform();
638 snapshot->surfaceDamage = surfaceDamageRegion;
639 snapshot->hasProtectedContent = isProtected();
640 snapshot->dimmingEnabled = isDimmingEnabled();
John Reck68796592023-01-25 13:47:12 -0500641 snapshot->currentSdrHdrRatio = getCurrentSdrHdrRatio();
642 snapshot->desiredSdrHdrRatio = getDesiredSdrHdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000643 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800644
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700645 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700646
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000647 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800648
649 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400650 // Rounded corners no longer force client composition, since we may use a
651 // hole punch so that the layer will appear to have rounded corners.
652 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000653 snapshot->stretchEffect.hasEffect()) {
654 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800655 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700656 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000657 snapshot->blurRegions = drawingState.blurRegions;
658 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400659
660 // Layer framerate is used in caching decisions.
661 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
662 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000663 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000664
665 if (hasBufferOrSidebandStream()) {
666 preparePerFrameBufferCompositionState();
667 } else {
668 preparePerFrameEffectsCompositionState();
669 }
670}
671
672void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000673 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000674 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000675 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000676 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
677 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000678 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
679 return;
680 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000681 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000682 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
683 } else {
684 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000685 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
686 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000687 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
688 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
689 }
690
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000691 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000692 snapshot->acquireFence = mBufferInfo.mFence;
693 snapshot->frameNumber = mBufferInfo.mFrameNumber;
694 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000695}
696
697void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000698 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000699 auto* snapshot = editLayerSnapshot();
700 snapshot->color = getColor();
701 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000702 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800703}
704
Lloyd Piquede196652020-01-22 17:29:58 -0800705void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800706 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000707 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000708 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800709
710 // Apply the layer's transform, followed by the display's global transform
711 // Here we're guaranteed that the layer's transform preserves rects
712 Rect win = getCroppedBufferSize(drawingState);
713 // Subtract the transparent region and snap to the bounds
714 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
715 Rect frame(getTransform().transform(bounds));
716
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000717 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800718}
719
Lloyd Piquea83776c2019-01-29 18:42:32 -0800720const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700721 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800722}
723
Mathias Agopian13127d82013-03-05 17:47:11 -0800724// ---------------------------------------------------------------------------
725// drawing...
726// ---------------------------------------------------------------------------
727
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500728aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
729 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700730 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800731 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500732 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800733 }
734 if (outputLayer->getState().hwc) {
735 return (*outputLayer->getState().hwc).hwcCompositionType;
736 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500737 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800738 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800739}
740
Mathias Agopian13127d82013-03-05 17:47:11 -0800741// ----------------------------------------------------------------------------
742// local state
743// ----------------------------------------------------------------------------
744
David Sodman41fdfc92017-11-06 16:09:56 -0800745bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800746 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700747 if (s.flags & layer_state_t::eLayerSecure) {
748 return true;
749 }
750
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000751 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700752 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700753}
754
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100755void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
756 std::vector<JankData>& jankData) {
757 if (mPendingJankClassifications.empty() ||
758 !mPendingJankClassifications.front()->getJankType()) {
759 return;
760 }
761
762 bool includeJankData = false;
763 for (const auto& handle : handles) {
764 for (const auto& cb : handle->callbackIds) {
765 if (cb.includeJankData) {
766 includeJankData = true;
767 break;
768 }
769 }
770
771 if (includeJankData) {
772 jankData.reserve(mPendingJankClassifications.size());
773 break;
774 }
775 }
776
777 while (!mPendingJankClassifications.empty() &&
778 mPendingJankClassifications.front()->getJankType()) {
779 if (includeJankData) {
780 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
781 mPendingJankClassifications.front();
782 jankData.emplace_back(
783 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
784 }
785 mPendingJankClassifications.pop_front();
786 }
787}
788
Mathias Agopian13127d82013-03-05 17:47:11 -0800789// ----------------------------------------------------------------------------
790// transaction
791// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800792
Vishnu Naira156f482023-02-22 00:23:38 +0000793uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700794 ATRACE_CALL();
795
Robert Carr0758e5d2021-03-11 22:15:04 -0800796 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700797 mDrawingStateModified = mDrawingState.modified;
798 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700799
Alec Mourib416efd2018-09-06 21:01:59 +0000800 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700801
Robert Carr6a160312021-05-17 12:08:20 -0700802 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800803 // invalidate and recompute the visible regions if needed
804 flags |= Layer::eVisibleRegion;
805 }
806
Robert Carr6a160312021-05-17 12:08:20 -0700807 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800808 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000809 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800810 flags |= eVisibleRegion;
811 this->contentDirty = true;
812
813 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700814 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800815 }
816
Arthur Hung9ed43392022-05-27 06:31:57 +0000817 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
818 mFlinger->mUpdateInputInfo = true;
819 }
820
Vishnu Naira156f482023-02-22 00:23:38 +0000821 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800822
Mathias Agopian13127d82013-03-05 17:47:11 -0800823 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800824}
825
Vishnu Naira156f482023-02-22 00:23:38 +0000826void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000827 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
828 // bufferSurfaceFrameTX will be presented in latchBuffer.
829 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
830 if (surfaceFrame->getPresentState() != PresentState::Presented) {
831 // With applyPendingStates, we could end up having presented surfaceframes from previous
832 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800833 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000834 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
835 }
836 }
Robert Carr6a160312021-05-17 12:08:20 -0700837 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700838}
839
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700840uint32_t Layer::clearTransactionFlags(uint32_t mask) {
841 const auto flags = mTransactionFlags & mask;
842 mTransactionFlags &= ~mask;
843 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800844}
845
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700846void Layer::setTransactionFlags(uint32_t mask) {
847 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800848}
849
Robert Carr1f0a16a2016-10-24 16:27:39 -0700850bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
851 ssize_t idx = mCurrentChildren.indexOf(childLayer);
852 if (idx < 0) {
853 return false;
854 }
855 if (childLayer->setLayer(z)) {
856 mCurrentChildren.removeAt(idx);
857 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800858 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700859 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800860 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700861}
862
Robert Carr503c7042017-09-27 15:06:08 -0700863bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
864 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
865 ssize_t idx = mCurrentChildren.indexOf(childLayer);
866 if (idx < 0) {
867 return false;
868 }
869 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
870 mCurrentChildren.removeAt(idx);
871 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800872 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700873 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800874 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700875}
876
Robert Carrae060832016-11-28 10:51:00 -0800877bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700878 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
879 mDrawingState.sequence++;
880 mDrawingState.z = z;
881 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700882
Robert Carra70e91c2021-06-11 13:59:52 -0700883 mFlinger->mSomeChildrenChanged = true;
884
Robert Carrdb66e622017-04-10 16:55:57 -0700885 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700886 if (mDrawingState.zOrderRelativeOf != nullptr) {
887 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700888 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700889 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700890 }
chaviw606e5cf2019-03-01 10:12:10 -0800891 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700892 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800893 setTransactionFlags(eTransactionNeeded);
894 return true;
895}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700896
Robert Carrdb66e622017-04-10 16:55:57 -0700897void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700898 mDrawingState.zOrderRelatives.remove(relative);
899 mDrawingState.sequence++;
900 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700901 setTransactionFlags(eTransactionNeeded);
902}
903
904void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700905 mDrawingState.zOrderRelatives.add(relative);
906 mDrawingState.modified = true;
907 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700908 setTransactionFlags(eTransactionNeeded);
909}
910
chaviw606e5cf2019-03-01 10:12:10 -0800911void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700912 mDrawingState.zOrderRelativeOf = relativeOf;
913 mDrawingState.sequence++;
914 mDrawingState.modified = true;
915 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700916
chaviw606e5cf2019-03-01 10:12:10 -0800917 setTransactionFlags(eTransactionNeeded);
918}
919
Robert Carr503d2bd2017-12-04 15:49:47 -0800920bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000921 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700922 if (relative == nullptr) {
923 return false;
924 }
925
Robert Carr6a160312021-05-17 12:08:20 -0700926 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
927 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800928 return false;
929 }
930
Robert Carr88b85e12022-03-21 15:47:35 -0700931 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
932 (relative->mDrawingState.zOrderRelativeOf == this)) {
933 ALOGE("Detected relative layer loop between %s and %s",
934 mName.c_str(), relative->mName.c_str());
935 ALOGE("Ignoring new call to set relative layer");
936 return false;
937 }
938
Robert Carra70e91c2021-06-11 13:59:52 -0700939 mFlinger->mSomeChildrenChanged = true;
940
Robert Carr6a160312021-05-17 12:08:20 -0700941 mDrawingState.sequence++;
942 mDrawingState.modified = true;
943 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700944
Robert Carr6a160312021-05-17 12:08:20 -0700945 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700946 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700947 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700948 }
chaviw606e5cf2019-03-01 10:12:10 -0800949 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700950 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700951
952 setTransactionFlags(eTransactionNeeded);
953
954 return true;
955}
956
Winson Chunga30f7c92021-06-29 15:42:56 -0700957bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
958 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
959 mDrawingState.isTrustedOverlay = isTrustedOverlay;
960 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000961 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700962 setTransactionFlags(eTransactionNeeded);
963 return true;
964}
965
966bool Layer::isTrustedOverlay() const {
967 if (getDrawingState().isTrustedOverlay) {
968 return true;
969 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000970 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700971 return (p != nullptr) && p->isTrustedOverlay();
972}
973
Dan Stoza9e56aa02015-11-02 13:00:03 -0800974bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700975 if (mDrawingState.color.a == alpha) return false;
976 mDrawingState.sequence++;
977 mDrawingState.color.a = alpha;
978 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800979 setTransactionFlags(eTransactionNeeded);
980 return true;
981}
chaviw13fdc492017-06-27 12:40:18 -0700982
Valerie Haudd0b7572019-01-29 14:59:27 -0800983bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700984 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700985 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800986 }
Robert Carr6a160312021-05-17 12:08:20 -0700987 mDrawingState.sequence++;
988 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800989 setTransactionFlags(eTransactionNeeded);
990
Robert Carr6a160312021-05-17 12:08:20 -0700991 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -0800992 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -0800993 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700994 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -0700995 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800996 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700997 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -0700998
Valerie Haudd0b7572019-01-29 14:59:27 -0800999 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001000 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001001 mFlinger->mLayersAdded = true;
1002 // set up SF to handle added color layer
1003 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -07001004 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001005 }
1006 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001007 } else if (mDrawingState.bgColorLayer && alpha == 0) {
1008 mDrawingState.bgColorLayer->reparent(nullptr);
1009 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001010 return true;
1011 }
1012
Robert Carr6a160312021-05-17 12:08:20 -07001013 mDrawingState.bgColorLayer->setColor(color);
1014 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1015 mDrawingState.bgColorLayer->setAlpha(alpha);
1016 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001017
chaviw13fdc492017-06-27 12:40:18 -07001018 return true;
1019}
1020
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001021bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001022 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001023
Robert Carr6a160312021-05-17 12:08:20 -07001024 mDrawingState.sequence++;
1025 mDrawingState.cornerRadius = cornerRadius;
1026 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001027 setTransactionFlags(eTransactionNeeded);
1028 return true;
1029}
1030
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001031bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001032 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001033 // If we start or stop drawing blur then the layer's visibility state may change so increment
1034 // the magic sequence number.
1035 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1036 mDrawingState.sequence++;
1037 }
Robert Carr6a160312021-05-17 12:08:20 -07001038 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1039 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001040 setTransactionFlags(eTransactionNeeded);
1041 return true;
1042}
Marissa Wall61c58622018-07-18 10:12:20 -07001043
Mathias Agopian13127d82013-03-05 17:47:11 -08001044bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001045 mDrawingState.sequence++;
1046 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001047 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001048 setTransactionFlags(eTransactionNeeded);
1049 return true;
1050}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001051
Lucas Dupinc3800b82020-10-02 16:24:48 -07001052bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001053 // If we start or stop drawing blur then the layer's visibility state may change so increment
1054 // the magic sequence number.
1055 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1056 mDrawingState.sequence++;
1057 }
Robert Carr6a160312021-05-17 12:08:20 -07001058 mDrawingState.blurRegions = blurRegions;
1059 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001060 setTransactionFlags(eTransactionNeeded);
1061 return true;
1062}
1063
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001064bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001065 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1066 if (mDrawingState.flags == newFlags) return false;
1067 mDrawingState.sequence++;
1068 mDrawingState.flags = newFlags;
1069 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001070 setTransactionFlags(eTransactionNeeded);
1071 return true;
1072}
Robert Carr99e27f02016-06-16 15:18:02 -07001073
chaviw25714502021-02-11 10:01:08 -08001074bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001075 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001076 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001077 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001078
Robert Carr6a160312021-05-17 12:08:20 -07001079 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001080 setTransactionFlags(eTransactionNeeded);
1081 return true;
1082}
Robert Carr8d5227b2017-03-16 15:41:03 -07001083
Evan Roskyef876c92019-01-25 17:46:06 -08001084bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001085 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1086 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001087 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001088 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001089}
1090
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001091bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001092 if (mDrawingState.layerStack == layerStack) return false;
1093 mDrawingState.sequence++;
1094 mDrawingState.layerStack = layerStack;
1095 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001096 setTransactionFlags(eTransactionNeeded);
1097 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001098}
1099
Peiyong Linc502cb72019-03-01 15:00:23 -08001100bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001101 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001102 return false;
1103 }
Robert Carr6a160312021-05-17 12:08:20 -07001104 mDrawingState.sequence++;
1105 mDrawingState.colorSpaceAgnostic = agnostic;
1106 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001107 setTransactionFlags(eTransactionNeeded);
1108 return true;
1109}
1110
Sally Qi81d95e62022-03-21 19:41:33 -07001111bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1112 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1113
1114 mDrawingState.sequence++;
1115 mDrawingState.dimmingEnabled = dimmingEnabled;
1116 mDrawingState.modified = true;
1117 setTransactionFlags(eTransactionNeeded);
1118 return true;
1119}
1120
Ana Krulecc84d09b2019-11-02 23:10:29 +01001121bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001122 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1123 mDrawingState.frameRateSelectionPriority = priority;
1124 mDrawingState.sequence++;
1125 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001126 setTransactionFlags(eTransactionNeeded);
1127 return true;
1128}
1129
1130int32_t Layer::getFrameRateSelectionPriority() const {
1131 // Check if layer has priority set.
1132 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1133 return mDrawingState.frameRateSelectionPriority;
1134 }
1135 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001136 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001137 if (parent != nullptr) {
1138 return parent->getFrameRateSelectionPriority();
1139 }
1140
1141 return Layer::PRIORITY_UNSET;
1142}
1143
Andy Labrada096227e2022-06-15 16:58:11 +00001144bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1145 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1146 mDrawingState.defaultFrameRateCompatibility = compatibility;
1147 mDrawingState.modified = true;
1148 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1149 setTransactionFlags(eTransactionNeeded);
1150 return true;
1151}
1152
1153scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1154 return mDrawingState.defaultFrameRateCompatibility;
1155}
1156
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001157bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1158 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1159};
1160
Vishnu Nair73908d12022-10-24 21:46:42 -07001161ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1162 bool useDrawing = state == LayerVector::StateSet::Drawing;
1163 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1164 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001165 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001166 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001167 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001168}
1169
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001170bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001171 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001172 return false;
1173 }
1174
Robert Carr6a160312021-05-17 12:08:20 -07001175 mDrawingState.sequence++;
1176 mDrawingState.shadowRadius = shadowRadius;
1177 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001178 setTransactionFlags(eTransactionNeeded);
1179 return true;
1180}
1181
Vishnu Nair6213bd92020-05-08 17:42:25 -07001182bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001183 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001184 return false;
1185 }
1186
Robert Carr6a160312021-05-17 12:08:20 -07001187 mDrawingState.sequence++;
1188 mDrawingState.fixedTransformHint = fixedTransformHint;
1189 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001190 setTransactionFlags(eTransactionNeeded);
1191 return true;
1192}
1193
John Reckcdb4ed72021-02-04 13:39:33 -05001194bool Layer::setStretchEffect(const StretchEffect& effect) {
1195 StretchEffect temp = effect;
1196 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001197 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001198 return false;
1199 }
Robert Carr6a160312021-05-17 12:08:20 -07001200 mDrawingState.sequence++;
1201 mDrawingState.stretchEffect = temp;
1202 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001203 setTransactionFlags(eTransactionNeeded);
1204 return true;
1205}
1206
John Reckc00c6692021-02-16 11:37:33 -05001207StretchEffect Layer::getStretchEffect() const {
1208 if (mDrawingState.stretchEffect.hasEffect()) {
1209 return mDrawingState.stretchEffect;
1210 }
1211
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001212 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001213 if (parent != nullptr) {
1214 auto effect = parent->getStretchEffect();
1215 if (effect.hasEffect()) {
1216 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1217 return effect;
1218 }
1219 }
1220 return StretchEffect{};
1221}
1222
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001223bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1224 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001225 return false;
1226 }
1227 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001228 mBorderWidth = width;
1229 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001230 return true;
1231}
1232
1233bool Layer::isBorderEnabled() {
1234 return mBorderEnabled;
1235}
1236
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001237float Layer::getBorderWidth() {
1238 return mBorderWidth;
1239}
1240
1241const half4& Layer::getBorderColor() {
1242 return mBorderColor;
1243}
1244
Ady Abrahama850c182021-08-04 13:04:37 -07001245bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1246 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1247 const auto frameRate = [&] {
1248 if (mDrawingState.frameRate.rate.isValid() ||
1249 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1250 return mDrawingState.frameRate;
1251 }
1252
1253 return parentFrameRate;
1254 }();
1255
1256 *transactionNeeded |= setFrameRateForLayerTree(frameRate);
1257
1258 // The frame rate is propagated to the children
1259 bool childrenHaveFrameRate = false;
1260 for (const sp<Layer>& child : mCurrentChildren) {
1261 childrenHaveFrameRate |=
1262 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1263 }
1264
1265 // If we don't have a valid frame rate, but the children do, we set this
1266 // layer as NoVote to allow the children to control the refresh rate
1267 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1268 childrenHaveFrameRate) {
1269 *transactionNeeded |=
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001270 setFrameRateForLayerTree(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001271 }
1272
1273 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1274 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001275 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001276 const auto layerVotedWithDefaultCompatibility =
1277 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1278 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1279 const auto layerVotedWithExactCompatibility =
1280 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1281 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1282 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1283}
1284
Ady Abraham60e42ea2020-03-09 19:17:31 -07001285void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001286 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001287 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001288 while (auto parent = layer->getParent()) {
1289 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001290 }
Ady Abrahama850c182021-08-04 13:04:37 -07001291 return layer;
1292 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001293
Ady Abraham60e42ea2020-03-09 19:17:31 -07001294 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001295 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001296
Ady Abrahama850c182021-08-04 13:04:37 -07001297 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001298 if (transactionNeeded) {
1299 mFlinger->setTransactionFlags(eTraversalNeeded);
1300 }
1301}
1302
Ady Abraham71c437d2020-01-31 15:56:57 -08001303bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001304 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001305 return false;
1306 }
1307
Robert Carr6a160312021-05-17 12:08:20 -07001308 mDrawingState.sequence++;
1309 mDrawingState.frameRate = frameRate;
1310 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001311
1312 updateTreeHasFrameRateVote();
1313
Steven Thomas3172e202020-01-06 19:25:30 -08001314 setTransactionFlags(eTransactionNeeded);
1315 return true;
1316}
1317
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001318void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1319 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001320 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001321
1322 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1323 // there are two transactions with the same token, the first one without a buffer and the
1324 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1325 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001326 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1327 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001328 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001329 mDrawingState.bufferSurfaceFrameTX = it->second;
1330 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1331 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1332 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001333 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001334 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001335 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1336 }
1337}
1338
1339void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1340 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001341 mDrawingState.frameTimelineInfo = info;
1342 mDrawingState.postTime = postTime;
1343 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001344 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001345
Robert Carr6a160312021-05-17 12:08:20 -07001346 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001347 bufferSurfaceFrameTX != nullptr) {
1348 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1349 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1350 // being used for BufferSurfaceFrame, don't create a new one.
1351 return;
1352 }
1353 }
1354 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1355 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1356 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001357 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1358 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001359 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001360 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001361 } else {
1362 if (it->second->getPresentState() == PresentState::Presented) {
1363 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1364 // have been from previous vsync.
1365 it->second = createSurfaceFrameForTransaction(info, postTime);
1366 }
1367 }
1368}
1369
1370void Layer::addSurfaceFrameDroppedForBuffer(
1371 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001372 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001373 surfaceFrame->setPresentState(PresentState::Dropped);
1374 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1375}
1376
1377void Layer::addSurfaceFramePresentedForBuffer(
1378 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1379 nsecs_t currentLatchTime) {
1380 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1381 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1382 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001383 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001384}
1385
1386std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1387 const FrameTimelineInfo& info, nsecs_t postTime) {
1388 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001389 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1390 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001391 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001392 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001393 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001394 // For Transactions, the post time is considered to be both queue and acquire fence time.
1395 surfaceFrame->setActualQueueTime(postTime);
1396 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001397 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1398 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001399 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001400 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001401 onSurfaceFrameCreated(surfaceFrame);
1402 return surfaceFrame;
1403}
1404
1405std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1406 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1407 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001408 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001409 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001410 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001411 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001412 // For buffers, acquire fence time will set during latch.
1413 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001414 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1415 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001416 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001417 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001418 onSurfaceFrameCreated(surfaceFrame);
1419 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001420}
1421
Ady Abrahama850c182021-08-04 13:04:37 -07001422bool Layer::setFrameRateForLayerTree(FrameRate frameRate) {
1423 if (mDrawingState.frameRateForLayerTree == frameRate) {
1424 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001425 }
1426
Ady Abrahama850c182021-08-04 13:04:37 -07001427 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001428
Ady Abrahama850c182021-08-04 13:04:37 -07001429 // TODO(b/195668952): we probably don't need to dirty visible regions here
1430 // or even store frameRateForLayerTree in mDrawingState
1431 mDrawingState.sequence++;
1432 mDrawingState.modified = true;
1433 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001434
Dominik Laskowski068173d2021-08-11 17:22:59 -07001435 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
1436 mFlinger->mScheduler->recordLayerHistory(this, systemTime(), LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001437
1438 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001439}
1440
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001441Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1442 return getDrawingState().frameRateForLayerTree;
1443}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001444
Robert Carr1f0a16a2016-10-24 16:27:39 -07001445bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001446 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001447 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001448 if (parent != nullptr && parent->isHiddenByPolicy()) {
1449 return true;
1450 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001451 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1452 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1453 if (zOrderRelativeOf != nullptr) {
1454 if (zOrderRelativeOf->isHiddenByPolicy()) {
1455 return true;
1456 }
1457 }
1458 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001459 if (CC_UNLIKELY(!isTransformValid())) {
1460 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1461 return true;
1462 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001463 return s.flags & layer_state_t::eLayerHidden;
1464}
1465
David Sodman41fdfc92017-11-06 16:09:56 -08001466uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001467 // TODO: should we do something special if mSecure is set?
1468 if (mProtectedByApp) {
1469 // need a hardware-protected path to external video sink
1470 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001471 }
Riley Andrews03414a12014-07-01 14:22:59 -07001472 if (mPotentialCursor) {
1473 usage |= GraphicBuffer::USAGE_CURSOR;
1474 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001475 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001476 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001477}
1478
Vishnu Nair71fcf912022-10-18 09:14:20 -07001479void Layer::skipReportingTransformHint() {
1480 mSkipReportingTransformHint = true;
1481}
1482
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001483void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1484 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1485 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001486 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001487
Vishnu Nair6213bd92020-05-08 17:42:25 -07001488 setTransformHint(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001489}
1490
Mathias Agopian13127d82013-03-05 17:47:11 -08001491// ----------------------------------------------------------------------------
1492// debugging
1493// ----------------------------------------------------------------------------
1494
Marissa Wall61c58622018-07-18 10:12:20 -07001495// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001496gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001497 using namespace std::string_literals;
1498
Huihong Luo05539a12022-02-23 10:29:40 -08001499 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001500 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001501 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001502 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001503 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001504 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001505
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001506 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001507 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001508 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001509 info.mX = ds.transform.tx();
1510 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001511 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001512 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001513 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001514 info.mFlags = ds.flags;
1515 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001516 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001517 info.mMatrix[0][0] = ds.transform[0][0];
1518 info.mMatrix[0][1] = ds.transform[0][1];
1519 info.mMatrix[1][0] = ds.transform[1][0];
1520 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001521 {
chaviwd62d3062019-09-04 14:48:02 -07001522 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001523 if (buffer != 0) {
1524 info.mActiveBufferWidth = buffer->getWidth();
1525 info.mActiveBufferHeight = buffer->getHeight();
1526 info.mActiveBufferStride = buffer->getStride();
1527 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001528 } else {
1529 info.mActiveBufferWidth = 0;
1530 info.mActiveBufferHeight = 0;
1531 info.mActiveBufferStride = 0;
1532 info.mActiveBufferFormat = 0;
1533 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001534 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001535 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001536 info.mIsOpaque = isOpaque(ds);
1537 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001538 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001539 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001540}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001541
Yiwei Zhang5434a782018-12-05 18:06:32 -08001542void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001543 result.append(kDumpTableRowLength, '-');
1544 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001545 result.append(" Layer name\n");
1546 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001547 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001548 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001549 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001550 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001551 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001552 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1553 result.append(kDumpTableRowLength, '-');
1554 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001555}
1556
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001557void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1558 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001559 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001560 return;
1561 }
1562
Yiwei Zhang5434a782018-12-05 18:06:32 -08001563 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001564 if (mName.length() > 77) {
1565 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001566 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001567 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001568 shortened.append(mName, mName.length() - 36);
1569 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001570 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001571 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001572 }
1573
Yiwei Zhang5434a782018-12-05 18:06:32 -08001574 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001575
Alec Mourib416efd2018-09-06 21:01:59 +00001576 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001577 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001578
Chia-I Wu1e043612018-03-01 09:45:09 -08001579 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001580 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001581 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001582 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001583 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001584 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001585 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001586 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1587 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001588 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001589 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001590 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001591 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001592 const auto frameRate = getFrameRateForLayerTree();
1593 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1594 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001595 ftl::enum_string(frameRate.type).c_str(),
1596 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001597 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001598 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001599 }
Dan Stozae22aec72016-08-01 13:20:59 -07001600
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001601 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1602 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1603
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001604 result.append(kDumpTableRowLength, '-');
1605 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001606}
Dan Stozae22aec72016-08-01 13:20:59 -07001607
Yiwei Zhang5434a782018-12-05 18:06:32 -08001608void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001609 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001610}
1611
Svetoslavd85084b2014-03-20 10:28:31 -07001612void Layer::clearFrameStats() {
1613 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001614}
1615
Jamie Gennis6547ff42013-07-16 20:12:42 -07001616void Layer::logFrameStats() {
1617 mFrameTracker.logAndResetStats(mName);
1618}
1619
Svetoslavd85084b2014-03-20 10:28:31 -07001620void Layer::getFrameStats(FrameStats* outStats) const {
1621 mFrameTracker.getStats(outStats);
1622}
1623
Vishnu Nair76554eb2022-12-09 03:38:36 +00001624void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1625 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
1626 StringAppendF(&result, "Layer %s%s pid:%d uid:%d\n", getName().c_str(), hasBuffer.c_str(),
Vishnu Naircb8be502022-10-12 19:03:23 +00001627 mOwnerPid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001628}
1629
Brian Anderson5ea5e592016-12-01 16:54:33 -08001630void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001631 const int32_t layerId = getSequence();
1632 mFlinger->mTimeStats->onDestroy(layerId);
1633 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001634}
1635
Chia-I Wu98f1c102017-05-30 14:54:08 -07001636size_t Layer::getChildrenCount() const {
1637 size_t count = 0;
1638 for (const sp<Layer>& child : mCurrentChildren) {
1639 count += 1 + child->getChildrenCount();
1640 }
1641 return count;
1642}
1643
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001644void Layer::setGameModeForTree(GameMode gameMode) {
1645 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001646 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1647 gameMode =
1648 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001649 }
1650 setGameMode(gameMode);
1651 for (const sp<Layer>& child : mCurrentChildren) {
1652 child->setGameModeForTree(gameMode);
1653 }
1654}
1655
Robert Carr1f0a16a2016-10-24 16:27:39 -07001656void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001657 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001658 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001659
Robert Carr1f0a16a2016-10-24 16:27:39 -07001660 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001661 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001662 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001663 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001664}
1665
1666ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001667 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001668 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001669
Robert Carr1323c952019-01-28 18:13:27 -08001670 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001671 const auto removeResult = mCurrentChildren.remove(layer);
1672
1673 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001674 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001675 layer->updateTreeHasFrameRateVote();
1676
1677 return removeResult;
1678}
1679
Robert Carr15eae092018-03-23 13:43:53 -07001680void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001681 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001682 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001683 const float parentShadowRadius =
1684 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001685 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001686 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001687 }
1688}
1689
chaviwf1961f72017-09-18 16:41:07 -07001690bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001691 sp<Layer> newParent;
1692 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001693 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001694 if (newParent == nullptr) {
1695 ALOGE("Unable to promote Layer handle");
1696 return false;
1697 }
1698 if (newParent == this) {
1699 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1700 return false;
1701 }
1702 }
1703
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001704 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001705 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001706 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001707 }
1708
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001709 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001710 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001711 if (!newParent->isRemovedFromCurrentState()) {
1712 addToCurrentState();
1713 } else {
1714 onRemovedFromCurrentState();
1715 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001716 } else {
1717 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001718 }
1719
chaviw06178942017-07-27 10:25:59 -07001720 return true;
1721}
1722
Peiyong Lind3788632018-09-18 16:01:31 -07001723bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001724 static const mat4 identityMatrix = mat4();
1725
Robert Carr6a160312021-05-17 12:08:20 -07001726 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001727 return false;
1728 }
Robert Carr6a160312021-05-17 12:08:20 -07001729 ++mDrawingState.sequence;
1730 mDrawingState.colorTransform = matrix;
1731 mDrawingState.hasColorTransform = matrix != identityMatrix;
1732 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001733 setTransactionFlags(eTransactionNeeded);
1734 return true;
1735}
1736
chaviwf66724d2018-11-28 16:35:21 -08001737mat4 Layer::getColorTransform() const {
1738 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001739 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001740 colorTransform = parent->getColorTransform() * colorTransform;
1741 }
1742 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001743}
1744
1745bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001746 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001747 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001748 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1749 }
1750 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001751}
1752
Chia-I Wu11481472018-05-04 10:43:19 -07001753bool Layer::isLegacyDataSpace() const {
1754 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001755 return !(getDataSpace() &
1756 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1757 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001758}
1759
Robert Carr1f0a16a2016-10-24 16:27:39 -07001760void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001761 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001762}
1763
Robert Carr6a160312021-05-17 12:08:20 -07001764int32_t Layer::getZ(LayerVector::StateSet) const {
1765 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001766}
1767
Robert Carr1c5481e2019-07-01 14:42:27 -07001768bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001769 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001770 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001771 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001772}
1773
David Sodman41fdfc92017-11-06 16:09:56 -08001774__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001775 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001776 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1777 "makeTraversalList received invalid stateSet");
1778 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1779 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001780 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001781
Robert Carr29abff82017-12-04 13:51:20 -08001782 if (state.zOrderRelatives.size() == 0) {
1783 *outSkipRelativeZUsers = true;
1784 return children;
1785 }
1786
chaviwfd462612018-05-31 16:11:27 -07001787 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001788 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001789 sp<Layer> strongRelative = weakRelative.promote();
1790 if (strongRelative != nullptr) {
1791 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001792 }
1793 }
1794
Dan Stoza412903f2017-04-27 13:42:17 -07001795 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001796 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001797 continue;
1798 }
Robert Carrdb66e622017-04-10 16:55:57 -07001799 traverse.add(child);
1800 }
1801
1802 return traverse;
1803}
1804
Robert Carr1f0a16a2016-10-24 16:27:39 -07001805/**
Robert Carrdb66e622017-04-10 16:55:57 -07001806 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001807 */
Dan Stoza412903f2017-04-27 13:42:17 -07001808void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001809 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1810 // produce a new list for traversing, including our relatives, and not including our children
1811 // who are relatives of another surface. In the case that there are no relative Z,
1812 // makeTraversalList returns our children directly to avoid significant overhead.
1813 // However in this case we need to take the responsibility for filtering children which
1814 // are relatives of another surface here.
1815 bool skipRelativeZUsers = false;
1816 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001817
Robert Carr1f0a16a2016-10-24 16:27:39 -07001818 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001819 for (; i < list.size(); i++) {
1820 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001821 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1822 continue;
1823 }
1824
chaviw301b1d82019-11-06 13:15:09 -08001825 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001826 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001827 }
Dan Stoza412903f2017-04-27 13:42:17 -07001828 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001829 }
Robert Carr29abff82017-12-04 13:51:20 -08001830
Dan Stoza412903f2017-04-27 13:42:17 -07001831 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001832 for (; i < list.size(); i++) {
1833 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001834
Robert Carr29abff82017-12-04 13:51:20 -08001835 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1836 continue;
1837 }
Dan Stoza412903f2017-04-27 13:42:17 -07001838 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001839 }
1840}
1841
1842/**
Robert Carrdb66e622017-04-10 16:55:57 -07001843 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001844 */
Dan Stoza412903f2017-04-27 13:42:17 -07001845void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1846 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001847 // See traverseInZOrder for documentation.
1848 bool skipRelativeZUsers = false;
1849 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001850
Robert Carr1f0a16a2016-10-24 16:27:39 -07001851 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001852 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001853 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001854
1855 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1856 continue;
1857 }
1858
chaviw301b1d82019-11-06 13:15:09 -08001859 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001860 break;
1861 }
Dan Stoza412903f2017-04-27 13:42:17 -07001862 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001863 }
Dan Stoza412903f2017-04-27 13:42:17 -07001864 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001865 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001866 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001867
1868 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1869 continue;
1870 }
1871
Dan Stoza412903f2017-04-27 13:42:17 -07001872 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001873 }
1874}
1875
Edgar Arriaga844fa672020-01-16 14:21:42 -08001876void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1877 visitor(this);
1878 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001879 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001880 for (const sp<Layer>& child : children) {
1881 child->traverse(state, visitor);
1882 }
1883}
1884
chaviw4b129c22018-04-09 16:19:43 -07001885LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1886 const std::vector<Layer*>& layersInTree) {
1887 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1888 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001889 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1890 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001891 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001892
chaviwfd462612018-05-31 16:11:27 -07001893 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001894 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1895 sp<Layer> strongRelative = weakRelative.promote();
1896 // Only add relative layers that are also descendents of the top most parent of the tree.
1897 // If a relative layer is not a descendent, then it should be ignored.
1898 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1899 traverse.add(strongRelative);
1900 }
1901 }
1902
1903 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001904 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001905 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1906 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1907 // the child here since it won't be added later as a relative.
1908 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1909 childState.zOrderRelativeOf.promote().get())) {
1910 continue;
1911 }
1912 traverse.add(child);
1913 }
1914
1915 return traverse;
1916}
1917
1918void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1919 LayerVector::StateSet stateSet,
1920 const LayerVector::Visitor& visitor) {
1921 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001922
1923 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001924 for (; i < list.size(); i++) {
1925 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001926 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001927 break;
1928 }
chaviw4b129c22018-04-09 16:19:43 -07001929 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001930 }
chaviw4b129c22018-04-09 16:19:43 -07001931
chaviwa76b2712017-09-20 12:02:26 -07001932 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001933 for (; i < list.size(); i++) {
1934 const auto& relative = list[i];
1935 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001936 }
1937}
1938
chaviw4b129c22018-04-09 16:19:43 -07001939std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1940 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1941 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1942
1943 std::vector<Layer*> layersInTree = {this};
1944 for (size_t i = 0; i < children.size(); i++) {
1945 const auto& child = children[i];
1946 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1947 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1948 }
1949
1950 return layersInTree;
1951}
1952
1953void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1954 const LayerVector::Visitor& visitor) {
1955 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1956 std::sort(layersInTree.begin(), layersInTree.end());
1957 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1958}
1959
Peiyong Linefefaac2018-08-17 12:27:51 -07001960ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001961 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001962}
1963
Garfield Tan2c1782c2022-02-16 15:25:05 -08001964bool Layer::isTransformValid() const {
1965 float transformDet = getTransform().det();
1966 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1967}
1968
chaviw13fdc492017-06-27 12:40:18 -07001969half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001970 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001971
chaviw13fdc492017-06-27 12:40:18 -07001972 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1973 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07001974}
Robert Carr6452f122017-03-21 10:41:29 -07001975
Vishnu Nair6213bd92020-05-08 17:42:25 -07001976ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07001977 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001978 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
1979 return fixedTransformHint;
1980 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001981 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07001982 if (!p) return fixedTransformHint;
1983 return p->getFixedTransformHint();
1984}
1985
chaviw13fdc492017-06-27 12:40:18 -07001986half4 Layer::getColor() const {
1987 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001988 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07001989}
Robert Carr6452f122017-03-21 10:41:29 -07001990
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001991int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00001992 if (getDrawingState().backgroundBlurRadius == 0) {
1993 return 0;
1994 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01001995
Vishnu Nair29810f72022-07-01 16:38:41 +00001996 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01001997 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1998 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001999}
2000
Galia Peychevae0acf382021-04-12 21:22:34 +02002001const std::vector<BlurRegion> Layer::getBlurRegions() const {
2002 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002003 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002004 for (auto& region : regionsCopy) {
2005 region.alpha = region.alpha * layerAlpha;
2006 }
2007 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002008}
2009
Vishnu Naire14c6b32022-08-06 04:20:15 +00002010RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002011 // Get parent settings
2012 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002013 const auto& parent = mDrawingParent.promote();
2014 if (parent != nullptr) {
2015 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002016 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002017 ui::Transform t = getActiveTransform(getDrawingState());
2018 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002019 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002020 parentSettings.radius.x *= t.getScaleX();
2021 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002022 }
2023 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002024
2025 // Get layer settings
2026 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002027 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002028 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002029 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002030
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002031 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002032 // If the parent and the layer have rounded corner settings, use the parent settings if the
2033 // parent crop is entirely inside the layer crop.
2034 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2035 if (parentSettings.cropRect.left > layerCropRect.left &&
2036 parentSettings.cropRect.top > layerCropRect.top &&
2037 parentSettings.cropRect.right < layerCropRect.right &&
2038 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2039 return parentSettings;
2040 } else {
2041 return layerSettings;
2042 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002043 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002044 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002045 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002046 return parentSettings;
2047 }
2048 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002049}
2050
Robert Carr88b85e12022-03-21 15:47:35 -07002051bool Layer::findInHierarchy(const sp<Layer>& l) {
2052 if (l == this) {
2053 return true;
2054 }
2055 for (auto& child : mDrawingChildren) {
2056 if (child->findInHierarchy(l)) {
2057 return true;
2058 }
2059 }
2060 return false;
2061}
2062
Robert Carr1f0a16a2016-10-24 16:27:39 -07002063void Layer::commitChildList() {
2064 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2065 const auto& child = mCurrentChildren[i];
2066 child->commitChildList();
2067 }
2068 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002069 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002070 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2071 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2072 if (zOrderRelativeOf == nullptr) return;
2073 if (findInHierarchy(zOrderRelativeOf)) {
2074 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2075 zOrderRelativeOf->mName.c_str());
2076 ALOGE("Severing rel Z loop, potentially dangerous");
2077 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002078 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002079 }
2080 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002081}
2082
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002083
chaviw3277faf2021-05-19 16:45:23 -05002084void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002085 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002086 mDrawingState.touchableRegionCrop =
2087 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002088 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002089 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002090 setTransactionFlags(eTransactionNeeded);
2091}
2092
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002093LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002094 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002095 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002096 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2097
Vishnu Nair00b90132021-11-05 14:03:40 -07002098 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002099 writeCompositionStateToProto(layerProto);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002100 }
2101
chaviw08f3cb22020-01-13 13:17:21 -08002102 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002103 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002104 }
chaviw6d89e2d2020-01-14 14:42:01 -08002105
2106 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002107}
2108
Vishnu Nairea6ff812023-02-27 17:41:39 +00002109void Layer::writeCompositionStateToProto(LayerProto* layerProto) {
2110 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2111
2112 // Only populate for the primary display.
2113 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
2114 const auto compositionType = getCompositionType(*display);
2115 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
2116 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2117 [&]() { return layerProto->mutable_visible_region(); });
2118 }
2119}
2120
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002121void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002122 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002123 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002124 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002125 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002126 [&]() { return layerInfo->mutable_active_buffer(); });
2127 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2128 layerInfo->mutable_buffer_transform());
2129 }
2130 layerInfo->set_invalidate(contentDirty);
2131 layerInfo->set_is_protected(isProtected());
2132 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2133 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002134 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002135 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002136 layerInfo->set_corner_radius(
2137 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002138 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2139 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2140 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2141 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2142 [&]() { return layerInfo->mutable_position(); });
2143 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002144 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2145 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002146
Vishnu Nair00b90132021-11-05 14:03:40 -07002147 if (hasColorTransform()) {
2148 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002149 }
2150
Vishnu Nair60db8c02020-04-02 11:55:16 -07002151 LayerProtoHelper::writeToProto(mSourceBounds,
2152 [&]() { return layerInfo->mutable_source_bounds(); });
2153 LayerProtoHelper::writeToProto(mScreenBounds,
2154 [&]() { return layerInfo->mutable_screen_bounds(); });
2155 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2156 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2157 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002158}
2159
2160void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002161 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002162 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2163 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002164 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002165
chaviw766c9c52021-02-10 17:36:47 -08002166 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002167
Vishnu Nair00b90132021-11-05 14:03:40 -07002168 layerInfo->set_id(sequence);
2169 layerInfo->set_name(getName().c_str());
2170 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002171
Vishnu Nair00b90132021-11-05 14:03:40 -07002172 for (const auto& child : children) {
2173 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002174 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002175
Vishnu Nair00b90132021-11-05 14:03:40 -07002176 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2177 sp<Layer> strongRelative = weakRelative.promote();
2178 if (strongRelative != nullptr) {
2179 layerInfo->add_relatives(strongRelative->sequence);
2180 }
2181 }
2182
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002183 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002184 [&]() { return layerInfo->mutable_transparent_region(); });
2185
2186 layerInfo->set_layer_stack(getLayerStack().id);
2187 layerInfo->set_z(state.z);
2188
2189 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2190 return layerInfo->mutable_requested_position();
2191 });
2192
Vishnu Nair00b90132021-11-05 14:03:40 -07002193 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2194
2195 layerInfo->set_is_opaque(isOpaque(state));
2196
2197 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2198 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2199 LayerProtoHelper::writeToProto(state.color,
2200 [&]() { return layerInfo->mutable_requested_color(); });
2201 layerInfo->set_flags(state.flags);
2202
2203 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2204 layerInfo->mutable_requested_transform());
2205
2206 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2207 if (parent != nullptr) {
2208 layerInfo->set_parent(parent->sequence);
2209 } else {
2210 layerInfo->set_parent(-1);
2211 }
2212
2213 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2214 if (zOrderRelativeOf != nullptr) {
2215 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2216 } else {
2217 layerInfo->set_z_order_relative_of(-1);
2218 }
2219
2220 layerInfo->set_is_relative_of(state.isRelativeOf);
2221
2222 layerInfo->set_owner_uid(mOwnerUid);
2223
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002224 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002225 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002226 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002227 info = fillInputInfo(
2228 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002229 } else {
2230 info = state.inputInfo;
2231 }
2232
2233 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002234 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002235 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002236
Vishnu Nair00b90132021-11-05 14:03:40 -07002237 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002238 auto protoMap = layerInfo->mutable_metadata();
2239 for (const auto& entry : state.metadata.mMap) {
2240 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2241 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002242 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002243
2244 LayerProtoHelper::writeToProto(state.destinationFrame,
2245 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002246}
2247
Robert Carr2e102c92018-10-23 12:11:15 -07002248bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002249 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002250}
2251
Prabir Pradhan33da9462022-06-14 14:55:57 +00002252// Applies the given transform to the region, while protecting against overflows caused by any
2253// offsets. If applying the offset in the transform to any of the Rects in the region would result
2254// in an overflow, they are not added to the output Region.
2255static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2256 const std::string& debugWindowName) {
2257 // Round the translation using the same rounding strategy used by ui::Transform.
2258 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2259 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2260
2261 ui::Transform transformWithoutOffset = t;
2262 transformWithoutOffset.set(0.f, 0.f);
2263
2264 const Region transformed = transformWithoutOffset.transform(r);
2265
2266 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2267 Region ret;
2268 for (const auto& rect : transformed) {
2269 Rect newRect;
2270 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2271 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2272 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2273 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2274 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2275 debugWindowName.c_str());
2276 continue;
2277 }
2278 ret.orSelf(newRect);
2279 }
2280 return ret;
2281}
2282
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002283void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
2284 Rect tmpBounds = getInputBounds();
2285 if (!tmpBounds.isValid()) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002286 info.touchableRegion.clear();
2287 // A layer could have invalid input bounds and still expect to receive touch input if it has
2288 // replaceTouchableRegionWithCrop. For that case, the input transform needs to be calculated
2289 // correctly to determine the coordinate space for input events. Use an empty rect so that
2290 // the layer will receive input in its own layer space.
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002291 tmpBounds = Rect::EMPTY_RECT;
chaviw7e72caf2020-12-02 16:50:43 -08002292 }
2293
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002294 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2295 // frame and transform used for the layer, which determines the bounds and the coordinate space
2296 // within which the layer will receive input.
2297 //
2298 // The coordinate space within which each of the bounds are specified is explicitly documented
2299 // in the variable name. For example "inputBoundsInLayer" is specified in layer space. A
2300 // Transform converts one coordinate space to another, which is apparent in its naming. For
2301 // example, "layerToDisplay" transforms layer space to display space.
2302 //
2303 // Coordinate space definitions:
2304 // - display: The display device's coordinate space. Correlates to pixels on the display.
2305 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2306 // - layer: The coordinate space of this layer.
2307 // - input: The coordinate space in which this layer will receive input events. This could be
2308 // different than layer space if a surfaceInset is used, which changes the origin
2309 // of the input space.
2310 const FloatRect inputBoundsInLayer = tmpBounds.toFloatRect();
chaviw7e72caf2020-12-02 16:50:43 -08002311
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002312 // Clamp surface inset to the input bounds.
2313 const auto surfaceInset = static_cast<float>(info.surfaceInset);
2314 const float xSurfaceInset =
2315 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getWidth() / 2.f));
2316 const float ySurfaceInset =
2317 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getHeight() / 2.f));
chaviw1ff3d1e2020-07-01 15:53:47 -07002318
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002319 // Apply the insets to the input bounds.
2320 const FloatRect insetBoundsInLayer(inputBoundsInLayer.left + xSurfaceInset,
2321 inputBoundsInLayer.top + ySurfaceInset,
2322 inputBoundsInLayer.right - xSurfaceInset,
2323 inputBoundsInLayer.bottom - ySurfaceInset);
Ady Abraham282f1d72019-07-24 18:05:56 -07002324
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002325 // Crop the input bounds to ensure it is within the parent's bounds.
2326 const FloatRect croppedInsetBoundsInLayer = mBounds.intersect(insetBoundsInLayer);
Ady Abraham282f1d72019-07-24 18:05:56 -07002327
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002328 const ui::Transform layerToScreen = getInputTransform();
2329 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
Vishnu Nair8033a492018-12-05 07:27:23 -08002330
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002331 const Rect roundedFrameInDisplay{layerToDisplay.transform(croppedInsetBoundsInLayer)};
2332 info.frameLeft = roundedFrameInDisplay.left;
2333 info.frameTop = roundedFrameInDisplay.top;
2334 info.frameRight = roundedFrameInDisplay.right;
2335 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002336
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002337 ui::Transform inputToLayer;
2338 inputToLayer.set(insetBoundsInLayer.left, insetBoundsInLayer.top);
2339 const ui::Transform inputToDisplay = layerToDisplay * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002340
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002341 // InputDispatcher expects a display-to-input transform.
2342 info.transform = inputToDisplay.inverse();
2343
2344 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002345 info.touchableRegion =
2346 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002347}
2348
chaviw3277faf2021-05-19 16:45:23 -05002349void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002350 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002351 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002352 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002353 }
2354 if (p != nullptr) {
2355 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2356 }
2357}
2358
Vishnu Naira066d902021-09-13 18:40:17 -07002359gui::DropInputMode Layer::getDropInputMode() const {
2360 gui::DropInputMode mode = mDrawingState.dropInputMode;
2361 if (mode == gui::DropInputMode::ALL) {
2362 return mode;
2363 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002364 sp<Layer> parent = mDrawingParent.promote();
2365 if (parent) {
2366 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002367 if (parentMode != gui::DropInputMode::NONE) {
2368 return parentMode;
2369 }
2370 }
2371 return mode;
2372}
2373
2374void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002375 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002376 return;
2377 }
2378
2379 // Check if we need to drop input unconditionally
2380 gui::DropInputMode dropInputMode = getDropInputMode();
2381 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002382 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002383 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2384 return;
2385 }
2386
2387 // Check if we need to check if the window is obscured by parent
2388 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2389 return;
2390 }
2391
2392 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002393 sp<Layer> parent = mDrawingParent.promote();
2394 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002395 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002396 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2397 static_cast<float>(getAlpha()));
2398 }
2399
2400 // Check if the parent has cropped the buffer
2401 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2402 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002403 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002404 return;
2405 }
2406
2407 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2408 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2409 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2410 // match then the layer has not been cropped by its parents.
2411 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2412 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2413
2414 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002415 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002416 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2417 getDebugName());
2418 } else {
2419 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2420 // input if the window is obscured. This check should be done in surfaceflinger but the
2421 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2422 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002423 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002424 }
2425}
2426
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002427WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002428 if (!hasInputInfo()) {
2429 mDrawingState.inputInfo.name = getName();
2430 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2431 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002432 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002433 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002434 }
2435
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002436 const ui::Transform& displayTransform =
2437 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2438
chaviw3277faf2021-05-19 16:45:23 -05002439 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002440 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002441 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002442
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002443 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002444
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002445 if (displayArgs.transform == nullptr) {
2446 // Do not let the window receive touches if it is not associated with a valid display
2447 // transform. We still allow the window to receive keys and prevent ANRs.
2448 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2449 }
2450
Robert Carr5dc426e2020-06-10 14:29:14 -07002451 // For compatibility reasons we let layers which can receive input
2452 // receive input before they have actually submitted a buffer. Because
2453 // of this we use canReceiveInput instead of isVisible to check the
2454 // policy-visibility, ignoring the buffer state. However for layers with
2455 // hasInputInfo()==false we can use the real visibility state.
2456 // We are just using these layers for occlusion detection in
2457 // InputDispatcher, and obviously if they aren't visible they can't occlude
2458 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002459 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2460 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2461
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002462 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002463 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002464 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002465
Vishnu Nair16a938f2021-09-24 07:14:54 -07002466 // If the window will be blacked out on a display because the display does not have the secure
2467 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002468 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002469 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002470 }
2471
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002472 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2473 if (info.replaceTouchableRegionWithCrop) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002474 const Rect bounds(cropLayer ? cropLayer->mScreenBounds : mScreenBounds);
2475 info.touchableRegion = Region(displayTransform.transform(bounds));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002476 } else if (cropLayer != nullptr) {
[1;3C2b9fc252021-02-04 16:16:50 -08002477 info.touchableRegion = info.touchableRegion.intersect(
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002478 displayTransform.transform(Rect{cropLayer->mScreenBounds}));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002479 }
2480
Winson Chunga30f7c92021-06-29 15:42:56 -07002481 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2482 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002483 if (isTrustedOverlay()) {
2484 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2485 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002486
chaviwaf87b3e2019-10-01 16:59:28 -07002487 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2488 // touches from going outside the cloned area.
2489 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002490 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002491 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2492 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002493 info.touchableRegion = info.touchableRegion.intersect(rect);
2494 }
2495 }
2496
Robert Carr720e5062018-07-30 17:45:14 -07002497 return info;
2498}
2499
chaviwaf87b3e2019-10-01 16:59:28 -07002500sp<Layer> Layer::getClonedRoot() {
2501 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002502 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002503 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002504 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002505 return nullptr;
2506 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002507 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002508}
2509
Robert Carredd13602020-04-13 17:24:34 -07002510bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002511 return mDrawingState.inputInfo.token != nullptr ||
2512 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002513}
2514
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002515compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002516 const DisplayDevice* display) const {
2517 if (!display) return nullptr;
Vishnu Naird47bcee2023-02-24 18:08:51 +00002518 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2519 return display->getCompositionDisplay()->getOutputLayerForLayer(
2520 getCompositionEngineLayerFE());
2521 }
2522 sp<LayerFE> layerFE;
2523 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2524 for (auto& [p, layer] : mLayerFEs) {
2525 if (p == path) {
2526 layerFE = layer;
2527 }
2528 }
2529
2530 if (!layerFE) return nullptr;
2531 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002532}
2533
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002534Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2535 const auto outputLayer = findOutputLayerForDisplay(display);
2536 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002537}
2538
chaviwb4c6e582019-08-16 14:35:07 -07002539void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002540 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002541 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002542 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2543 mPotentialCursor = clonedFrom->mPotentialCursor;
2544 mProtectedByApp = clonedFrom->mProtectedByApp;
2545 updateCloneBufferInfo();
2546}
2547
2548void Layer::updateCloneBufferInfo() {
2549 if (!isClone() || !isClonedFromAlive()) {
2550 return;
2551 }
2552
2553 sp<Layer> clonedFrom = getClonedFrom();
2554 mBufferInfo = clonedFrom->mBufferInfo;
2555 mSidebandStream = clonedFrom->mSidebandStream;
2556 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2557 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2558 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2559
2560 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2561 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2562 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2563 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2564 // the cloned drawingState again.
2565 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2566 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2567 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2568 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2569
2570 cloneDrawingState(clonedFrom.get());
2571
2572 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2573 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2574 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2575 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002576}
chaviw74b03172019-08-19 11:09:03 -07002577
2578void Layer::updateMirrorInfo() {
2579 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2580 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2581 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2582 // that case, we want to delete the reference to the clone since we want it to get
2583 // destroyed. The root, this layer, will still be around since the client can continue
2584 // to hold a reference, but no cloned layers will be displayed.
2585 mClonedChild = nullptr;
2586 return;
2587 }
2588
2589 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2590 // If the real layer exists and is in current state, add the clone as a child of the root.
2591 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2592 // copied to drawingState for the root layer. So the clonedChild is always removed from
2593 // drawingState and then needs to be added back each traversal.
2594 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2595 addChildToDrawing(mClonedChild);
2596 }
2597
2598 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002599 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002600 mClonedChild->updateClonedRelatives(clonedLayersMap);
2601}
2602
2603void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2604 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2605 // to the clone. If the real layer is no longer alive, continue traversing the children
2606 // since we may be able to pull out other children that are still alive.
2607 if (isClonedFromAlive()) {
2608 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002609 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002610 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002611 }
2612
2613 // The clone layer may have children in drawingState since they may have been created and
2614 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2615 // that already exist, since we can just re-use them.
2616 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2617 // not updated in the regular traversal. They are skipped since the root will lose the
2618 // reference to them when it copies its currentChildren to drawing.
2619 for (sp<Layer>& child : mDrawingChildren) {
2620 child->updateClonedDrawingState(clonedLayersMap);
2621 }
2622}
2623
2624void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2625 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2626 mDrawingChildren.clear();
2627
2628 if (!isClonedFromAlive()) {
2629 return;
2630 }
2631
2632 sp<Layer> clonedFrom = getClonedFrom();
2633 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2634 if (child == mirrorRoot) {
2635 // This is to avoid cyclical mirroring.
2636 continue;
2637 }
2638 sp<Layer> clonedChild = clonedLayersMap[child];
2639 if (clonedChild == nullptr) {
2640 clonedChild = child->createClone();
2641 clonedLayersMap[child] = clonedChild;
2642 }
2643 addChildToDrawing(clonedChild);
2644 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2645 }
2646}
2647
chaviwaf87b3e2019-10-01 16:59:28 -07002648void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2649 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2650 if (cropLayer != nullptr) {
2651 if (clonedLayersMap.count(cropLayer) == 0) {
2652 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2653 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002654 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002655 } else {
2656 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2657 mDrawingState.touchableRegionCrop = clonedCropLayer;
2658 }
2659 }
2660 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2661 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002662 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002663}
2664
2665void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002666 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002667 mDrawingState.zOrderRelatives.clear();
2668
2669 if (!isClonedFromAlive()) {
2670 return;
2671 }
2672
chaviwaf87b3e2019-10-01 16:59:28 -07002673 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002674 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002675 const sp<Layer>& relative = relativeWeak.promote();
2676 if (clonedLayersMap.count(relative) > 0) {
2677 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002678 mDrawingState.zOrderRelatives.add(clonedRelative);
2679 }
2680 }
2681
2682 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2683 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2684 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2685 // still traverse the children, but the layer with the missing relativeOf will not be shown
2686 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002687 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2688 if (clonedLayersMap.count(relativeOf) > 0) {
2689 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002690 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2691 }
2692
chaviwaf87b3e2019-10-01 16:59:28 -07002693 updateClonedInputInfo(clonedLayersMap);
2694
chaviw74b03172019-08-19 11:09:03 -07002695 for (sp<Layer>& child : mDrawingChildren) {
2696 child->updateClonedRelatives(clonedLayersMap);
2697 }
2698}
2699
2700void Layer::addChildToDrawing(const sp<Layer>& layer) {
2701 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002702 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002703}
2704
Steven Thomas62a4cf82020-01-31 12:04:03 -08002705Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2706 switch (compatibility) {
2707 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2708 return FrameRateCompatibility::Default;
2709 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2710 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002711 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2712 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002713 case ANATIVEWINDOW_FRAME_RATE_MIN:
2714 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002715 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2716 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002717 default:
2718 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2719 return FrameRateCompatibility::Default;
2720 }
2721}
2722
Marin Shalamanovc5986772021-03-16 16:09:49 +01002723scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2724 switch (strategy) {
2725 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2726 return Seamlessness::OnlySeamless;
2727 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2728 return Seamlessness::SeamedAndSeamless;
2729 default:
2730 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2731 return Seamlessness::Default;
2732 }
2733}
2734
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002735bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002736 const State& s(mDrawingState);
2737 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2738 return true;
2739 }
2740
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002741 sp<Layer> parent = mDrawingParent.promote();
2742 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002743}
2744
Robert Carr6a0382d2021-07-01 15:57:17 -07002745void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2746 mClonedChild = clonedChild;
2747 mHadClonedChild = true;
2748 mFlinger->mNumClones++;
2749}
2750
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002751bool Layer::setDropInputMode(gui::DropInputMode mode) {
2752 if (mDrawingState.dropInputMode == mode) {
2753 return false;
2754 }
2755 mDrawingState.dropInputMode = mode;
2756 return true;
2757}
2758
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002759void Layer::cloneDrawingState(const Layer* from) {
2760 mDrawingState = from->mDrawingState;
2761 // Skip callback info since they are not applicable for cloned layers.
2762 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002763 // TODO (b/238781169) currently broken for mirror layers because we do not
2764 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002765 mDrawingState.callbackHandles = {};
2766}
2767
Patrick Williamsbb25f802022-08-30 23:02:34 +00002768void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2769 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002770 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002771 if (!listener) {
2772 return;
2773 }
2774 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002775 uint32_t currentMaxAcquiredBufferCount =
2776 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002777 listener->onReleaseBuffer({buffer->getId(), framenumber},
2778 releaseFence ? releaseFence : Fence::NO_FENCE,
2779 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002780}
2781
2782void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2783 // If we are displayed on multiple displays in a single composition cycle then we would
2784 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2785 // For example we can only use it if all the displays are client comp, and we need
2786 // to merge all the client comp fences. We could do this, but for now we just
2787 // disable the optimization when a layer is composed on multiple displays.
2788 if (mClearClientCompositionFenceOnLayerDisplayed) {
2789 mLastClientCompositionFence = nullptr;
2790 } else {
2791 mClearClientCompositionFenceOnLayerDisplayed = true;
2792 }
2793
2794 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2795 // buffer that was presented on this layer. The first transaction that came in this frame that
2796 // replaced the previous buffer on this layer needs this release fence, because the fence will
2797 // let the client know when that previous buffer is removed from the screen.
2798 //
2799 // Every other transaction on this layer does not need a release fence because no other
2800 // Transactions that were set on this layer this frame are going to have their preceding buffer
2801 // removed from the display this frame.
2802 //
2803 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2804 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2805 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2806 // the previous buffer will be released this frame. The third transaction also contains a
2807 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2808 // transaction will now no longer be presented so it is released immediately and the third
2809 // transaction doesn't need a previous release fence.
2810 sp<CallbackHandle> ch;
2811 for (auto& handle : mDrawingState.callbackHandles) {
2812 if (handle->releasePreviousBuffer &&
2813 mDrawingState.releaseBufferEndpoint == handle->listener) {
2814 ch = handle;
2815 break;
2816 }
2817 }
2818
2819 // Prevent tracing the same release multiple times.
2820 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2821 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2822 }
2823
2824 if (ch != nullptr) {
2825 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2826 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2827 ch->name = mName;
2828 }
2829}
2830
2831void Layer::onSurfaceFrameCreated(
2832 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2833 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2834 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2835 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2836 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002837 if (hasBufferOrSidebandStreamInDrawing()) {
2838 // Only log for layers with a buffer, since we expect the jank data to be drained for
2839 // these, while there may be no jank listeners for bufferless layers.
2840 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2841 mName.c_str());
2842 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2843 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2844 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002845 mPendingJankClassifications.pop_front();
2846 }
2847 mPendingJankClassifications.emplace_back(surfaceFrame);
2848}
2849
2850void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2851 for (const auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair71fcf912022-10-18 09:14:20 -07002852 handle->transformHint = mSkipReportingTransformHint
2853 ? std::nullopt
2854 : std::make_optional<uint32_t>(mTransformHint);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002855 handle->dequeueReadyTime = dequeueReadyTime;
2856 handle->currentMaxAcquiredBufferCount =
2857 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2858 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2859 handle->previousReleaseCallbackId.framenumber);
2860 }
2861
2862 for (auto& handle : mDrawingState.callbackHandles) {
2863 if (handle->releasePreviousBuffer &&
2864 mDrawingState.releaseBufferEndpoint == handle->listener) {
2865 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2866 break;
2867 }
2868 }
2869
2870 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002871 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002872 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2873 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002874 mDrawingState.callbackHandles = {};
2875}
2876
2877bool Layer::willPresentCurrentTransaction() const {
2878 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2879 return (getSidebandStreamChanged() || getAutoRefresh() ||
2880 (mDrawingState.modified &&
2881 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2882}
2883
2884bool Layer::setTransform(uint32_t transform) {
2885 if (mDrawingState.bufferTransform == transform) return false;
2886 mDrawingState.bufferTransform = transform;
2887 mDrawingState.modified = true;
2888 setTransactionFlags(eTransactionNeeded);
2889 return true;
2890}
2891
2892bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2893 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2894 mDrawingState.sequence++;
2895 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2896 mDrawingState.modified = true;
2897 setTransactionFlags(eTransactionNeeded);
2898 return true;
2899}
2900
2901bool Layer::setBufferCrop(const Rect& bufferCrop) {
2902 if (mDrawingState.bufferCrop == bufferCrop) return false;
2903
2904 mDrawingState.sequence++;
2905 mDrawingState.bufferCrop = bufferCrop;
2906
2907 mDrawingState.modified = true;
2908 setTransactionFlags(eTransactionNeeded);
2909 return true;
2910}
2911
2912bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2913 if (mDrawingState.destinationFrame == destinationFrame) return false;
2914
2915 mDrawingState.sequence++;
2916 mDrawingState.destinationFrame = destinationFrame;
2917
2918 mDrawingState.modified = true;
2919 setTransactionFlags(eTransactionNeeded);
2920 return true;
2921}
2922
2923// Translate destination frame into scale and position. If a destination frame is not set, use the
2924// provided scale and position
2925bool Layer::updateGeometry() {
2926 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2927 mDrawingState.destinationFrame.isEmpty()) {
2928 // If destination frame is not set, use the requested transform set via
2929 // Layer::setPosition and Layer::setMatrix.
2930 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2931 }
2932
2933 Rect destRect = mDrawingState.destinationFrame;
2934 int32_t destW = destRect.width();
2935 int32_t destH = destRect.height();
2936 if (destRect.left < 0) {
2937 destRect.left = 0;
2938 destRect.right = destW;
2939 }
2940 if (destRect.top < 0) {
2941 destRect.top = 0;
2942 destRect.bottom = destH;
2943 }
2944
2945 if (!mDrawingState.buffer) {
2946 ui::Transform t;
2947 t.set(destRect.left, destRect.top);
2948 return assignTransform(&mDrawingState.transform, t);
2949 }
2950
2951 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2952 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2953 // Undo any transformations on the buffer.
2954 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2955 std::swap(bufferWidth, bufferHeight);
2956 }
2957 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
2958 if (mDrawingState.transformToDisplayInverse) {
2959 if (invTransform & ui::Transform::ROT_90) {
2960 std::swap(bufferWidth, bufferHeight);
2961 }
2962 }
2963
2964 float sx = destW / static_cast<float>(bufferWidth);
2965 float sy = destH / static_cast<float>(bufferHeight);
2966 ui::Transform t;
2967 t.set(sx, 0, 0, sy);
2968 t.set(destRect.left, destRect.top);
2969 return assignTransform(&mDrawingState.transform, t);
2970}
2971
2972bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
2973 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
2974 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
2975 return false;
2976 }
2977
2978 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
2979
2980 mDrawingState.sequence++;
2981 mDrawingState.modified = true;
2982 setTransactionFlags(eTransactionNeeded);
2983
2984 return true;
2985}
2986
2987bool Layer::setPosition(float x, float y) {
2988 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
2989 return false;
2990 }
2991
2992 mRequestedTransform.set(x, y);
2993
2994 mDrawingState.sequence++;
2995 mDrawingState.modified = true;
2996 setTransactionFlags(eTransactionNeeded);
2997
2998 return true;
2999}
3000
3001bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3002 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3003 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003004 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003005 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003006 if (!buffer) {
3007 return false;
3008 }
3009
3010 const bool frameNumberChanged =
3011 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3012 const uint64_t frameNumber =
3013 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003014 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003015
3016 if (mDrawingState.buffer) {
3017 mReleasePreviousBuffer = true;
3018 if (!mBufferInfo.mBuffer ||
3019 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3020 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3021 // If mDrawingState has a buffer, and we are about to update again
3022 // before swapping to drawing state, then the first buffer will be
3023 // dropped and we should decrement the pending buffer count and
3024 // call any release buffer callbacks if set.
3025 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3026 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003027 mDrawingState.acquireFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003028 decrementPendingBufferCount();
3029 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3030 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3031 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
3032 mDrawingState.bufferSurfaceFrameTX.reset();
3033 }
3034 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3035 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3036 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003037 mLastClientCompositionFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003038 mLastClientCompositionFence = nullptr;
3039 }
Vishnu Nairc09c0232023-03-02 03:22:35 +00003040 } else {
3041 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3042 // we don't want to incorrectly classify a frame if we miss the desired present time.
3043 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003044 }
3045
liulijuneb489f62022-10-17 22:02:14 +08003046 mDrawingState.producerId = bufferData.producerId;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003047 mDrawingState.frameNumber = frameNumber;
3048 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3049 mDrawingState.buffer = std::move(buffer);
3050 mDrawingState.clientCacheId = bufferData.cachedBuffer;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003051 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3052 ? bufferData.acquireFence
3053 : Fence::NO_FENCE;
3054 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3055 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3056 // We latched this buffer unsiganled, so we need to pass the acquire fence
3057 // on the callback instead of just the acquire time, since it's unknown at
3058 // this point.
3059 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3060 } else {
3061 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3062 }
3063
3064 mDrawingState.modified = true;
3065 setTransactionFlags(eTransactionNeeded);
3066
3067 const int32_t layerId = getSequence();
3068 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3069 mOwnerUid, postTime, getGameMode());
3070 mDrawingState.desiredPresentTime = desiredPresentTime;
3071 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3072
3073 const nsecs_t presentTime = [&] {
3074 if (!isAutoTimestamp) return desiredPresentTime;
3075
3076 const auto prediction =
3077 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
3078 if (prediction.has_value()) return prediction->presentTime;
3079
3080 return static_cast<nsecs_t>(0);
3081 }();
3082
3083 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
3084 mFlinger->mScheduler->recordLayerHistory(this, presentTime, LayerUpdateType::Buffer);
3085
3086 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3087
3088 if (dequeueTime && *dequeueTime != 0) {
3089 const uint64_t bufferId = mDrawingState.buffer->getId();
3090 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3091 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3092 FrameTracer::FrameEvent::DEQUEUE);
3093 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3094 FrameTracer::FrameEvent::QUEUE);
3095 }
3096
3097 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3098 return true;
3099}
3100
3101bool Layer::setDataspace(ui::Dataspace dataspace) {
3102 mDrawingState.dataspaceRequested = true;
3103 if (mDrawingState.dataspace == dataspace) return false;
3104 mDrawingState.dataspace = dataspace;
3105 mDrawingState.modified = true;
3106 setTransactionFlags(eTransactionNeeded);
3107 return true;
3108}
3109
John Reck68796592023-01-25 13:47:12 -05003110bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
3111 if (mDrawingState.currentSdrHdrRatio == currentBufferRatio &&
3112 mDrawingState.desiredSdrHdrRatio == desiredRatio)
3113 return false;
3114 mDrawingState.currentSdrHdrRatio = currentBufferRatio;
3115 mDrawingState.desiredSdrHdrRatio = desiredRatio;
3116 mDrawingState.modified = true;
3117 setTransactionFlags(eTransactionNeeded);
3118 return true;
3119}
3120
Alec Mourif4af03e2023-02-11 00:25:24 +00003121bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3122 if (mDrawingState.cachingHint == cachingHint) return false;
3123 mDrawingState.cachingHint = cachingHint;
3124 mDrawingState.modified = true;
3125 setTransactionFlags(eTransactionNeeded);
3126 return true;
3127}
3128
Patrick Williamsbb25f802022-08-30 23:02:34 +00003129bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3130 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3131 mDrawingState.hdrMetadata = hdrMetadata;
3132 mDrawingState.modified = true;
3133 setTransactionFlags(eTransactionNeeded);
3134 return true;
3135}
3136
3137bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
3138 mDrawingState.surfaceDamageRegion = surfaceDamage;
3139 mDrawingState.modified = true;
3140 setTransactionFlags(eTransactionNeeded);
3141 return true;
3142}
3143
3144bool Layer::setApi(int32_t api) {
3145 if (mDrawingState.api == api) return false;
3146 mDrawingState.api = api;
3147 mDrawingState.modified = true;
3148 setTransactionFlags(eTransactionNeeded);
3149 return true;
3150}
3151
3152bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3153 if (mDrawingState.sidebandStream == sidebandStream) return false;
3154
3155 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3156 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3157 } else if (sidebandStream != nullptr) {
3158 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3159 }
3160
3161 mDrawingState.sidebandStream = sidebandStream;
3162 mDrawingState.modified = true;
3163 setTransactionFlags(eTransactionNeeded);
3164 if (!mSidebandStreamChanged.exchange(true)) {
3165 // mSidebandStreamChanged was false
3166 mFlinger->onLayerUpdate();
3167 }
3168 return true;
3169}
3170
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003171bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3172 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003173 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3174 if (handles.empty()) {
3175 mReleasePreviousBuffer = false;
3176 return false;
3177 }
3178
Pascal Muetschard81cef292023-02-06 12:18:52 +01003179 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003180 for (const auto& handle : handles) {
3181 // If this transaction set a buffer on this layer, release its previous buffer
3182 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3183
3184 // If this layer will be presented in this frame
3185 if (willPresent) {
3186 // If this transaction set an acquire fence on this layer, set its acquire time
3187 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3188 handle->frameNumber = mDrawingState.frameNumber;
3189
3190 // Store so latched time and release fence can be set
3191 mDrawingState.callbackHandles.push_back(handle);
3192
3193 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003194 // Queue this handle to be notified below.
3195 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003196 }
3197 }
3198
Pascal Muetschard81cef292023-02-06 12:18:52 +01003199 if (!remainingHandles.empty()) {
3200 // Notify the transaction completed threads these handles are done. These are only the
3201 // handles that were not added to the mDrawingState, which will be notified later.
3202 std::vector<JankData> jankData;
3203 transferAvailableJankData(remainingHandles, jankData);
3204 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3205 }
3206
Patrick Williamsbb25f802022-08-30 23:02:34 +00003207 mReleasePreviousBuffer = false;
3208 mCallbackHandleAcquireTimeOrFence = -1;
3209
3210 return willPresent;
3211}
3212
3213Rect Layer::getBufferSize(const State& /*s*/) const {
3214 // for buffer state layers we use the display frame size as the buffer size.
3215
3216 if (mBufferInfo.mBuffer == nullptr) {
3217 return Rect::INVALID_RECT;
3218 }
3219
3220 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3221 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3222
3223 // Undo any transformations on the buffer and return the result.
3224 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3225 std::swap(bufWidth, bufHeight);
3226 }
3227
3228 if (getTransformToDisplayInverse()) {
3229 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3230 if (invTransform & ui::Transform::ROT_90) {
3231 std::swap(bufWidth, bufHeight);
3232 }
3233 }
3234
3235 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3236}
3237
3238FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3239 if (mBufferInfo.mBuffer == nullptr) {
3240 return parentBounds;
3241 }
3242
3243 return getBufferSize(getDrawingState()).toFloatRect();
3244}
3245
3246bool Layer::fenceHasSignaled() const {
3247 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3248 return true;
3249 }
3250
3251 const bool fenceSignaled =
3252 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3253 if (!fenceSignaled) {
3254 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3255 TimeStats::LatchSkipReason::LateAcquire);
3256 }
3257
3258 return fenceSignaled;
3259}
3260
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003261void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003262 for (const auto& handle : mDrawingState.callbackHandles) {
3263 handle->refreshStartTime = refreshStartTime;
3264 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003265}
3266
3267void Layer::setAutoRefresh(bool autoRefresh) {
3268 mDrawingState.autoRefresh = autoRefresh;
3269}
3270
3271bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3272 // 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 +00003273 auto* snapshot = editLayerSnapshot();
3274 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003275
3276 if (mSidebandStreamChanged.exchange(false)) {
3277 const State& s(getDrawingState());
3278 // mSidebandStreamChanged was true
3279 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003280 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003281 if (mSidebandStream != nullptr) {
3282 setTransactionFlags(eTransactionNeeded);
3283 mFlinger->setTransactionFlags(eTraversalNeeded);
3284 }
3285 recomputeVisibleRegions = true;
3286
3287 return true;
3288 }
3289 return false;
3290}
3291
3292bool Layer::hasFrameUpdate() const {
3293 const State& c(getDrawingState());
3294 return (mDrawingStateModified || mDrawingState.modified) &&
3295 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3296}
3297
Vishnu Naird47bcee2023-02-24 18:08:51 +00003298void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003299 const State& s(getDrawingState());
3300
3301 if (!s.buffer) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003302 if (bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003303 for (auto& handle : mDrawingState.callbackHandles) {
3304 handle->latchTime = latchTime;
3305 }
3306 }
3307 return;
3308 }
3309
3310 for (auto& handle : mDrawingState.callbackHandles) {
3311 if (handle->frameNumber == mDrawingState.frameNumber) {
3312 handle->latchTime = latchTime;
3313 }
3314 }
3315
3316 const int32_t layerId = getSequence();
3317 const uint64_t bufferId = mDrawingState.buffer->getId();
3318 const uint64_t frameNumber = mDrawingState.frameNumber;
3319 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3320 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3321 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3322
3323 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3324 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3325 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3326 FrameTracer::FrameEvent::LATCH);
3327
3328 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3329 if (bufferSurfaceFrame != nullptr &&
3330 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3331 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3332 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3333 // are processing the next state.
3334 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3335 mDrawingState.acquireFenceTime->getSignalTime(),
3336 latchTime);
3337 mDrawingState.bufferSurfaceFrameTX.reset();
3338 }
3339
3340 std::deque<sp<CallbackHandle>> remainingHandles;
3341 mFlinger->getTransactionCallbackInvoker()
3342 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3343 mDrawingState.callbackHandles = remainingHandles;
3344
3345 mDrawingStateModified = false;
3346}
3347
3348void Layer::gatherBufferInfo() {
3349 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3350 decrementPendingBufferCount();
3351 }
3352
3353 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3354 mBufferInfo.mBuffer = mDrawingState.buffer;
3355 mBufferInfo.mFence = mDrawingState.acquireFence;
3356 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3357 mBufferInfo.mPixelFormat =
3358 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3359 mBufferInfo.mFrameLatencyNeeded = true;
3360 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3361 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3362 mBufferInfo.mFence = mDrawingState.acquireFence;
3363 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3364 auto lastDataspace = mBufferInfo.mDataspace;
3365 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3366 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003367 mFlinger->mHdrLayerInfoChanged = true;
3368 }
3369 if (mBufferInfo.mDesiredSdrHdrRatio != mDrawingState.desiredSdrHdrRatio) {
3370 mBufferInfo.mDesiredSdrHdrRatio = mDrawingState.desiredSdrHdrRatio;
3371 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003372 }
3373 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3374 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3375 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3376 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3377 mBufferInfo.mApi = mDrawingState.api;
3378 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003379}
3380
3381Rect Layer::computeBufferCrop(const State& s) {
3382 if (s.buffer && !s.bufferCrop.isEmpty()) {
3383 Rect bufferCrop;
3384 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3385 return bufferCrop;
3386 } else if (s.buffer) {
3387 return s.buffer->getBounds();
3388 } else {
3389 return s.bufferCrop;
3390 }
3391}
3392
3393sp<Layer> Layer::createClone() {
3394 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3395 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003396 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003397 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3398 return layer;
3399}
3400
Patrick Williamsbb25f802022-08-30 23:02:34 +00003401void Layer::decrementPendingBufferCount() {
3402 int32_t pendingBuffers = --mPendingBufferTransactions;
3403 tracePendingBufferCount(pendingBuffers);
3404}
3405
3406void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3407 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3408}
3409
3410/*
3411 * We don't want to send the layer's transform to input, but rather the
3412 * parent's transform. This is because Layer's transform is
3413 * information about how the buffer is placed on screen. The parent's
3414 * transform makes more sense to send since it's information about how the
3415 * layer is placed on screen. This transform is used by input to determine
3416 * how to go from screen space back to window space.
3417 */
3418ui::Transform Layer::getInputTransform() const {
3419 if (!hasBufferOrSidebandStream()) {
3420 return getTransform();
3421 }
3422 sp<Layer> parent = mDrawingParent.promote();
3423 if (parent == nullptr) {
3424 return ui::Transform();
3425 }
3426
3427 return parent->getTransform();
3428}
3429
3430/**
3431 * Similar to getInputTransform, we need to update the bounds to include the transform.
3432 * This is because bounds don't include the buffer transform, where the input assumes
3433 * that's already included.
3434 */
3435Rect Layer::getInputBounds() const {
3436 if (!hasBufferOrSidebandStream()) {
3437 return getCroppedBufferSize(getDrawingState());
3438 }
3439
3440 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
3441 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
3442 return bufferBounds;
3443 }
3444 return mDrawingState.transform.transform(bufferBounds);
3445}
3446
3447bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3448 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3449
3450 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3451 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3452 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3453 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3454 layer_state_t::eReparent;
3455
3456 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3457 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3458 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3459 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3460 layer_state_t::eInputInfoChanged;
3461
3462 if ((s.what & requiredFlags) != requiredFlags) {
3463 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3464 (s.what | requiredFlags) & ~s.what);
3465 return false;
3466 }
3467
3468 if (s.what & deniedFlags) {
3469 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3470 return false;
3471 }
3472
3473 if (s.what & allowedFlags) {
3474 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3475 }
3476
3477 if (s.what & layer_state_t::ePositionChanged) {
3478 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3479 ALOGV("%s: false [ePositionChanged changed]", __func__);
3480 return false;
3481 }
3482 }
3483
3484 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003485 if (mDrawingState.color.a != s.color.a) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003486 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3487 return false;
3488 }
3489 }
3490
3491 if (s.what & layer_state_t::eColorTransformChanged) {
3492 if (mDrawingState.colorTransform != s.colorTransform) {
3493 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3494 return false;
3495 }
3496 }
3497
3498 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003499 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003500 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3501 return false;
3502 }
3503 }
3504
3505 if (s.what & layer_state_t::eMatrixChanged) {
3506 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3507 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3508 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3509 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3510 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3511 return false;
3512 }
3513 }
3514
3515 if (s.what & layer_state_t::eCornerRadiusChanged) {
3516 if (mDrawingState.cornerRadius != s.cornerRadius) {
3517 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3518 return false;
3519 }
3520 }
3521
3522 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3523 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3524 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3525 return false;
3526 }
3527 }
3528
Vishnu Nairbbceb462022-10-10 04:52:13 +00003529 if (s.what & layer_state_t::eBufferTransformChanged) {
3530 if (mDrawingState.bufferTransform != s.bufferTransform) {
3531 ALOGV("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003532 return false;
3533 }
3534 }
3535
3536 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3537 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3538 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3539 return false;
3540 }
3541 }
3542
3543 if (s.what & layer_state_t::eCropChanged) {
3544 if (mDrawingState.crop != s.crop) {
3545 ALOGV("%s: false [eCropChanged changed]", __func__);
3546 return false;
3547 }
3548 }
3549
3550 if (s.what & layer_state_t::eDataspaceChanged) {
3551 if (mDrawingState.dataspace != s.dataspace) {
3552 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3553 return false;
3554 }
3555 }
3556
3557 if (s.what & layer_state_t::eHdrMetadataChanged) {
3558 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3559 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3560 return false;
3561 }
3562 }
3563
3564 if (s.what & layer_state_t::eSidebandStreamChanged) {
3565 if (mDrawingState.sidebandStream != s.sidebandStream) {
3566 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3567 return false;
3568 }
3569 }
3570
3571 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3572 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3573 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3574 return false;
3575 }
3576 }
3577
3578 if (s.what & layer_state_t::eShadowRadiusChanged) {
3579 if (mDrawingState.shadowRadius != s.shadowRadius) {
3580 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3581 return false;
3582 }
3583 }
3584
3585 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3586 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3587 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3588 return false;
3589 }
3590 }
3591
3592 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3593 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3594 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3595 return false;
3596 }
3597 }
3598
3599 if (s.what & layer_state_t::eStretchChanged) {
3600 StretchEffect temp = s.stretchEffect;
3601 temp.sanitize();
3602 if (mDrawingState.stretchEffect != temp) {
3603 ALOGV("%s: false [eStretchChanged changed]", __func__);
3604 return false;
3605 }
3606 }
3607
3608 if (s.what & layer_state_t::eBufferCropChanged) {
3609 if (mDrawingState.bufferCrop != s.bufferCrop) {
3610 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3611 return false;
3612 }
3613 }
3614
3615 if (s.what & layer_state_t::eDestinationFrameChanged) {
3616 if (mDrawingState.destinationFrame != s.destinationFrame) {
3617 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3618 return false;
3619 }
3620 }
3621
3622 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3623 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3624 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3625 return false;
3626 }
3627 }
3628
John Reck68796592023-01-25 13:47:12 -05003629 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
3630 if (mDrawingState.currentSdrHdrRatio != s.currentSdrHdrRatio ||
3631 mDrawingState.desiredSdrHdrRatio != s.desiredSdrHdrRatio) {
3632 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3633 return false;
3634 }
3635 }
3636
Patrick Williamsbb25f802022-08-30 23:02:34 +00003637 ALOGV("%s: true", __func__);
3638 return true;
3639}
3640
3641bool Layer::isHdrY410() const {
3642 // pixel format is HDR Y410 masquerading as RGBA_1010102
3643 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3644 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3645 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3646}
3647
Vishnu Naire14c6b32022-08-06 04:20:15 +00003648sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003649 // 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 +00003650 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003651}
3652
Vishnu Naire14c6b32022-08-06 04:20:15 +00003653const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003654 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003655}
3656
Vishnu Naire14c6b32022-08-06 04:20:15 +00003657LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003658 return mSnapshot.get();
3659}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003660
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003661std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3662 return std::move(mSnapshot);
3663}
3664
3665void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3666 mSnapshot = std::move(snapshot);
3667}
3668
Patrick Williamsbb25f802022-08-30 23:02:34 +00003669const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003670 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003671}
3672
Patrick Williams7584c6a2022-10-29 02:10:58 +00003673sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003674 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003675 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3676 return result;
3677}
3678
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003679sp<LayerFE> Layer::getCompositionEngineLayerFE(
3680 const frontend::LayerHierarchy::TraversalPath& path) {
3681 for (auto& [p, layerFE] : mLayerFEs) {
3682 if (p == path) {
3683 return layerFE;
3684 }
3685 }
3686 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3687 mLayerFEs.emplace_back(path, layerFE);
3688 return layerFE;
3689}
3690
Patrick Williamsbb25f802022-08-30 23:02:34 +00003691void Layer::useSurfaceDamage() {
3692 if (mFlinger->mForceFullDamage) {
3693 surfaceDamageRegion = Region::INVALID_REGION;
3694 } else {
3695 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3696 }
3697}
3698
3699void Layer::useEmptyDamage() {
3700 surfaceDamageRegion.clear();
3701}
3702
3703bool Layer::isOpaque(const Layer::State& s) const {
3704 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3705 // layer's opaque flag.
3706 if (!hasSomethingToDraw()) {
3707 return false;
3708 }
3709
3710 // if the layer has the opaque flag, then we're always opaque
3711 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3712 return true;
3713 }
3714
3715 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003716 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003717 return true;
3718 }
3719
3720 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3721 return fillsColor() && getAlpha() == 1.0_hf;
3722}
3723
3724bool Layer::canReceiveInput() const {
3725 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3726}
3727
3728bool Layer::isVisible() const {
3729 if (!hasSomethingToDraw()) {
3730 return false;
3731 }
3732
3733 if (isHiddenByPolicy()) {
3734 return false;
3735 }
3736
3737 return getAlpha() > 0.0f || hasBlur();
3738}
3739
3740void Layer::onPostComposition(const DisplayDevice* display,
3741 const std::shared_ptr<FenceTime>& glDoneFence,
3742 const std::shared_ptr<FenceTime>& presentFence,
3743 const CompositorTiming& compositorTiming) {
3744 // mFrameLatencyNeeded is true when a new frame was latched for the
3745 // composition.
3746 if (!mBufferInfo.mFrameLatencyNeeded) return;
3747
3748 for (const auto& handle : mDrawingState.callbackHandles) {
3749 handle->gpuCompositionDoneFence = glDoneFence;
3750 handle->compositorTiming = compositorTiming;
3751 }
3752
3753 // Update mFrameTracker.
3754 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3755 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3756
3757 const int32_t layerId = getSequence();
3758 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3759
3760 const auto outputLayer = findOutputLayerForDisplay(display);
3761 if (outputLayer && outputLayer->requiresClientComposition()) {
3762 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3763 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3764 clientCompositionTimestamp,
3765 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3766 // Update the SurfaceFrames in the drawing state
3767 if (mDrawingState.bufferSurfaceFrameTX) {
3768 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3769 }
3770 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3771 surfaceFrame->setGpuComposition();
3772 }
3773 }
3774
3775 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3776 if (frameReadyFence->isValid()) {
3777 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3778 } else {
3779 // There was no fence for this frame, so assume that it was ready
3780 // to be presented at the desired present time.
3781 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3782 }
3783
3784 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08003785 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003786 const std::optional<Fps> renderRate =
3787 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3788
3789 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3790 const auto gameMode = getGameMode();
3791
3792 if (presentFence->isValid()) {
3793 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3794 refreshRate, renderRate, vote, gameMode);
3795 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3796 presentFence,
3797 FrameTracer::FrameEvent::PRESENT_FENCE);
3798 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3799 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3800 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003801 // The HWC doesn't support present fences, so use the present timestamp instead.
3802 const nsecs_t presentTimestamp =
3803 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3804
3805 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3806 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3807 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3808
Patrick Williamsbb25f802022-08-30 23:02:34 +00003809 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3810 refreshRate, renderRate, vote, gameMode);
3811 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3812 mCurrentFrameNumber, actualPresentTime,
3813 FrameTracer::FrameEvent::PRESENT_FENCE);
3814 mFrameTracker.setActualPresentTime(actualPresentTime);
3815 }
3816 }
3817
3818 mFrameTracker.advanceFrame();
3819 mBufferInfo.mFrameLatencyNeeded = false;
3820}
3821
3822bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003823 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
3824 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
3825}
3826
3827bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003828 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3829 getDrawingState().frameNumber);
3830
3831 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3832
3833 if (refreshRequired) {
3834 return refreshRequired;
3835 }
3836
3837 // If the head buffer's acquire fence hasn't signaled yet, return and
3838 // try again later
3839 if (!fenceHasSignaled()) {
3840 ATRACE_NAME("!fenceHasSignaled()");
3841 mFlinger->onLayerUpdate();
3842 return false;
3843 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00003844 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003845 if (mDrawingState.buffer == nullptr) {
3846 return false;
3847 }
3848
3849 // Capture the old state of the layer for comparisons later
3850 BufferInfo oldBufferInfo = mBufferInfo;
3851 const bool oldOpacity = isOpaque(mDrawingState);
3852 mPreviousFrameNumber = mCurrentFrameNumber;
3853 mCurrentFrameNumber = mDrawingState.frameNumber;
3854 gatherBufferInfo();
3855
3856 if (oldBufferInfo.mBuffer == nullptr) {
3857 // the first time we receive a buffer, we need to trigger a
3858 // geometry invalidation.
3859 recomputeVisibleRegions = true;
3860 }
3861
3862 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3863 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3864 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3865 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3866 recomputeVisibleRegions = true;
3867 }
3868
3869 if (oldBufferInfo.mBuffer != nullptr) {
3870 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3871 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3872 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3873 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3874 recomputeVisibleRegions = true;
3875 }
3876 }
3877
3878 if (oldOpacity != isOpaque(mDrawingState)) {
3879 recomputeVisibleRegions = true;
3880 }
3881
3882 return true;
3883}
3884
3885bool Layer::hasReadyFrame() const {
3886 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
3887}
3888
3889bool Layer::isProtected() const {
3890 return (mBufferInfo.mBuffer != nullptr) &&
3891 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
3892}
3893
Patrick Williamsbb25f802022-08-30 23:02:34 +00003894void Layer::latchAndReleaseBuffer() {
3895 if (hasReadyFrame()) {
3896 bool ignored = false;
3897 latchBuffer(ignored, systemTime());
3898 }
3899 releasePendingBuffer(systemTime());
3900}
3901
3902PixelFormat Layer::getPixelFormat() const {
3903 return mBufferInfo.mPixelFormat;
3904}
3905
3906bool Layer::getTransformToDisplayInverse() const {
3907 return mBufferInfo.mTransformToDisplayInverse;
3908}
3909
3910Rect Layer::getBufferCrop() const {
3911 // this is the crop rectangle that applies to the buffer
3912 // itself (as opposed to the window)
3913 if (!mBufferInfo.mCrop.isEmpty()) {
3914 // if the buffer crop is defined, we use that
3915 return mBufferInfo.mCrop;
3916 } else if (mBufferInfo.mBuffer != nullptr) {
3917 // otherwise we use the whole buffer
3918 return mBufferInfo.mBuffer->getBounds();
3919 } else {
3920 // if we don't have a buffer yet, we use an empty/invalid crop
3921 return Rect();
3922 }
3923}
3924
3925uint32_t Layer::getBufferTransform() const {
3926 return mBufferInfo.mTransform;
3927}
3928
3929ui::Dataspace Layer::getDataSpace() const {
3930 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
3931}
3932
3933ui::Dataspace Layer::getRequestedDataSpace() const {
3934 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
3935}
3936
3937ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
3938 ui::Dataspace updatedDataspace = dataspace;
3939 // translate legacy dataspaces to modern dataspaces
3940 switch (dataspace) {
3941 case ui::Dataspace::SRGB:
3942 updatedDataspace = ui::Dataspace::V0_SRGB;
3943 break;
3944 case ui::Dataspace::SRGB_LINEAR:
3945 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
3946 break;
3947 case ui::Dataspace::JFIF:
3948 updatedDataspace = ui::Dataspace::V0_JFIF;
3949 break;
3950 case ui::Dataspace::BT601_625:
3951 updatedDataspace = ui::Dataspace::V0_BT601_625;
3952 break;
3953 case ui::Dataspace::BT601_525:
3954 updatedDataspace = ui::Dataspace::V0_BT601_525;
3955 break;
3956 case ui::Dataspace::BT709:
3957 updatedDataspace = ui::Dataspace::V0_BT709;
3958 break;
3959 default:
3960 break;
3961 }
3962
3963 return updatedDataspace;
3964}
3965
3966sp<GraphicBuffer> Layer::getBuffer() const {
3967 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
3968}
3969
Patrick Williamsbb25f802022-08-30 23:02:34 +00003970void Layer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
3971 mTransformHint = getFixedTransformHint();
3972 if (mTransformHint == ui::Transform::ROT_INVALID) {
3973 mTransformHint = displayTransformHint;
3974 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07003975 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003976}
3977
3978const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
3979 return mBufferInfo.mBuffer;
3980}
3981
3982bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003983 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003984 return false;
3985 }
3986
3987 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00003988 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003989 mDrawingState.modified = true;
3990 setTransactionFlags(eTransactionNeeded);
3991 return true;
3992}
3993
3994bool Layer::fillsColor() const {
3995 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
3996 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
3997}
3998
3999bool Layer::hasBlur() const {
4000 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4001}
4002
Vishnu Nairba354102022-08-01 00:14:18 +00004003void Layer::updateSnapshot(bool updateGeometry) {
4004 if (!getCompositionEngineLayerFE()) {
4005 return;
4006 }
4007
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004008 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004009 if (updateGeometry) {
4010 prepareBasicGeometryCompositionState();
4011 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004012 snapshot->roundedCorner = getRoundedCornerState();
4013 snapshot->stretchEffect = getStretchEffect();
4014 snapshot->transformedBounds = mScreenBounds;
4015 if (mEffectiveShadowRadius > 0.f) {
4016 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4017
4018 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4019 // it if transparent regions are present. This may not be necessary since shadows are
4020 // typically cast by layers without transparent regions.
4021 snapshot->shadowSettings.boundaries = mBounds;
4022
4023 const float casterAlpha = snapshot->alpha;
4024 const bool casterIsOpaque =
4025 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4026
4027 // If the casting layer is translucent, we need to fill in the shadow underneath the
4028 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4029 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4030 snapshot->shadowSettings.ambientColor *= casterAlpha;
4031 snapshot->shadowSettings.spotColor *= casterAlpha;
4032 }
4033 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004034 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004035 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004036 snapshot->layerOpaqueFlagSet =
4037 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004038 snapshot->isHdrY410 = isHdrY410();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004039 sp<Layer> p = mDrawingParent.promote();
4040 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004041 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004042 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004043 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004044 }
4045 snapshot->bufferSize = getBufferSize(mDrawingState);
4046 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004047 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004048 preparePerFrameCompositionState();
4049}
4050
Vishnu Naire14c6b32022-08-06 04:20:15 +00004051void Layer::updateChildrenSnapshots(bool updateGeometry) {
4052 for (const sp<Layer>& child : mDrawingChildren) {
4053 child->updateSnapshot(updateGeometry);
4054 child->updateChildrenSnapshots(updateGeometry);
4055 }
4056}
4057
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004058void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4059 mSnapshot->layerMetadata = parentMetadata;
4060 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4061 for (const sp<Layer>& child : mDrawingChildren) {
4062 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4063 }
4064}
4065
4066void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4067 std::unordered_set<Layer*>& visited) {
4068 if (visited.find(this) != visited.end()) {
4069 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4070 return;
4071 }
4072 visited.insert(this);
4073
4074 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4075
4076 if (mDrawingState.zOrderRelatives.empty()) {
4077 return;
4078 }
4079 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4080 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4081 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4082 sp<Layer> relative = weakRelative.promote();
4083 if (!relative) {
4084 continue;
4085 }
4086 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4087 }
4088}
4089
Chavi Weingarten328a8312023-01-26 21:17:52 +00004090bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004091 TrustedPresentationListener const& listener) {
4092 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4093 mTrustedPresentationListener = listener;
4094 mTrustedPresentationThresholds = thresholds;
4095 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4096 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4097 mFlinger->mNumTrustedPresentationListeners++;
4098 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4099 mFlinger->mNumTrustedPresentationListeners--;
4100 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004101
4102 // Reset trusted presentation states to ensure we start the time again.
4103 mEnteredTrustedPresentationStateTime = -1;
4104 mLastReportedTrustedPresentationState = false;
4105 mLastComputedTrustedPresentationState = false;
4106
4107 // If there's a new trusted presentation listener, the code needs to go through the composite
4108 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4109 // we're already in the requested state.
4110 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004111}
4112
Vishnu Naira156f482023-02-22 00:23:38 +00004113void Layer::updateLastLatchTime(nsecs_t latchTime) {
4114 mLastLatchTime = latchTime;
4115}
4116
Mathias Agopian13127d82013-03-05 17:47:11 -08004117// ---------------------------------------------------------------------------
4118
Marin Shalamanov46084422020-10-13 12:33:42 +02004119std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004120 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4121 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004122}
4123
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004124} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004125
4126#if defined(__gl_h_)
4127#error "don't include gl/gl.h in this file"
4128#endif
4129
4130#if defined(__gl2_h_)
4131#error "don't include gl2/gl2.h in this file"
4132#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004133
4134// TODO(b/129481165): remove the #pragma below and fix conversion issues
4135#pragma clang diagnostic pop // ignored "-Wconversion"