blob: a97144a6fe4a9909e99b8a9b1fa0bd8b856205fd [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;
ramindanib2158ee2023-02-13 20:29:59 -0800683 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
684 snapshot->compositionType =
685 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000686 } else {
687 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000688 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
689 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000690 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
691 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
692 }
693
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000694 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000695 snapshot->acquireFence = mBufferInfo.mFence;
696 snapshot->frameNumber = mBufferInfo.mFrameNumber;
697 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000698}
699
700void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000701 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000702 auto* snapshot = editLayerSnapshot();
703 snapshot->color = getColor();
704 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000705 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800706}
707
Lloyd Piquede196652020-01-22 17:29:58 -0800708void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800709 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000710 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000711 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800712
713 // Apply the layer's transform, followed by the display's global transform
714 // Here we're guaranteed that the layer's transform preserves rects
715 Rect win = getCroppedBufferSize(drawingState);
716 // Subtract the transparent region and snap to the bounds
717 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
718 Rect frame(getTransform().transform(bounds));
719
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000720 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800721}
722
Lloyd Piquea83776c2019-01-29 18:42:32 -0800723const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700724 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800725}
726
Mathias Agopian13127d82013-03-05 17:47:11 -0800727// ---------------------------------------------------------------------------
728// drawing...
729// ---------------------------------------------------------------------------
730
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500731aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
732 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700733 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800734 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500735 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800736 }
737 if (outputLayer->getState().hwc) {
738 return (*outputLayer->getState().hwc).hwcCompositionType;
739 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500740 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800741 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800742}
743
Mathias Agopian13127d82013-03-05 17:47:11 -0800744// ----------------------------------------------------------------------------
745// local state
746// ----------------------------------------------------------------------------
747
David Sodman41fdfc92017-11-06 16:09:56 -0800748bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800749 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700750 if (s.flags & layer_state_t::eLayerSecure) {
751 return true;
752 }
753
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000754 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700755 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700756}
757
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100758void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
759 std::vector<JankData>& jankData) {
760 if (mPendingJankClassifications.empty() ||
761 !mPendingJankClassifications.front()->getJankType()) {
762 return;
763 }
764
765 bool includeJankData = false;
766 for (const auto& handle : handles) {
767 for (const auto& cb : handle->callbackIds) {
768 if (cb.includeJankData) {
769 includeJankData = true;
770 break;
771 }
772 }
773
774 if (includeJankData) {
775 jankData.reserve(mPendingJankClassifications.size());
776 break;
777 }
778 }
779
780 while (!mPendingJankClassifications.empty() &&
781 mPendingJankClassifications.front()->getJankType()) {
782 if (includeJankData) {
783 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
784 mPendingJankClassifications.front();
785 jankData.emplace_back(
786 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
787 }
788 mPendingJankClassifications.pop_front();
789 }
790}
791
Mathias Agopian13127d82013-03-05 17:47:11 -0800792// ----------------------------------------------------------------------------
793// transaction
794// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800795
Vishnu Naira156f482023-02-22 00:23:38 +0000796uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700797 ATRACE_CALL();
798
Robert Carr0758e5d2021-03-11 22:15:04 -0800799 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700800 mDrawingStateModified = mDrawingState.modified;
801 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700802
Alec Mourib416efd2018-09-06 21:01:59 +0000803 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700804
Robert Carr6a160312021-05-17 12:08:20 -0700805 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800806 // invalidate and recompute the visible regions if needed
807 flags |= Layer::eVisibleRegion;
808 }
809
Robert Carr6a160312021-05-17 12:08:20 -0700810 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800811 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000812 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800813 flags |= eVisibleRegion;
814 this->contentDirty = true;
815
816 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700817 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800818 }
819
Arthur Hung9ed43392022-05-27 06:31:57 +0000820 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
821 mFlinger->mUpdateInputInfo = true;
822 }
823
Vishnu Naira156f482023-02-22 00:23:38 +0000824 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800825
Mathias Agopian13127d82013-03-05 17:47:11 -0800826 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800827}
828
Vishnu Naira156f482023-02-22 00:23:38 +0000829void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000830 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
831 // bufferSurfaceFrameTX will be presented in latchBuffer.
832 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
833 if (surfaceFrame->getPresentState() != PresentState::Presented) {
834 // With applyPendingStates, we could end up having presented surfaceframes from previous
835 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800836 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000837 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
838 }
839 }
Robert Carr6a160312021-05-17 12:08:20 -0700840 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700841}
842
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700843uint32_t Layer::clearTransactionFlags(uint32_t mask) {
844 const auto flags = mTransactionFlags & mask;
845 mTransactionFlags &= ~mask;
846 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800847}
848
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700849void Layer::setTransactionFlags(uint32_t mask) {
850 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800851}
852
Robert Carr1f0a16a2016-10-24 16:27:39 -0700853bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
854 ssize_t idx = mCurrentChildren.indexOf(childLayer);
855 if (idx < 0) {
856 return false;
857 }
858 if (childLayer->setLayer(z)) {
859 mCurrentChildren.removeAt(idx);
860 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800861 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700862 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800863 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700864}
865
Robert Carr503c7042017-09-27 15:06:08 -0700866bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
867 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
868 ssize_t idx = mCurrentChildren.indexOf(childLayer);
869 if (idx < 0) {
870 return false;
871 }
872 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
873 mCurrentChildren.removeAt(idx);
874 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800875 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700876 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800877 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700878}
879
Robert Carrae060832016-11-28 10:51:00 -0800880bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700881 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
882 mDrawingState.sequence++;
883 mDrawingState.z = z;
884 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700885
Robert Carra70e91c2021-06-11 13:59:52 -0700886 mFlinger->mSomeChildrenChanged = true;
887
Robert Carrdb66e622017-04-10 16:55:57 -0700888 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700889 if (mDrawingState.zOrderRelativeOf != nullptr) {
890 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700891 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700892 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700893 }
chaviw606e5cf2019-03-01 10:12:10 -0800894 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700895 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800896 setTransactionFlags(eTransactionNeeded);
897 return true;
898}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700899
Robert Carrdb66e622017-04-10 16:55:57 -0700900void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700901 mDrawingState.zOrderRelatives.remove(relative);
902 mDrawingState.sequence++;
903 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700904 setTransactionFlags(eTransactionNeeded);
905}
906
907void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700908 mDrawingState.zOrderRelatives.add(relative);
909 mDrawingState.modified = true;
910 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700911 setTransactionFlags(eTransactionNeeded);
912}
913
chaviw606e5cf2019-03-01 10:12:10 -0800914void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700915 mDrawingState.zOrderRelativeOf = relativeOf;
916 mDrawingState.sequence++;
917 mDrawingState.modified = true;
918 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700919
chaviw606e5cf2019-03-01 10:12:10 -0800920 setTransactionFlags(eTransactionNeeded);
921}
922
Robert Carr503d2bd2017-12-04 15:49:47 -0800923bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000924 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700925 if (relative == nullptr) {
926 return false;
927 }
928
Robert Carr6a160312021-05-17 12:08:20 -0700929 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
930 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800931 return false;
932 }
933
Robert Carr88b85e12022-03-21 15:47:35 -0700934 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
935 (relative->mDrawingState.zOrderRelativeOf == this)) {
936 ALOGE("Detected relative layer loop between %s and %s",
937 mName.c_str(), relative->mName.c_str());
938 ALOGE("Ignoring new call to set relative layer");
939 return false;
940 }
941
Robert Carra70e91c2021-06-11 13:59:52 -0700942 mFlinger->mSomeChildrenChanged = true;
943
Robert Carr6a160312021-05-17 12:08:20 -0700944 mDrawingState.sequence++;
945 mDrawingState.modified = true;
946 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700947
Robert Carr6a160312021-05-17 12:08:20 -0700948 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700949 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700950 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700951 }
chaviw606e5cf2019-03-01 10:12:10 -0800952 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700953 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700954
955 setTransactionFlags(eTransactionNeeded);
956
957 return true;
958}
959
Winson Chunga30f7c92021-06-29 15:42:56 -0700960bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
961 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
962 mDrawingState.isTrustedOverlay = isTrustedOverlay;
963 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000964 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700965 setTransactionFlags(eTransactionNeeded);
966 return true;
967}
968
969bool Layer::isTrustedOverlay() const {
970 if (getDrawingState().isTrustedOverlay) {
971 return true;
972 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000973 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700974 return (p != nullptr) && p->isTrustedOverlay();
975}
976
Dan Stoza9e56aa02015-11-02 13:00:03 -0800977bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700978 if (mDrawingState.color.a == alpha) return false;
979 mDrawingState.sequence++;
980 mDrawingState.color.a = alpha;
981 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800982 setTransactionFlags(eTransactionNeeded);
983 return true;
984}
chaviw13fdc492017-06-27 12:40:18 -0700985
Valerie Haudd0b7572019-01-29 14:59:27 -0800986bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700987 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700988 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800989 }
Robert Carr6a160312021-05-17 12:08:20 -0700990 mDrawingState.sequence++;
991 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800992 setTransactionFlags(eTransactionNeeded);
993
Robert Carr6a160312021-05-17 12:08:20 -0700994 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -0800995 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -0800996 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700997 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -0700998 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800999 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001000 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001001
Valerie Haudd0b7572019-01-29 14:59:27 -08001002 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001003 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001004 mFlinger->mLayersAdded = true;
1005 // set up SF to handle added color layer
1006 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -07001007 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001008 }
1009 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001010 } else if (mDrawingState.bgColorLayer && alpha == 0) {
1011 mDrawingState.bgColorLayer->reparent(nullptr);
1012 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001013 return true;
1014 }
1015
Robert Carr6a160312021-05-17 12:08:20 -07001016 mDrawingState.bgColorLayer->setColor(color);
1017 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1018 mDrawingState.bgColorLayer->setAlpha(alpha);
1019 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001020
chaviw13fdc492017-06-27 12:40:18 -07001021 return true;
1022}
1023
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001024bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001025 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001026
Robert Carr6a160312021-05-17 12:08:20 -07001027 mDrawingState.sequence++;
1028 mDrawingState.cornerRadius = cornerRadius;
1029 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001030 setTransactionFlags(eTransactionNeeded);
1031 return true;
1032}
1033
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001034bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001035 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001036 // If we start or stop drawing blur then the layer's visibility state may change so increment
1037 // the magic sequence number.
1038 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1039 mDrawingState.sequence++;
1040 }
Robert Carr6a160312021-05-17 12:08:20 -07001041 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1042 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001043 setTransactionFlags(eTransactionNeeded);
1044 return true;
1045}
Marissa Wall61c58622018-07-18 10:12:20 -07001046
Mathias Agopian13127d82013-03-05 17:47:11 -08001047bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001048 mDrawingState.sequence++;
1049 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001050 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001051 setTransactionFlags(eTransactionNeeded);
1052 return true;
1053}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001054
Lucas Dupinc3800b82020-10-02 16:24:48 -07001055bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001056 // If we start or stop drawing blur then the layer's visibility state may change so increment
1057 // the magic sequence number.
1058 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1059 mDrawingState.sequence++;
1060 }
Robert Carr6a160312021-05-17 12:08:20 -07001061 mDrawingState.blurRegions = blurRegions;
1062 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001063 setTransactionFlags(eTransactionNeeded);
1064 return true;
1065}
1066
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001067bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001068 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1069 if (mDrawingState.flags == newFlags) return false;
1070 mDrawingState.sequence++;
1071 mDrawingState.flags = newFlags;
1072 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001073 setTransactionFlags(eTransactionNeeded);
1074 return true;
1075}
Robert Carr99e27f02016-06-16 15:18:02 -07001076
chaviw25714502021-02-11 10:01:08 -08001077bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001078 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001079 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001080 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001081
Robert Carr6a160312021-05-17 12:08:20 -07001082 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001083 setTransactionFlags(eTransactionNeeded);
1084 return true;
1085}
Robert Carr8d5227b2017-03-16 15:41:03 -07001086
Evan Roskyef876c92019-01-25 17:46:06 -08001087bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001088 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1089 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001090 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001091 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001092}
1093
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001094bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001095 if (mDrawingState.layerStack == layerStack) return false;
1096 mDrawingState.sequence++;
1097 mDrawingState.layerStack = layerStack;
1098 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001099 setTransactionFlags(eTransactionNeeded);
1100 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001101}
1102
Peiyong Linc502cb72019-03-01 15:00:23 -08001103bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001104 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001105 return false;
1106 }
Robert Carr6a160312021-05-17 12:08:20 -07001107 mDrawingState.sequence++;
1108 mDrawingState.colorSpaceAgnostic = agnostic;
1109 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001110 setTransactionFlags(eTransactionNeeded);
1111 return true;
1112}
1113
Sally Qi81d95e62022-03-21 19:41:33 -07001114bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1115 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1116
1117 mDrawingState.sequence++;
1118 mDrawingState.dimmingEnabled = dimmingEnabled;
1119 mDrawingState.modified = true;
1120 setTransactionFlags(eTransactionNeeded);
1121 return true;
1122}
1123
Ana Krulecc84d09b2019-11-02 23:10:29 +01001124bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001125 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1126 mDrawingState.frameRateSelectionPriority = priority;
1127 mDrawingState.sequence++;
1128 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001129 setTransactionFlags(eTransactionNeeded);
1130 return true;
1131}
1132
1133int32_t Layer::getFrameRateSelectionPriority() const {
1134 // Check if layer has priority set.
1135 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1136 return mDrawingState.frameRateSelectionPriority;
1137 }
1138 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001139 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001140 if (parent != nullptr) {
1141 return parent->getFrameRateSelectionPriority();
1142 }
1143
1144 return Layer::PRIORITY_UNSET;
1145}
1146
Andy Labrada096227e2022-06-15 16:58:11 +00001147bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1148 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1149 mDrawingState.defaultFrameRateCompatibility = compatibility;
1150 mDrawingState.modified = true;
1151 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1152 setTransactionFlags(eTransactionNeeded);
1153 return true;
1154}
1155
1156scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1157 return mDrawingState.defaultFrameRateCompatibility;
1158}
1159
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001160bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1161 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1162};
1163
Vishnu Nair73908d12022-10-24 21:46:42 -07001164ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1165 bool useDrawing = state == LayerVector::StateSet::Drawing;
1166 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1167 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001168 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001169 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001170 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001171}
1172
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001173bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001174 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001175 return false;
1176 }
1177
Robert Carr6a160312021-05-17 12:08:20 -07001178 mDrawingState.sequence++;
1179 mDrawingState.shadowRadius = shadowRadius;
1180 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001181 setTransactionFlags(eTransactionNeeded);
1182 return true;
1183}
1184
Vishnu Nair6213bd92020-05-08 17:42:25 -07001185bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001186 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001187 return false;
1188 }
1189
Robert Carr6a160312021-05-17 12:08:20 -07001190 mDrawingState.sequence++;
1191 mDrawingState.fixedTransformHint = fixedTransformHint;
1192 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001193 setTransactionFlags(eTransactionNeeded);
1194 return true;
1195}
1196
John Reckcdb4ed72021-02-04 13:39:33 -05001197bool Layer::setStretchEffect(const StretchEffect& effect) {
1198 StretchEffect temp = effect;
1199 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001200 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001201 return false;
1202 }
Robert Carr6a160312021-05-17 12:08:20 -07001203 mDrawingState.sequence++;
1204 mDrawingState.stretchEffect = temp;
1205 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001206 setTransactionFlags(eTransactionNeeded);
1207 return true;
1208}
1209
John Reckc00c6692021-02-16 11:37:33 -05001210StretchEffect Layer::getStretchEffect() const {
1211 if (mDrawingState.stretchEffect.hasEffect()) {
1212 return mDrawingState.stretchEffect;
1213 }
1214
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001215 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001216 if (parent != nullptr) {
1217 auto effect = parent->getStretchEffect();
1218 if (effect.hasEffect()) {
1219 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1220 return effect;
1221 }
1222 }
1223 return StretchEffect{};
1224}
1225
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001226bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1227 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001228 return false;
1229 }
1230 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001231 mBorderWidth = width;
1232 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001233 return true;
1234}
1235
1236bool Layer::isBorderEnabled() {
1237 return mBorderEnabled;
1238}
1239
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001240float Layer::getBorderWidth() {
1241 return mBorderWidth;
1242}
1243
1244const half4& Layer::getBorderColor() {
1245 return mBorderColor;
1246}
1247
Ady Abrahama850c182021-08-04 13:04:37 -07001248bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1249 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1250 const auto frameRate = [&] {
1251 if (mDrawingState.frameRate.rate.isValid() ||
1252 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1253 return mDrawingState.frameRate;
1254 }
1255
1256 return parentFrameRate;
1257 }();
1258
1259 *transactionNeeded |= setFrameRateForLayerTree(frameRate);
1260
1261 // The frame rate is propagated to the children
1262 bool childrenHaveFrameRate = false;
1263 for (const sp<Layer>& child : mCurrentChildren) {
1264 childrenHaveFrameRate |=
1265 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1266 }
1267
1268 // If we don't have a valid frame rate, but the children do, we set this
1269 // layer as NoVote to allow the children to control the refresh rate
1270 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1271 childrenHaveFrameRate) {
1272 *transactionNeeded |=
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001273 setFrameRateForLayerTree(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001274 }
1275
1276 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1277 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001278 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001279 const auto layerVotedWithDefaultCompatibility =
1280 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1281 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1282 const auto layerVotedWithExactCompatibility =
1283 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1284 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1285 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1286}
1287
Ady Abraham60e42ea2020-03-09 19:17:31 -07001288void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001289 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001290 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001291 while (auto parent = layer->getParent()) {
1292 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001293 }
Ady Abrahama850c182021-08-04 13:04:37 -07001294 return layer;
1295 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001296
Ady Abraham60e42ea2020-03-09 19:17:31 -07001297 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001298 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001299
Ady Abrahama850c182021-08-04 13:04:37 -07001300 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001301 if (transactionNeeded) {
1302 mFlinger->setTransactionFlags(eTraversalNeeded);
1303 }
1304}
1305
Ady Abraham71c437d2020-01-31 15:56:57 -08001306bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001307 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001308 return false;
1309 }
1310
Robert Carr6a160312021-05-17 12:08:20 -07001311 mDrawingState.sequence++;
1312 mDrawingState.frameRate = frameRate;
1313 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001314
1315 updateTreeHasFrameRateVote();
1316
Steven Thomas3172e202020-01-06 19:25:30 -08001317 setTransactionFlags(eTransactionNeeded);
1318 return true;
1319}
1320
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001321void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1322 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001323 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001324
1325 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1326 // there are two transactions with the same token, the first one without a buffer and the
1327 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1328 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001329 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1330 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001331 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001332 mDrawingState.bufferSurfaceFrameTX = it->second;
1333 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1334 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1335 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001336 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001337 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001338 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1339 }
1340}
1341
1342void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1343 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001344 mDrawingState.frameTimelineInfo = info;
1345 mDrawingState.postTime = postTime;
1346 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001347 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001348
Robert Carr6a160312021-05-17 12:08:20 -07001349 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001350 bufferSurfaceFrameTX != nullptr) {
1351 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1352 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1353 // being used for BufferSurfaceFrame, don't create a new one.
1354 return;
1355 }
1356 }
1357 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1358 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1359 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001360 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1361 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001362 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001363 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001364 } else {
1365 if (it->second->getPresentState() == PresentState::Presented) {
1366 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1367 // have been from previous vsync.
1368 it->second = createSurfaceFrameForTransaction(info, postTime);
1369 }
1370 }
1371}
1372
1373void Layer::addSurfaceFrameDroppedForBuffer(
1374 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001375 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001376 surfaceFrame->setPresentState(PresentState::Dropped);
1377 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1378}
1379
1380void Layer::addSurfaceFramePresentedForBuffer(
1381 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1382 nsecs_t currentLatchTime) {
1383 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1384 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1385 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001386 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001387}
1388
1389std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1390 const FrameTimelineInfo& info, nsecs_t postTime) {
1391 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001392 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1393 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001394 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001395 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001396 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001397 // For Transactions, the post time is considered to be both queue and acquire fence time.
1398 surfaceFrame->setActualQueueTime(postTime);
1399 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001400 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1401 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001402 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001403 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001404 onSurfaceFrameCreated(surfaceFrame);
1405 return surfaceFrame;
1406}
1407
1408std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1409 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1410 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001411 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001412 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001413 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001414 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001415 // For buffers, acquire fence time will set during latch.
1416 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001417 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1418 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001419 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001420 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001421 onSurfaceFrameCreated(surfaceFrame);
1422 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001423}
1424
Ady Abrahama850c182021-08-04 13:04:37 -07001425bool Layer::setFrameRateForLayerTree(FrameRate frameRate) {
1426 if (mDrawingState.frameRateForLayerTree == frameRate) {
1427 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001428 }
1429
Ady Abrahama850c182021-08-04 13:04:37 -07001430 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001431
Ady Abrahama850c182021-08-04 13:04:37 -07001432 // TODO(b/195668952): we probably don't need to dirty visible regions here
1433 // or even store frameRateForLayerTree in mDrawingState
1434 mDrawingState.sequence++;
1435 mDrawingState.modified = true;
1436 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001437
Dominik Laskowski068173d2021-08-11 17:22:59 -07001438 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
1439 mFlinger->mScheduler->recordLayerHistory(this, systemTime(), LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001440
1441 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001442}
1443
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001444Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1445 return getDrawingState().frameRateForLayerTree;
1446}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001447
Robert Carr1f0a16a2016-10-24 16:27:39 -07001448bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001449 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001450 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001451 if (parent != nullptr && parent->isHiddenByPolicy()) {
1452 return true;
1453 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001454 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1455 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1456 if (zOrderRelativeOf != nullptr) {
1457 if (zOrderRelativeOf->isHiddenByPolicy()) {
1458 return true;
1459 }
1460 }
1461 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001462 if (CC_UNLIKELY(!isTransformValid())) {
1463 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1464 return true;
1465 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001466 return s.flags & layer_state_t::eLayerHidden;
1467}
1468
David Sodman41fdfc92017-11-06 16:09:56 -08001469uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001470 // TODO: should we do something special if mSecure is set?
1471 if (mProtectedByApp) {
1472 // need a hardware-protected path to external video sink
1473 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001474 }
Riley Andrews03414a12014-07-01 14:22:59 -07001475 if (mPotentialCursor) {
1476 usage |= GraphicBuffer::USAGE_CURSOR;
1477 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001478 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001479 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001480}
1481
Vishnu Nair71fcf912022-10-18 09:14:20 -07001482void Layer::skipReportingTransformHint() {
1483 mSkipReportingTransformHint = true;
1484}
1485
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001486void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1487 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1488 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001489 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001490
Vishnu Nair6213bd92020-05-08 17:42:25 -07001491 setTransformHint(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001492}
1493
Mathias Agopian13127d82013-03-05 17:47:11 -08001494// ----------------------------------------------------------------------------
1495// debugging
1496// ----------------------------------------------------------------------------
1497
Marissa Wall61c58622018-07-18 10:12:20 -07001498// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001499gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001500 using namespace std::string_literals;
1501
Huihong Luo05539a12022-02-23 10:29:40 -08001502 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001503 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001504 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001505 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001506 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001507 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001508
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001509 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001510 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001511 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001512 info.mX = ds.transform.tx();
1513 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001514 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001515 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001516 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001517 info.mFlags = ds.flags;
1518 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001519 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001520 info.mMatrix[0][0] = ds.transform[0][0];
1521 info.mMatrix[0][1] = ds.transform[0][1];
1522 info.mMatrix[1][0] = ds.transform[1][0];
1523 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001524 {
chaviwd62d3062019-09-04 14:48:02 -07001525 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001526 if (buffer != 0) {
1527 info.mActiveBufferWidth = buffer->getWidth();
1528 info.mActiveBufferHeight = buffer->getHeight();
1529 info.mActiveBufferStride = buffer->getStride();
1530 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001531 } else {
1532 info.mActiveBufferWidth = 0;
1533 info.mActiveBufferHeight = 0;
1534 info.mActiveBufferStride = 0;
1535 info.mActiveBufferFormat = 0;
1536 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001537 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001538 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001539 info.mIsOpaque = isOpaque(ds);
1540 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001541 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001542 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001543}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001544
Yiwei Zhang5434a782018-12-05 18:06:32 -08001545void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001546 result.append(kDumpTableRowLength, '-');
1547 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001548 result.append(" Layer name\n");
1549 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001550 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001551 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001552 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001553 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001554 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001555 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1556 result.append(kDumpTableRowLength, '-');
1557 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001558}
1559
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001560void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1561 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001562 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001563 return;
1564 }
1565
Yiwei Zhang5434a782018-12-05 18:06:32 -08001566 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001567 if (mName.length() > 77) {
1568 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001569 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001570 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001571 shortened.append(mName, mName.length() - 36);
1572 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001573 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001574 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001575 }
1576
Yiwei Zhang5434a782018-12-05 18:06:32 -08001577 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001578
Alec Mourib416efd2018-09-06 21:01:59 +00001579 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001580 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001581
Chia-I Wu1e043612018-03-01 09:45:09 -08001582 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001583 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001584 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001585 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001586 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001587 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001588 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001589 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1590 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001591 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001592 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001593 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001594 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001595 const auto frameRate = getFrameRateForLayerTree();
1596 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1597 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001598 ftl::enum_string(frameRate.type).c_str(),
1599 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001600 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001601 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001602 }
Dan Stozae22aec72016-08-01 13:20:59 -07001603
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001604 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1605 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1606
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001607 result.append(kDumpTableRowLength, '-');
1608 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001609}
Dan Stozae22aec72016-08-01 13:20:59 -07001610
Yiwei Zhang5434a782018-12-05 18:06:32 -08001611void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001612 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001613}
1614
Svetoslavd85084b2014-03-20 10:28:31 -07001615void Layer::clearFrameStats() {
1616 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001617}
1618
Jamie Gennis6547ff42013-07-16 20:12:42 -07001619void Layer::logFrameStats() {
1620 mFrameTracker.logAndResetStats(mName);
1621}
1622
Svetoslavd85084b2014-03-20 10:28:31 -07001623void Layer::getFrameStats(FrameStats* outStats) const {
1624 mFrameTracker.getStats(outStats);
1625}
1626
Vishnu Nair76554eb2022-12-09 03:38:36 +00001627void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1628 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
1629 StringAppendF(&result, "Layer %s%s pid:%d uid:%d\n", getName().c_str(), hasBuffer.c_str(),
Vishnu Naircb8be502022-10-12 19:03:23 +00001630 mOwnerPid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001631}
1632
Brian Anderson5ea5e592016-12-01 16:54:33 -08001633void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001634 const int32_t layerId = getSequence();
1635 mFlinger->mTimeStats->onDestroy(layerId);
1636 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001637}
1638
Chia-I Wu98f1c102017-05-30 14:54:08 -07001639size_t Layer::getChildrenCount() const {
1640 size_t count = 0;
1641 for (const sp<Layer>& child : mCurrentChildren) {
1642 count += 1 + child->getChildrenCount();
1643 }
1644 return count;
1645}
1646
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001647void Layer::setGameModeForTree(GameMode gameMode) {
1648 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001649 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1650 gameMode =
1651 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001652 }
1653 setGameMode(gameMode);
1654 for (const sp<Layer>& child : mCurrentChildren) {
1655 child->setGameModeForTree(gameMode);
1656 }
1657}
1658
Robert Carr1f0a16a2016-10-24 16:27:39 -07001659void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001660 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001661 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001662
Robert Carr1f0a16a2016-10-24 16:27:39 -07001663 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001664 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001665 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001666 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001667}
1668
1669ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001670 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001671 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001672
Robert Carr1323c952019-01-28 18:13:27 -08001673 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001674 const auto removeResult = mCurrentChildren.remove(layer);
1675
1676 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001677 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001678 layer->updateTreeHasFrameRateVote();
1679
1680 return removeResult;
1681}
1682
Robert Carr15eae092018-03-23 13:43:53 -07001683void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001684 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001685 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001686 const float parentShadowRadius =
1687 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001688 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001689 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001690 }
1691}
1692
chaviwf1961f72017-09-18 16:41:07 -07001693bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001694 sp<Layer> newParent;
1695 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001696 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001697 if (newParent == nullptr) {
1698 ALOGE("Unable to promote Layer handle");
1699 return false;
1700 }
1701 if (newParent == this) {
1702 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1703 return false;
1704 }
1705 }
1706
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001707 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001708 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001709 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001710 }
1711
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001712 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001713 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001714 if (!newParent->isRemovedFromCurrentState()) {
1715 addToCurrentState();
1716 } else {
1717 onRemovedFromCurrentState();
1718 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001719 } else {
1720 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001721 }
1722
chaviw06178942017-07-27 10:25:59 -07001723 return true;
1724}
1725
Peiyong Lind3788632018-09-18 16:01:31 -07001726bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001727 static const mat4 identityMatrix = mat4();
1728
Robert Carr6a160312021-05-17 12:08:20 -07001729 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001730 return false;
1731 }
Robert Carr6a160312021-05-17 12:08:20 -07001732 ++mDrawingState.sequence;
1733 mDrawingState.colorTransform = matrix;
1734 mDrawingState.hasColorTransform = matrix != identityMatrix;
1735 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001736 setTransactionFlags(eTransactionNeeded);
1737 return true;
1738}
1739
chaviwf66724d2018-11-28 16:35:21 -08001740mat4 Layer::getColorTransform() const {
1741 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001742 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001743 colorTransform = parent->getColorTransform() * colorTransform;
1744 }
1745 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001746}
1747
1748bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001749 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001750 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001751 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1752 }
1753 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001754}
1755
Chia-I Wu11481472018-05-04 10:43:19 -07001756bool Layer::isLegacyDataSpace() const {
1757 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001758 return !(getDataSpace() &
1759 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1760 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001761}
1762
Robert Carr1f0a16a2016-10-24 16:27:39 -07001763void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001764 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001765}
1766
Robert Carr6a160312021-05-17 12:08:20 -07001767int32_t Layer::getZ(LayerVector::StateSet) const {
1768 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001769}
1770
Robert Carr1c5481e2019-07-01 14:42:27 -07001771bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001772 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001773 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001774 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001775}
1776
David Sodman41fdfc92017-11-06 16:09:56 -08001777__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001778 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001779 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1780 "makeTraversalList received invalid stateSet");
1781 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1782 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001783 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001784
Robert Carr29abff82017-12-04 13:51:20 -08001785 if (state.zOrderRelatives.size() == 0) {
1786 *outSkipRelativeZUsers = true;
1787 return children;
1788 }
1789
chaviwfd462612018-05-31 16:11:27 -07001790 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001791 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001792 sp<Layer> strongRelative = weakRelative.promote();
1793 if (strongRelative != nullptr) {
1794 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001795 }
1796 }
1797
Dan Stoza412903f2017-04-27 13:42:17 -07001798 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001799 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001800 continue;
1801 }
Robert Carrdb66e622017-04-10 16:55:57 -07001802 traverse.add(child);
1803 }
1804
1805 return traverse;
1806}
1807
Robert Carr1f0a16a2016-10-24 16:27:39 -07001808/**
Robert Carrdb66e622017-04-10 16:55:57 -07001809 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001810 */
Dan Stoza412903f2017-04-27 13:42:17 -07001811void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001812 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1813 // produce a new list for traversing, including our relatives, and not including our children
1814 // who are relatives of another surface. In the case that there are no relative Z,
1815 // makeTraversalList returns our children directly to avoid significant overhead.
1816 // However in this case we need to take the responsibility for filtering children which
1817 // are relatives of another surface here.
1818 bool skipRelativeZUsers = false;
1819 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001820
Robert Carr1f0a16a2016-10-24 16:27:39 -07001821 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001822 for (; i < list.size(); i++) {
1823 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001824 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1825 continue;
1826 }
1827
chaviw301b1d82019-11-06 13:15:09 -08001828 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001829 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001830 }
Dan Stoza412903f2017-04-27 13:42:17 -07001831 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001832 }
Robert Carr29abff82017-12-04 13:51:20 -08001833
Dan Stoza412903f2017-04-27 13:42:17 -07001834 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001835 for (; i < list.size(); i++) {
1836 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001837
Robert Carr29abff82017-12-04 13:51:20 -08001838 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1839 continue;
1840 }
Dan Stoza412903f2017-04-27 13:42:17 -07001841 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001842 }
1843}
1844
1845/**
Robert Carrdb66e622017-04-10 16:55:57 -07001846 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001847 */
Dan Stoza412903f2017-04-27 13:42:17 -07001848void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1849 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001850 // See traverseInZOrder for documentation.
1851 bool skipRelativeZUsers = false;
1852 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001853
Robert Carr1f0a16a2016-10-24 16:27:39 -07001854 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001855 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001856 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001857
1858 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1859 continue;
1860 }
1861
chaviw301b1d82019-11-06 13:15:09 -08001862 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001863 break;
1864 }
Dan Stoza412903f2017-04-27 13:42:17 -07001865 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001866 }
Dan Stoza412903f2017-04-27 13:42:17 -07001867 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001868 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001869 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001870
1871 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1872 continue;
1873 }
1874
Dan Stoza412903f2017-04-27 13:42:17 -07001875 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001876 }
1877}
1878
Edgar Arriaga844fa672020-01-16 14:21:42 -08001879void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1880 visitor(this);
1881 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001882 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001883 for (const sp<Layer>& child : children) {
1884 child->traverse(state, visitor);
1885 }
1886}
1887
chaviw4b129c22018-04-09 16:19:43 -07001888LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1889 const std::vector<Layer*>& layersInTree) {
1890 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1891 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001892 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1893 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001894 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001895
chaviwfd462612018-05-31 16:11:27 -07001896 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001897 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1898 sp<Layer> strongRelative = weakRelative.promote();
1899 // Only add relative layers that are also descendents of the top most parent of the tree.
1900 // If a relative layer is not a descendent, then it should be ignored.
1901 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1902 traverse.add(strongRelative);
1903 }
1904 }
1905
1906 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001907 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001908 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1909 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1910 // the child here since it won't be added later as a relative.
1911 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1912 childState.zOrderRelativeOf.promote().get())) {
1913 continue;
1914 }
1915 traverse.add(child);
1916 }
1917
1918 return traverse;
1919}
1920
1921void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1922 LayerVector::StateSet stateSet,
1923 const LayerVector::Visitor& visitor) {
1924 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001925
1926 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001927 for (; i < list.size(); i++) {
1928 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001929 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001930 break;
1931 }
chaviw4b129c22018-04-09 16:19:43 -07001932 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001933 }
chaviw4b129c22018-04-09 16:19:43 -07001934
chaviwa76b2712017-09-20 12:02:26 -07001935 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001936 for (; i < list.size(); i++) {
1937 const auto& relative = list[i];
1938 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001939 }
1940}
1941
chaviw4b129c22018-04-09 16:19:43 -07001942std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1943 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1944 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1945
1946 std::vector<Layer*> layersInTree = {this};
1947 for (size_t i = 0; i < children.size(); i++) {
1948 const auto& child = children[i];
1949 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1950 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1951 }
1952
1953 return layersInTree;
1954}
1955
1956void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1957 const LayerVector::Visitor& visitor) {
1958 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1959 std::sort(layersInTree.begin(), layersInTree.end());
1960 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1961}
1962
Peiyong Linefefaac2018-08-17 12:27:51 -07001963ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001964 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001965}
1966
Garfield Tan2c1782c2022-02-16 15:25:05 -08001967bool Layer::isTransformValid() const {
1968 float transformDet = getTransform().det();
1969 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1970}
1971
chaviw13fdc492017-06-27 12:40:18 -07001972half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001973 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001974
chaviw13fdc492017-06-27 12:40:18 -07001975 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1976 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07001977}
Robert Carr6452f122017-03-21 10:41:29 -07001978
Vishnu Nair6213bd92020-05-08 17:42:25 -07001979ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07001980 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001981 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
1982 return fixedTransformHint;
1983 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001984 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07001985 if (!p) return fixedTransformHint;
1986 return p->getFixedTransformHint();
1987}
1988
chaviw13fdc492017-06-27 12:40:18 -07001989half4 Layer::getColor() const {
1990 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001991 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07001992}
Robert Carr6452f122017-03-21 10:41:29 -07001993
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001994int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00001995 if (getDrawingState().backgroundBlurRadius == 0) {
1996 return 0;
1997 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01001998
Vishnu Nair29810f72022-07-01 16:38:41 +00001999 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002000 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2001 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002002}
2003
Galia Peychevae0acf382021-04-12 21:22:34 +02002004const std::vector<BlurRegion> Layer::getBlurRegions() const {
2005 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002006 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002007 for (auto& region : regionsCopy) {
2008 region.alpha = region.alpha * layerAlpha;
2009 }
2010 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002011}
2012
Vishnu Naire14c6b32022-08-06 04:20:15 +00002013RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002014 // Get parent settings
2015 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002016 const auto& parent = mDrawingParent.promote();
2017 if (parent != nullptr) {
2018 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002019 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002020 ui::Transform t = getActiveTransform(getDrawingState());
2021 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002022 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002023 parentSettings.radius.x *= t.getScaleX();
2024 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002025 }
2026 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002027
2028 // Get layer settings
2029 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002030 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002031 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002032 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002033
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002034 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002035 // If the parent and the layer have rounded corner settings, use the parent settings if the
2036 // parent crop is entirely inside the layer crop.
2037 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2038 if (parentSettings.cropRect.left > layerCropRect.left &&
2039 parentSettings.cropRect.top > layerCropRect.top &&
2040 parentSettings.cropRect.right < layerCropRect.right &&
2041 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2042 return parentSettings;
2043 } else {
2044 return layerSettings;
2045 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002046 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002047 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002048 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002049 return parentSettings;
2050 }
2051 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002052}
2053
Robert Carr88b85e12022-03-21 15:47:35 -07002054bool Layer::findInHierarchy(const sp<Layer>& l) {
2055 if (l == this) {
2056 return true;
2057 }
2058 for (auto& child : mDrawingChildren) {
2059 if (child->findInHierarchy(l)) {
2060 return true;
2061 }
2062 }
2063 return false;
2064}
2065
Robert Carr1f0a16a2016-10-24 16:27:39 -07002066void Layer::commitChildList() {
2067 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2068 const auto& child = mCurrentChildren[i];
2069 child->commitChildList();
2070 }
2071 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002072 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002073 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2074 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2075 if (zOrderRelativeOf == nullptr) return;
2076 if (findInHierarchy(zOrderRelativeOf)) {
2077 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2078 zOrderRelativeOf->mName.c_str());
2079 ALOGE("Severing rel Z loop, potentially dangerous");
2080 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002081 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002082 }
2083 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002084}
2085
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002086
chaviw3277faf2021-05-19 16:45:23 -05002087void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002088 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002089 mDrawingState.touchableRegionCrop =
2090 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002091 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002092 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002093 setTransactionFlags(eTransactionNeeded);
2094}
2095
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002096LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002097 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002098 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002099 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2100
Vishnu Nair00b90132021-11-05 14:03:40 -07002101 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002102 writeCompositionStateToProto(layerProto);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002103 }
2104
chaviw08f3cb22020-01-13 13:17:21 -08002105 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002106 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002107 }
chaviw6d89e2d2020-01-14 14:42:01 -08002108
2109 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002110}
2111
Vishnu Nairea6ff812023-02-27 17:41:39 +00002112void Layer::writeCompositionStateToProto(LayerProto* layerProto) {
2113 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2114
2115 // Only populate for the primary display.
2116 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
2117 const auto compositionType = getCompositionType(*display);
2118 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
2119 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2120 [&]() { return layerProto->mutable_visible_region(); });
2121 }
2122}
2123
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002124void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002125 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002126 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002127 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002128 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002129 [&]() { return layerInfo->mutable_active_buffer(); });
2130 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2131 layerInfo->mutable_buffer_transform());
2132 }
2133 layerInfo->set_invalidate(contentDirty);
2134 layerInfo->set_is_protected(isProtected());
2135 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2136 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002137 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002138 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002139 layerInfo->set_corner_radius(
2140 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002141 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2142 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2143 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2144 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2145 [&]() { return layerInfo->mutable_position(); });
2146 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002147 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2148 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002149
Vishnu Nair00b90132021-11-05 14:03:40 -07002150 if (hasColorTransform()) {
2151 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002152 }
2153
Vishnu Nair60db8c02020-04-02 11:55:16 -07002154 LayerProtoHelper::writeToProto(mSourceBounds,
2155 [&]() { return layerInfo->mutable_source_bounds(); });
2156 LayerProtoHelper::writeToProto(mScreenBounds,
2157 [&]() { return layerInfo->mutable_screen_bounds(); });
2158 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2159 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2160 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002161}
2162
2163void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002164 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002165 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2166 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002167 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002168
chaviw766c9c52021-02-10 17:36:47 -08002169 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002170
Vishnu Nair00b90132021-11-05 14:03:40 -07002171 layerInfo->set_id(sequence);
2172 layerInfo->set_name(getName().c_str());
2173 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002174
Vishnu Nair00b90132021-11-05 14:03:40 -07002175 for (const auto& child : children) {
2176 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002177 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002178
Vishnu Nair00b90132021-11-05 14:03:40 -07002179 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2180 sp<Layer> strongRelative = weakRelative.promote();
2181 if (strongRelative != nullptr) {
2182 layerInfo->add_relatives(strongRelative->sequence);
2183 }
2184 }
2185
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002186 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002187 [&]() { return layerInfo->mutable_transparent_region(); });
2188
2189 layerInfo->set_layer_stack(getLayerStack().id);
2190 layerInfo->set_z(state.z);
2191
2192 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2193 return layerInfo->mutable_requested_position();
2194 });
2195
Vishnu Nair00b90132021-11-05 14:03:40 -07002196 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2197
2198 layerInfo->set_is_opaque(isOpaque(state));
2199
2200 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2201 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2202 LayerProtoHelper::writeToProto(state.color,
2203 [&]() { return layerInfo->mutable_requested_color(); });
2204 layerInfo->set_flags(state.flags);
2205
2206 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2207 layerInfo->mutable_requested_transform());
2208
2209 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2210 if (parent != nullptr) {
2211 layerInfo->set_parent(parent->sequence);
2212 } else {
2213 layerInfo->set_parent(-1);
2214 }
2215
2216 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2217 if (zOrderRelativeOf != nullptr) {
2218 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2219 } else {
2220 layerInfo->set_z_order_relative_of(-1);
2221 }
2222
2223 layerInfo->set_is_relative_of(state.isRelativeOf);
2224
2225 layerInfo->set_owner_uid(mOwnerUid);
2226
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002227 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002228 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002229 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002230 info = fillInputInfo(
2231 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002232 } else {
2233 info = state.inputInfo;
2234 }
2235
2236 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002237 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002238 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002239
Vishnu Nair00b90132021-11-05 14:03:40 -07002240 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002241 auto protoMap = layerInfo->mutable_metadata();
2242 for (const auto& entry : state.metadata.mMap) {
2243 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2244 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002245 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002246
2247 LayerProtoHelper::writeToProto(state.destinationFrame,
2248 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002249}
2250
Robert Carr2e102c92018-10-23 12:11:15 -07002251bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002252 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002253}
2254
Prabir Pradhan33da9462022-06-14 14:55:57 +00002255// Applies the given transform to the region, while protecting against overflows caused by any
2256// offsets. If applying the offset in the transform to any of the Rects in the region would result
2257// in an overflow, they are not added to the output Region.
2258static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2259 const std::string& debugWindowName) {
2260 // Round the translation using the same rounding strategy used by ui::Transform.
2261 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2262 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2263
2264 ui::Transform transformWithoutOffset = t;
2265 transformWithoutOffset.set(0.f, 0.f);
2266
2267 const Region transformed = transformWithoutOffset.transform(r);
2268
2269 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2270 Region ret;
2271 for (const auto& rect : transformed) {
2272 Rect newRect;
2273 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2274 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2275 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2276 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2277 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2278 debugWindowName.c_str());
2279 continue;
2280 }
2281 ret.orSelf(newRect);
2282 }
2283 return ret;
2284}
2285
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002286void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
2287 Rect tmpBounds = getInputBounds();
2288 if (!tmpBounds.isValid()) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002289 info.touchableRegion.clear();
2290 // A layer could have invalid input bounds and still expect to receive touch input if it has
2291 // replaceTouchableRegionWithCrop. For that case, the input transform needs to be calculated
2292 // correctly to determine the coordinate space for input events. Use an empty rect so that
2293 // the layer will receive input in its own layer space.
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002294 tmpBounds = Rect::EMPTY_RECT;
chaviw7e72caf2020-12-02 16:50:43 -08002295 }
2296
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002297 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2298 // frame and transform used for the layer, which determines the bounds and the coordinate space
2299 // within which the layer will receive input.
2300 //
2301 // The coordinate space within which each of the bounds are specified is explicitly documented
2302 // in the variable name. For example "inputBoundsInLayer" is specified in layer space. A
2303 // Transform converts one coordinate space to another, which is apparent in its naming. For
2304 // example, "layerToDisplay" transforms layer space to display space.
2305 //
2306 // Coordinate space definitions:
2307 // - display: The display device's coordinate space. Correlates to pixels on the display.
2308 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2309 // - layer: The coordinate space of this layer.
2310 // - input: The coordinate space in which this layer will receive input events. This could be
2311 // different than layer space if a surfaceInset is used, which changes the origin
2312 // of the input space.
2313 const FloatRect inputBoundsInLayer = tmpBounds.toFloatRect();
chaviw7e72caf2020-12-02 16:50:43 -08002314
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002315 // Clamp surface inset to the input bounds.
2316 const auto surfaceInset = static_cast<float>(info.surfaceInset);
2317 const float xSurfaceInset =
2318 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getWidth() / 2.f));
2319 const float ySurfaceInset =
2320 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getHeight() / 2.f));
chaviw1ff3d1e2020-07-01 15:53:47 -07002321
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002322 // Apply the insets to the input bounds.
2323 const FloatRect insetBoundsInLayer(inputBoundsInLayer.left + xSurfaceInset,
2324 inputBoundsInLayer.top + ySurfaceInset,
2325 inputBoundsInLayer.right - xSurfaceInset,
2326 inputBoundsInLayer.bottom - ySurfaceInset);
Ady Abraham282f1d72019-07-24 18:05:56 -07002327
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002328 // Crop the input bounds to ensure it is within the parent's bounds.
2329 const FloatRect croppedInsetBoundsInLayer = mBounds.intersect(insetBoundsInLayer);
Ady Abraham282f1d72019-07-24 18:05:56 -07002330
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002331 const ui::Transform layerToScreen = getInputTransform();
2332 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
Vishnu Nair8033a492018-12-05 07:27:23 -08002333
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002334 const Rect roundedFrameInDisplay{layerToDisplay.transform(croppedInsetBoundsInLayer)};
2335 info.frameLeft = roundedFrameInDisplay.left;
2336 info.frameTop = roundedFrameInDisplay.top;
2337 info.frameRight = roundedFrameInDisplay.right;
2338 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002339
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002340 ui::Transform inputToLayer;
2341 inputToLayer.set(insetBoundsInLayer.left, insetBoundsInLayer.top);
2342 const ui::Transform inputToDisplay = layerToDisplay * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002343
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002344 // InputDispatcher expects a display-to-input transform.
2345 info.transform = inputToDisplay.inverse();
2346
2347 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002348 info.touchableRegion =
2349 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002350}
2351
chaviw3277faf2021-05-19 16:45:23 -05002352void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002353 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002354 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002355 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002356 }
2357 if (p != nullptr) {
2358 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2359 }
2360}
2361
Vishnu Naira066d902021-09-13 18:40:17 -07002362gui::DropInputMode Layer::getDropInputMode() const {
2363 gui::DropInputMode mode = mDrawingState.dropInputMode;
2364 if (mode == gui::DropInputMode::ALL) {
2365 return mode;
2366 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002367 sp<Layer> parent = mDrawingParent.promote();
2368 if (parent) {
2369 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002370 if (parentMode != gui::DropInputMode::NONE) {
2371 return parentMode;
2372 }
2373 }
2374 return mode;
2375}
2376
2377void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002378 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002379 return;
2380 }
2381
2382 // Check if we need to drop input unconditionally
2383 gui::DropInputMode dropInputMode = getDropInputMode();
2384 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002385 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002386 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2387 return;
2388 }
2389
2390 // Check if we need to check if the window is obscured by parent
2391 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2392 return;
2393 }
2394
2395 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002396 sp<Layer> parent = mDrawingParent.promote();
2397 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002398 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002399 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2400 static_cast<float>(getAlpha()));
2401 }
2402
2403 // Check if the parent has cropped the buffer
2404 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2405 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002406 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002407 return;
2408 }
2409
2410 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2411 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2412 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2413 // match then the layer has not been cropped by its parents.
2414 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2415 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2416
2417 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002418 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002419 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2420 getDebugName());
2421 } else {
2422 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2423 // input if the window is obscured. This check should be done in surfaceflinger but the
2424 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2425 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002426 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002427 }
2428}
2429
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002430WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002431 if (!hasInputInfo()) {
2432 mDrawingState.inputInfo.name = getName();
2433 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2434 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002435 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002436 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002437 }
2438
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002439 const ui::Transform& displayTransform =
2440 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2441
chaviw3277faf2021-05-19 16:45:23 -05002442 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002443 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002444 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002445
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002446 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002447
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002448 if (displayArgs.transform == nullptr) {
2449 // Do not let the window receive touches if it is not associated with a valid display
2450 // transform. We still allow the window to receive keys and prevent ANRs.
2451 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2452 }
2453
Robert Carr5dc426e2020-06-10 14:29:14 -07002454 // For compatibility reasons we let layers which can receive input
2455 // receive input before they have actually submitted a buffer. Because
2456 // of this we use canReceiveInput instead of isVisible to check the
2457 // policy-visibility, ignoring the buffer state. However for layers with
2458 // hasInputInfo()==false we can use the real visibility state.
2459 // We are just using these layers for occlusion detection in
2460 // InputDispatcher, and obviously if they aren't visible they can't occlude
2461 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002462 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2463 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2464
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002465 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002466 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002467 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002468
Vishnu Nair16a938f2021-09-24 07:14:54 -07002469 // If the window will be blacked out on a display because the display does not have the secure
2470 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002471 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002472 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002473 }
2474
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002475 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2476 if (info.replaceTouchableRegionWithCrop) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002477 const Rect bounds(cropLayer ? cropLayer->mScreenBounds : mScreenBounds);
2478 info.touchableRegion = Region(displayTransform.transform(bounds));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002479 } else if (cropLayer != nullptr) {
[1;3C2b9fc252021-02-04 16:16:50 -08002480 info.touchableRegion = info.touchableRegion.intersect(
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002481 displayTransform.transform(Rect{cropLayer->mScreenBounds}));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002482 }
2483
Winson Chunga30f7c92021-06-29 15:42:56 -07002484 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2485 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002486 if (isTrustedOverlay()) {
2487 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2488 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002489
chaviwaf87b3e2019-10-01 16:59:28 -07002490 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2491 // touches from going outside the cloned area.
2492 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002493 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002494 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2495 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002496 info.touchableRegion = info.touchableRegion.intersect(rect);
2497 }
2498 }
2499
Robert Carr720e5062018-07-30 17:45:14 -07002500 return info;
2501}
2502
chaviwaf87b3e2019-10-01 16:59:28 -07002503sp<Layer> Layer::getClonedRoot() {
2504 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002505 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002506 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002507 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002508 return nullptr;
2509 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002510 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002511}
2512
Robert Carredd13602020-04-13 17:24:34 -07002513bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002514 return mDrawingState.inputInfo.token != nullptr ||
2515 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002516}
2517
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002518compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002519 const DisplayDevice* display) const {
2520 if (!display) return nullptr;
Vishnu Naird47bcee2023-02-24 18:08:51 +00002521 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2522 return display->getCompositionDisplay()->getOutputLayerForLayer(
2523 getCompositionEngineLayerFE());
2524 }
2525 sp<LayerFE> layerFE;
2526 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2527 for (auto& [p, layer] : mLayerFEs) {
2528 if (p == path) {
2529 layerFE = layer;
2530 }
2531 }
2532
2533 if (!layerFE) return nullptr;
2534 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002535}
2536
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002537Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2538 const auto outputLayer = findOutputLayerForDisplay(display);
2539 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002540}
2541
chaviwb4c6e582019-08-16 14:35:07 -07002542void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002543 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002544 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002545 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2546 mPotentialCursor = clonedFrom->mPotentialCursor;
2547 mProtectedByApp = clonedFrom->mProtectedByApp;
2548 updateCloneBufferInfo();
2549}
2550
2551void Layer::updateCloneBufferInfo() {
2552 if (!isClone() || !isClonedFromAlive()) {
2553 return;
2554 }
2555
2556 sp<Layer> clonedFrom = getClonedFrom();
2557 mBufferInfo = clonedFrom->mBufferInfo;
2558 mSidebandStream = clonedFrom->mSidebandStream;
2559 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2560 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2561 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2562
2563 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2564 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2565 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2566 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2567 // the cloned drawingState again.
2568 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2569 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2570 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2571 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2572
2573 cloneDrawingState(clonedFrom.get());
2574
2575 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2576 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2577 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2578 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002579}
chaviw74b03172019-08-19 11:09:03 -07002580
2581void Layer::updateMirrorInfo() {
2582 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2583 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2584 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2585 // that case, we want to delete the reference to the clone since we want it to get
2586 // destroyed. The root, this layer, will still be around since the client can continue
2587 // to hold a reference, but no cloned layers will be displayed.
2588 mClonedChild = nullptr;
2589 return;
2590 }
2591
2592 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2593 // If the real layer exists and is in current state, add the clone as a child of the root.
2594 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2595 // copied to drawingState for the root layer. So the clonedChild is always removed from
2596 // drawingState and then needs to be added back each traversal.
2597 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2598 addChildToDrawing(mClonedChild);
2599 }
2600
2601 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002602 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002603 mClonedChild->updateClonedRelatives(clonedLayersMap);
2604}
2605
2606void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2607 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2608 // to the clone. If the real layer is no longer alive, continue traversing the children
2609 // since we may be able to pull out other children that are still alive.
2610 if (isClonedFromAlive()) {
2611 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002612 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002613 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002614 }
2615
2616 // The clone layer may have children in drawingState since they may have been created and
2617 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2618 // that already exist, since we can just re-use them.
2619 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2620 // not updated in the regular traversal. They are skipped since the root will lose the
2621 // reference to them when it copies its currentChildren to drawing.
2622 for (sp<Layer>& child : mDrawingChildren) {
2623 child->updateClonedDrawingState(clonedLayersMap);
2624 }
2625}
2626
2627void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2628 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2629 mDrawingChildren.clear();
2630
2631 if (!isClonedFromAlive()) {
2632 return;
2633 }
2634
2635 sp<Layer> clonedFrom = getClonedFrom();
2636 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2637 if (child == mirrorRoot) {
2638 // This is to avoid cyclical mirroring.
2639 continue;
2640 }
2641 sp<Layer> clonedChild = clonedLayersMap[child];
2642 if (clonedChild == nullptr) {
2643 clonedChild = child->createClone();
2644 clonedLayersMap[child] = clonedChild;
2645 }
2646 addChildToDrawing(clonedChild);
2647 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2648 }
2649}
2650
chaviwaf87b3e2019-10-01 16:59:28 -07002651void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2652 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2653 if (cropLayer != nullptr) {
2654 if (clonedLayersMap.count(cropLayer) == 0) {
2655 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2656 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002657 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002658 } else {
2659 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2660 mDrawingState.touchableRegionCrop = clonedCropLayer;
2661 }
2662 }
2663 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2664 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002665 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002666}
2667
2668void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002669 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002670 mDrawingState.zOrderRelatives.clear();
2671
2672 if (!isClonedFromAlive()) {
2673 return;
2674 }
2675
chaviwaf87b3e2019-10-01 16:59:28 -07002676 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002677 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002678 const sp<Layer>& relative = relativeWeak.promote();
2679 if (clonedLayersMap.count(relative) > 0) {
2680 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002681 mDrawingState.zOrderRelatives.add(clonedRelative);
2682 }
2683 }
2684
2685 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2686 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2687 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2688 // still traverse the children, but the layer with the missing relativeOf will not be shown
2689 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002690 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2691 if (clonedLayersMap.count(relativeOf) > 0) {
2692 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002693 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2694 }
2695
chaviwaf87b3e2019-10-01 16:59:28 -07002696 updateClonedInputInfo(clonedLayersMap);
2697
chaviw74b03172019-08-19 11:09:03 -07002698 for (sp<Layer>& child : mDrawingChildren) {
2699 child->updateClonedRelatives(clonedLayersMap);
2700 }
2701}
2702
2703void Layer::addChildToDrawing(const sp<Layer>& layer) {
2704 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002705 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002706}
2707
Steven Thomas62a4cf82020-01-31 12:04:03 -08002708Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2709 switch (compatibility) {
2710 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2711 return FrameRateCompatibility::Default;
2712 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2713 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002714 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2715 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002716 case ANATIVEWINDOW_FRAME_RATE_MIN:
2717 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002718 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2719 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002720 default:
2721 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2722 return FrameRateCompatibility::Default;
2723 }
2724}
2725
Marin Shalamanovc5986772021-03-16 16:09:49 +01002726scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2727 switch (strategy) {
2728 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2729 return Seamlessness::OnlySeamless;
2730 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2731 return Seamlessness::SeamedAndSeamless;
2732 default:
2733 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2734 return Seamlessness::Default;
2735 }
2736}
2737
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002738bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002739 const State& s(mDrawingState);
2740 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2741 return true;
2742 }
2743
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002744 sp<Layer> parent = mDrawingParent.promote();
2745 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002746}
2747
Robert Carr6a0382d2021-07-01 15:57:17 -07002748void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2749 mClonedChild = clonedChild;
2750 mHadClonedChild = true;
2751 mFlinger->mNumClones++;
2752}
2753
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002754bool Layer::setDropInputMode(gui::DropInputMode mode) {
2755 if (mDrawingState.dropInputMode == mode) {
2756 return false;
2757 }
2758 mDrawingState.dropInputMode = mode;
2759 return true;
2760}
2761
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002762void Layer::cloneDrawingState(const Layer* from) {
2763 mDrawingState = from->mDrawingState;
2764 // Skip callback info since they are not applicable for cloned layers.
2765 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002766 // TODO (b/238781169) currently broken for mirror layers because we do not
2767 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002768 mDrawingState.callbackHandles = {};
2769}
2770
Patrick Williamsbb25f802022-08-30 23:02:34 +00002771void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2772 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002773 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002774 if (!listener) {
2775 return;
2776 }
2777 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002778 uint32_t currentMaxAcquiredBufferCount =
2779 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002780 listener->onReleaseBuffer({buffer->getId(), framenumber},
2781 releaseFence ? releaseFence : Fence::NO_FENCE,
2782 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002783}
2784
2785void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2786 // If we are displayed on multiple displays in a single composition cycle then we would
2787 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2788 // For example we can only use it if all the displays are client comp, and we need
2789 // to merge all the client comp fences. We could do this, but for now we just
2790 // disable the optimization when a layer is composed on multiple displays.
2791 if (mClearClientCompositionFenceOnLayerDisplayed) {
2792 mLastClientCompositionFence = nullptr;
2793 } else {
2794 mClearClientCompositionFenceOnLayerDisplayed = true;
2795 }
2796
2797 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2798 // buffer that was presented on this layer. The first transaction that came in this frame that
2799 // replaced the previous buffer on this layer needs this release fence, because the fence will
2800 // let the client know when that previous buffer is removed from the screen.
2801 //
2802 // Every other transaction on this layer does not need a release fence because no other
2803 // Transactions that were set on this layer this frame are going to have their preceding buffer
2804 // removed from the display this frame.
2805 //
2806 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2807 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2808 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2809 // the previous buffer will be released this frame. The third transaction also contains a
2810 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2811 // transaction will now no longer be presented so it is released immediately and the third
2812 // transaction doesn't need a previous release fence.
2813 sp<CallbackHandle> ch;
2814 for (auto& handle : mDrawingState.callbackHandles) {
2815 if (handle->releasePreviousBuffer &&
2816 mDrawingState.releaseBufferEndpoint == handle->listener) {
2817 ch = handle;
2818 break;
2819 }
2820 }
2821
2822 // Prevent tracing the same release multiple times.
2823 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2824 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2825 }
2826
2827 if (ch != nullptr) {
2828 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2829 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2830 ch->name = mName;
2831 }
2832}
2833
2834void Layer::onSurfaceFrameCreated(
2835 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2836 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2837 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2838 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2839 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002840 if (hasBufferOrSidebandStreamInDrawing()) {
2841 // Only log for layers with a buffer, since we expect the jank data to be drained for
2842 // these, while there may be no jank listeners for bufferless layers.
2843 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2844 mName.c_str());
2845 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2846 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2847 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002848 mPendingJankClassifications.pop_front();
2849 }
2850 mPendingJankClassifications.emplace_back(surfaceFrame);
2851}
2852
2853void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2854 for (const auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair71fcf912022-10-18 09:14:20 -07002855 handle->transformHint = mSkipReportingTransformHint
2856 ? std::nullopt
2857 : std::make_optional<uint32_t>(mTransformHint);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002858 handle->dequeueReadyTime = dequeueReadyTime;
2859 handle->currentMaxAcquiredBufferCount =
2860 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2861 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2862 handle->previousReleaseCallbackId.framenumber);
2863 }
2864
2865 for (auto& handle : mDrawingState.callbackHandles) {
2866 if (handle->releasePreviousBuffer &&
2867 mDrawingState.releaseBufferEndpoint == handle->listener) {
2868 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2869 break;
2870 }
2871 }
2872
2873 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002874 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002875 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2876 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002877 mDrawingState.callbackHandles = {};
2878}
2879
2880bool Layer::willPresentCurrentTransaction() const {
2881 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2882 return (getSidebandStreamChanged() || getAutoRefresh() ||
2883 (mDrawingState.modified &&
2884 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2885}
2886
2887bool Layer::setTransform(uint32_t transform) {
2888 if (mDrawingState.bufferTransform == transform) return false;
2889 mDrawingState.bufferTransform = transform;
2890 mDrawingState.modified = true;
2891 setTransactionFlags(eTransactionNeeded);
2892 return true;
2893}
2894
2895bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2896 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2897 mDrawingState.sequence++;
2898 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2899 mDrawingState.modified = true;
2900 setTransactionFlags(eTransactionNeeded);
2901 return true;
2902}
2903
2904bool Layer::setBufferCrop(const Rect& bufferCrop) {
2905 if (mDrawingState.bufferCrop == bufferCrop) return false;
2906
2907 mDrawingState.sequence++;
2908 mDrawingState.bufferCrop = bufferCrop;
2909
2910 mDrawingState.modified = true;
2911 setTransactionFlags(eTransactionNeeded);
2912 return true;
2913}
2914
2915bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2916 if (mDrawingState.destinationFrame == destinationFrame) return false;
2917
2918 mDrawingState.sequence++;
2919 mDrawingState.destinationFrame = destinationFrame;
2920
2921 mDrawingState.modified = true;
2922 setTransactionFlags(eTransactionNeeded);
2923 return true;
2924}
2925
2926// Translate destination frame into scale and position. If a destination frame is not set, use the
2927// provided scale and position
2928bool Layer::updateGeometry() {
2929 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2930 mDrawingState.destinationFrame.isEmpty()) {
2931 // If destination frame is not set, use the requested transform set via
2932 // Layer::setPosition and Layer::setMatrix.
2933 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2934 }
2935
2936 Rect destRect = mDrawingState.destinationFrame;
2937 int32_t destW = destRect.width();
2938 int32_t destH = destRect.height();
2939 if (destRect.left < 0) {
2940 destRect.left = 0;
2941 destRect.right = destW;
2942 }
2943 if (destRect.top < 0) {
2944 destRect.top = 0;
2945 destRect.bottom = destH;
2946 }
2947
2948 if (!mDrawingState.buffer) {
2949 ui::Transform t;
2950 t.set(destRect.left, destRect.top);
2951 return assignTransform(&mDrawingState.transform, t);
2952 }
2953
2954 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2955 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2956 // Undo any transformations on the buffer.
2957 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2958 std::swap(bufferWidth, bufferHeight);
2959 }
2960 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
2961 if (mDrawingState.transformToDisplayInverse) {
2962 if (invTransform & ui::Transform::ROT_90) {
2963 std::swap(bufferWidth, bufferHeight);
2964 }
2965 }
2966
2967 float sx = destW / static_cast<float>(bufferWidth);
2968 float sy = destH / static_cast<float>(bufferHeight);
2969 ui::Transform t;
2970 t.set(sx, 0, 0, sy);
2971 t.set(destRect.left, destRect.top);
2972 return assignTransform(&mDrawingState.transform, t);
2973}
2974
2975bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
2976 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
2977 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
2978 return false;
2979 }
2980
2981 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
2982
2983 mDrawingState.sequence++;
2984 mDrawingState.modified = true;
2985 setTransactionFlags(eTransactionNeeded);
2986
2987 return true;
2988}
2989
2990bool Layer::setPosition(float x, float y) {
2991 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
2992 return false;
2993 }
2994
2995 mRequestedTransform.set(x, y);
2996
2997 mDrawingState.sequence++;
2998 mDrawingState.modified = true;
2999 setTransactionFlags(eTransactionNeeded);
3000
3001 return true;
3002}
3003
3004bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3005 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3006 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003007 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003008 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003009 if (!buffer) {
3010 return false;
3011 }
3012
3013 const bool frameNumberChanged =
3014 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3015 const uint64_t frameNumber =
3016 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003017 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003018
3019 if (mDrawingState.buffer) {
3020 mReleasePreviousBuffer = true;
3021 if (!mBufferInfo.mBuffer ||
3022 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3023 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3024 // If mDrawingState has a buffer, and we are about to update again
3025 // before swapping to drawing state, then the first buffer will be
3026 // dropped and we should decrement the pending buffer count and
3027 // call any release buffer callbacks if set.
3028 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3029 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003030 mDrawingState.acquireFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003031 decrementPendingBufferCount();
3032 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3033 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3034 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
3035 mDrawingState.bufferSurfaceFrameTX.reset();
3036 }
3037 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3038 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3039 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003040 mLastClientCompositionFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003041 mLastClientCompositionFence = nullptr;
3042 }
3043 }
3044
liulijuneb489f62022-10-17 22:02:14 +08003045 mDrawingState.producerId = bufferData.producerId;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003046 mDrawingState.frameNumber = frameNumber;
3047 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3048 mDrawingState.buffer = std::move(buffer);
3049 mDrawingState.clientCacheId = bufferData.cachedBuffer;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003050 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3051 ? bufferData.acquireFence
3052 : Fence::NO_FENCE;
3053 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3054 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3055 // We latched this buffer unsiganled, so we need to pass the acquire fence
3056 // on the callback instead of just the acquire time, since it's unknown at
3057 // this point.
3058 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3059 } else {
3060 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3061 }
3062
3063 mDrawingState.modified = true;
3064 setTransactionFlags(eTransactionNeeded);
3065
3066 const int32_t layerId = getSequence();
3067 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3068 mOwnerUid, postTime, getGameMode());
3069 mDrawingState.desiredPresentTime = desiredPresentTime;
3070 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3071
3072 const nsecs_t presentTime = [&] {
3073 if (!isAutoTimestamp) return desiredPresentTime;
3074
3075 const auto prediction =
3076 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
3077 if (prediction.has_value()) return prediction->presentTime;
3078
3079 return static_cast<nsecs_t>(0);
3080 }();
3081
3082 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
3083 mFlinger->mScheduler->recordLayerHistory(this, presentTime, LayerUpdateType::Buffer);
3084
3085 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3086
3087 if (dequeueTime && *dequeueTime != 0) {
3088 const uint64_t bufferId = mDrawingState.buffer->getId();
3089 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3090 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3091 FrameTracer::FrameEvent::DEQUEUE);
3092 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3093 FrameTracer::FrameEvent::QUEUE);
3094 }
3095
3096 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3097 return true;
3098}
3099
3100bool Layer::setDataspace(ui::Dataspace dataspace) {
3101 mDrawingState.dataspaceRequested = true;
3102 if (mDrawingState.dataspace == dataspace) return false;
3103 mDrawingState.dataspace = dataspace;
3104 mDrawingState.modified = true;
3105 setTransactionFlags(eTransactionNeeded);
3106 return true;
3107}
3108
John Reck68796592023-01-25 13:47:12 -05003109bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
3110 if (mDrawingState.currentSdrHdrRatio == currentBufferRatio &&
3111 mDrawingState.desiredSdrHdrRatio == desiredRatio)
3112 return false;
3113 mDrawingState.currentSdrHdrRatio = currentBufferRatio;
3114 mDrawingState.desiredSdrHdrRatio = desiredRatio;
3115 mDrawingState.modified = true;
3116 setTransactionFlags(eTransactionNeeded);
3117 return true;
3118}
3119
Alec Mourif4af03e2023-02-11 00:25:24 +00003120bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3121 if (mDrawingState.cachingHint == cachingHint) return false;
3122 mDrawingState.cachingHint = cachingHint;
3123 mDrawingState.modified = true;
3124 setTransactionFlags(eTransactionNeeded);
3125 return true;
3126}
3127
Patrick Williamsbb25f802022-08-30 23:02:34 +00003128bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3129 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3130 mDrawingState.hdrMetadata = hdrMetadata;
3131 mDrawingState.modified = true;
3132 setTransactionFlags(eTransactionNeeded);
3133 return true;
3134}
3135
3136bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
3137 mDrawingState.surfaceDamageRegion = surfaceDamage;
3138 mDrawingState.modified = true;
3139 setTransactionFlags(eTransactionNeeded);
3140 return true;
3141}
3142
3143bool Layer::setApi(int32_t api) {
3144 if (mDrawingState.api == api) return false;
3145 mDrawingState.api = api;
3146 mDrawingState.modified = true;
3147 setTransactionFlags(eTransactionNeeded);
3148 return true;
3149}
3150
3151bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3152 if (mDrawingState.sidebandStream == sidebandStream) return false;
3153
3154 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3155 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3156 } else if (sidebandStream != nullptr) {
3157 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3158 }
3159
3160 mDrawingState.sidebandStream = sidebandStream;
3161 mDrawingState.modified = true;
3162 setTransactionFlags(eTransactionNeeded);
3163 if (!mSidebandStreamChanged.exchange(true)) {
3164 // mSidebandStreamChanged was false
3165 mFlinger->onLayerUpdate();
3166 }
3167 return true;
3168}
3169
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003170bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3171 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003172 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3173 if (handles.empty()) {
3174 mReleasePreviousBuffer = false;
3175 return false;
3176 }
3177
Pascal Muetschard81cef292023-02-06 12:18:52 +01003178 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003179 for (const auto& handle : handles) {
3180 // If this transaction set a buffer on this layer, release its previous buffer
3181 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3182
3183 // If this layer will be presented in this frame
3184 if (willPresent) {
3185 // If this transaction set an acquire fence on this layer, set its acquire time
3186 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3187 handle->frameNumber = mDrawingState.frameNumber;
3188
3189 // Store so latched time and release fence can be set
3190 mDrawingState.callbackHandles.push_back(handle);
3191
3192 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003193 // Queue this handle to be notified below.
3194 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003195 }
3196 }
3197
Pascal Muetschard81cef292023-02-06 12:18:52 +01003198 if (!remainingHandles.empty()) {
3199 // Notify the transaction completed threads these handles are done. These are only the
3200 // handles that were not added to the mDrawingState, which will be notified later.
3201 std::vector<JankData> jankData;
3202 transferAvailableJankData(remainingHandles, jankData);
3203 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3204 }
3205
Patrick Williamsbb25f802022-08-30 23:02:34 +00003206 mReleasePreviousBuffer = false;
3207 mCallbackHandleAcquireTimeOrFence = -1;
3208
3209 return willPresent;
3210}
3211
3212Rect Layer::getBufferSize(const State& /*s*/) const {
3213 // for buffer state layers we use the display frame size as the buffer size.
3214
3215 if (mBufferInfo.mBuffer == nullptr) {
3216 return Rect::INVALID_RECT;
3217 }
3218
3219 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3220 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3221
3222 // Undo any transformations on the buffer and return the result.
3223 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3224 std::swap(bufWidth, bufHeight);
3225 }
3226
3227 if (getTransformToDisplayInverse()) {
3228 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3229 if (invTransform & ui::Transform::ROT_90) {
3230 std::swap(bufWidth, bufHeight);
3231 }
3232 }
3233
3234 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3235}
3236
3237FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3238 if (mBufferInfo.mBuffer == nullptr) {
3239 return parentBounds;
3240 }
3241
3242 return getBufferSize(getDrawingState()).toFloatRect();
3243}
3244
3245bool Layer::fenceHasSignaled() const {
3246 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3247 return true;
3248 }
3249
3250 const bool fenceSignaled =
3251 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3252 if (!fenceSignaled) {
3253 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3254 TimeStats::LatchSkipReason::LateAcquire);
3255 }
3256
3257 return fenceSignaled;
3258}
3259
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003260void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003261 for (const auto& handle : mDrawingState.callbackHandles) {
3262 handle->refreshStartTime = refreshStartTime;
3263 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003264}
3265
3266void Layer::setAutoRefresh(bool autoRefresh) {
3267 mDrawingState.autoRefresh = autoRefresh;
3268}
3269
3270bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3271 // 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 +00003272 auto* snapshot = editLayerSnapshot();
3273 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003274
3275 if (mSidebandStreamChanged.exchange(false)) {
3276 const State& s(getDrawingState());
3277 // mSidebandStreamChanged was true
3278 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003279 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003280 if (mSidebandStream != nullptr) {
3281 setTransactionFlags(eTransactionNeeded);
3282 mFlinger->setTransactionFlags(eTraversalNeeded);
3283 }
3284 recomputeVisibleRegions = true;
3285
3286 return true;
3287 }
3288 return false;
3289}
3290
3291bool Layer::hasFrameUpdate() const {
3292 const State& c(getDrawingState());
3293 return (mDrawingStateModified || mDrawingState.modified) &&
3294 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3295}
3296
Vishnu Naird47bcee2023-02-24 18:08:51 +00003297void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003298 const State& s(getDrawingState());
3299
3300 if (!s.buffer) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003301 if (bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003302 for (auto& handle : mDrawingState.callbackHandles) {
3303 handle->latchTime = latchTime;
3304 }
3305 }
3306 return;
3307 }
3308
3309 for (auto& handle : mDrawingState.callbackHandles) {
3310 if (handle->frameNumber == mDrawingState.frameNumber) {
3311 handle->latchTime = latchTime;
3312 }
3313 }
3314
3315 const int32_t layerId = getSequence();
3316 const uint64_t bufferId = mDrawingState.buffer->getId();
3317 const uint64_t frameNumber = mDrawingState.frameNumber;
3318 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3319 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3320 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3321
3322 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3323 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3324 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3325 FrameTracer::FrameEvent::LATCH);
3326
3327 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3328 if (bufferSurfaceFrame != nullptr &&
3329 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3330 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3331 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3332 // are processing the next state.
3333 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3334 mDrawingState.acquireFenceTime->getSignalTime(),
3335 latchTime);
3336 mDrawingState.bufferSurfaceFrameTX.reset();
3337 }
3338
3339 std::deque<sp<CallbackHandle>> remainingHandles;
3340 mFlinger->getTransactionCallbackInvoker()
3341 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3342 mDrawingState.callbackHandles = remainingHandles;
3343
3344 mDrawingStateModified = false;
3345}
3346
3347void Layer::gatherBufferInfo() {
3348 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3349 decrementPendingBufferCount();
3350 }
3351
3352 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3353 mBufferInfo.mBuffer = mDrawingState.buffer;
3354 mBufferInfo.mFence = mDrawingState.acquireFence;
3355 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3356 mBufferInfo.mPixelFormat =
3357 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3358 mBufferInfo.mFrameLatencyNeeded = true;
3359 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3360 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3361 mBufferInfo.mFence = mDrawingState.acquireFence;
3362 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3363 auto lastDataspace = mBufferInfo.mDataspace;
3364 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3365 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003366 mFlinger->mHdrLayerInfoChanged = true;
3367 }
3368 if (mBufferInfo.mDesiredSdrHdrRatio != mDrawingState.desiredSdrHdrRatio) {
3369 mBufferInfo.mDesiredSdrHdrRatio = mDrawingState.desiredSdrHdrRatio;
3370 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003371 }
3372 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3373 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3374 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3375 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3376 mBufferInfo.mApi = mDrawingState.api;
3377 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003378}
3379
3380Rect Layer::computeBufferCrop(const State& s) {
3381 if (s.buffer && !s.bufferCrop.isEmpty()) {
3382 Rect bufferCrop;
3383 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3384 return bufferCrop;
3385 } else if (s.buffer) {
3386 return s.buffer->getBounds();
3387 } else {
3388 return s.bufferCrop;
3389 }
3390}
3391
3392sp<Layer> Layer::createClone() {
3393 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3394 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003395 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003396 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3397 return layer;
3398}
3399
Patrick Williamsbb25f802022-08-30 23:02:34 +00003400void Layer::decrementPendingBufferCount() {
3401 int32_t pendingBuffers = --mPendingBufferTransactions;
3402 tracePendingBufferCount(pendingBuffers);
3403}
3404
3405void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3406 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3407}
3408
3409/*
3410 * We don't want to send the layer's transform to input, but rather the
3411 * parent's transform. This is because Layer's transform is
3412 * information about how the buffer is placed on screen. The parent's
3413 * transform makes more sense to send since it's information about how the
3414 * layer is placed on screen. This transform is used by input to determine
3415 * how to go from screen space back to window space.
3416 */
3417ui::Transform Layer::getInputTransform() const {
3418 if (!hasBufferOrSidebandStream()) {
3419 return getTransform();
3420 }
3421 sp<Layer> parent = mDrawingParent.promote();
3422 if (parent == nullptr) {
3423 return ui::Transform();
3424 }
3425
3426 return parent->getTransform();
3427}
3428
3429/**
3430 * Similar to getInputTransform, we need to update the bounds to include the transform.
3431 * This is because bounds don't include the buffer transform, where the input assumes
3432 * that's already included.
3433 */
3434Rect Layer::getInputBounds() const {
3435 if (!hasBufferOrSidebandStream()) {
3436 return getCroppedBufferSize(getDrawingState());
3437 }
3438
3439 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
3440 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
3441 return bufferBounds;
3442 }
3443 return mDrawingState.transform.transform(bufferBounds);
3444}
3445
3446bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3447 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3448
3449 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3450 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3451 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3452 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3453 layer_state_t::eReparent;
3454
3455 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3456 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3457 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3458 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3459 layer_state_t::eInputInfoChanged;
3460
3461 if ((s.what & requiredFlags) != requiredFlags) {
3462 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3463 (s.what | requiredFlags) & ~s.what);
3464 return false;
3465 }
3466
3467 if (s.what & deniedFlags) {
3468 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3469 return false;
3470 }
3471
3472 if (s.what & allowedFlags) {
3473 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3474 }
3475
3476 if (s.what & layer_state_t::ePositionChanged) {
3477 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3478 ALOGV("%s: false [ePositionChanged changed]", __func__);
3479 return false;
3480 }
3481 }
3482
3483 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003484 if (mDrawingState.color.a != s.color.a) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003485 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3486 return false;
3487 }
3488 }
3489
3490 if (s.what & layer_state_t::eColorTransformChanged) {
3491 if (mDrawingState.colorTransform != s.colorTransform) {
3492 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3493 return false;
3494 }
3495 }
3496
3497 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003498 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003499 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3500 return false;
3501 }
3502 }
3503
3504 if (s.what & layer_state_t::eMatrixChanged) {
3505 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3506 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3507 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3508 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3509 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3510 return false;
3511 }
3512 }
3513
3514 if (s.what & layer_state_t::eCornerRadiusChanged) {
3515 if (mDrawingState.cornerRadius != s.cornerRadius) {
3516 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3517 return false;
3518 }
3519 }
3520
3521 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3522 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3523 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3524 return false;
3525 }
3526 }
3527
Vishnu Nairbbceb462022-10-10 04:52:13 +00003528 if (s.what & layer_state_t::eBufferTransformChanged) {
3529 if (mDrawingState.bufferTransform != s.bufferTransform) {
3530 ALOGV("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003531 return false;
3532 }
3533 }
3534
3535 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3536 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3537 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3538 return false;
3539 }
3540 }
3541
3542 if (s.what & layer_state_t::eCropChanged) {
3543 if (mDrawingState.crop != s.crop) {
3544 ALOGV("%s: false [eCropChanged changed]", __func__);
3545 return false;
3546 }
3547 }
3548
3549 if (s.what & layer_state_t::eDataspaceChanged) {
3550 if (mDrawingState.dataspace != s.dataspace) {
3551 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3552 return false;
3553 }
3554 }
3555
3556 if (s.what & layer_state_t::eHdrMetadataChanged) {
3557 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3558 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3559 return false;
3560 }
3561 }
3562
3563 if (s.what & layer_state_t::eSidebandStreamChanged) {
3564 if (mDrawingState.sidebandStream != s.sidebandStream) {
3565 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3566 return false;
3567 }
3568 }
3569
3570 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3571 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3572 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3573 return false;
3574 }
3575 }
3576
3577 if (s.what & layer_state_t::eShadowRadiusChanged) {
3578 if (mDrawingState.shadowRadius != s.shadowRadius) {
3579 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3580 return false;
3581 }
3582 }
3583
3584 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3585 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3586 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3587 return false;
3588 }
3589 }
3590
3591 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3592 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3593 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3594 return false;
3595 }
3596 }
3597
3598 if (s.what & layer_state_t::eStretchChanged) {
3599 StretchEffect temp = s.stretchEffect;
3600 temp.sanitize();
3601 if (mDrawingState.stretchEffect != temp) {
3602 ALOGV("%s: false [eStretchChanged changed]", __func__);
3603 return false;
3604 }
3605 }
3606
3607 if (s.what & layer_state_t::eBufferCropChanged) {
3608 if (mDrawingState.bufferCrop != s.bufferCrop) {
3609 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3610 return false;
3611 }
3612 }
3613
3614 if (s.what & layer_state_t::eDestinationFrameChanged) {
3615 if (mDrawingState.destinationFrame != s.destinationFrame) {
3616 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3617 return false;
3618 }
3619 }
3620
3621 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3622 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3623 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3624 return false;
3625 }
3626 }
3627
John Reck68796592023-01-25 13:47:12 -05003628 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
3629 if (mDrawingState.currentSdrHdrRatio != s.currentSdrHdrRatio ||
3630 mDrawingState.desiredSdrHdrRatio != s.desiredSdrHdrRatio) {
3631 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3632 return false;
3633 }
3634 }
3635
Patrick Williamsbb25f802022-08-30 23:02:34 +00003636 ALOGV("%s: true", __func__);
3637 return true;
3638}
3639
3640bool Layer::isHdrY410() const {
3641 // pixel format is HDR Y410 masquerading as RGBA_1010102
3642 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3643 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3644 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3645}
3646
Vishnu Naire14c6b32022-08-06 04:20:15 +00003647sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003648 // 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 +00003649 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003650}
3651
Vishnu Naire14c6b32022-08-06 04:20:15 +00003652const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003653 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003654}
3655
Vishnu Naire14c6b32022-08-06 04:20:15 +00003656LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003657 return mSnapshot.get();
3658}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003659
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003660std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3661 return std::move(mSnapshot);
3662}
3663
3664void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3665 mSnapshot = std::move(snapshot);
3666}
3667
Patrick Williamsbb25f802022-08-30 23:02:34 +00003668const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003669 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003670}
3671
Patrick Williams7584c6a2022-10-29 02:10:58 +00003672sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003673 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003674 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3675 return result;
3676}
3677
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003678sp<LayerFE> Layer::getCompositionEngineLayerFE(
3679 const frontend::LayerHierarchy::TraversalPath& path) {
3680 for (auto& [p, layerFE] : mLayerFEs) {
3681 if (p == path) {
3682 return layerFE;
3683 }
3684 }
3685 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3686 mLayerFEs.emplace_back(path, layerFE);
3687 return layerFE;
3688}
3689
Patrick Williamsbb25f802022-08-30 23:02:34 +00003690void Layer::useSurfaceDamage() {
3691 if (mFlinger->mForceFullDamage) {
3692 surfaceDamageRegion = Region::INVALID_REGION;
3693 } else {
3694 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3695 }
3696}
3697
3698void Layer::useEmptyDamage() {
3699 surfaceDamageRegion.clear();
3700}
3701
3702bool Layer::isOpaque(const Layer::State& s) const {
3703 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3704 // layer's opaque flag.
3705 if (!hasSomethingToDraw()) {
3706 return false;
3707 }
3708
3709 // if the layer has the opaque flag, then we're always opaque
3710 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3711 return true;
3712 }
3713
3714 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003715 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003716 return true;
3717 }
3718
3719 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3720 return fillsColor() && getAlpha() == 1.0_hf;
3721}
3722
3723bool Layer::canReceiveInput() const {
3724 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3725}
3726
3727bool Layer::isVisible() const {
3728 if (!hasSomethingToDraw()) {
3729 return false;
3730 }
3731
3732 if (isHiddenByPolicy()) {
3733 return false;
3734 }
3735
3736 return getAlpha() > 0.0f || hasBlur();
3737}
3738
3739void Layer::onPostComposition(const DisplayDevice* display,
3740 const std::shared_ptr<FenceTime>& glDoneFence,
3741 const std::shared_ptr<FenceTime>& presentFence,
3742 const CompositorTiming& compositorTiming) {
3743 // mFrameLatencyNeeded is true when a new frame was latched for the
3744 // composition.
3745 if (!mBufferInfo.mFrameLatencyNeeded) return;
3746
3747 for (const auto& handle : mDrawingState.callbackHandles) {
3748 handle->gpuCompositionDoneFence = glDoneFence;
3749 handle->compositorTiming = compositorTiming;
3750 }
3751
3752 // Update mFrameTracker.
3753 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3754 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3755
3756 const int32_t layerId = getSequence();
3757 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3758
3759 const auto outputLayer = findOutputLayerForDisplay(display);
3760 if (outputLayer && outputLayer->requiresClientComposition()) {
3761 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3762 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3763 clientCompositionTimestamp,
3764 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3765 // Update the SurfaceFrames in the drawing state
3766 if (mDrawingState.bufferSurfaceFrameTX) {
3767 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3768 }
3769 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3770 surfaceFrame->setGpuComposition();
3771 }
3772 }
3773
3774 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3775 if (frameReadyFence->isValid()) {
3776 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3777 } else {
3778 // There was no fence for this frame, so assume that it was ready
3779 // to be presented at the desired present time.
3780 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3781 }
3782
3783 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08003784 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003785 const std::optional<Fps> renderRate =
3786 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3787
3788 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3789 const auto gameMode = getGameMode();
3790
3791 if (presentFence->isValid()) {
3792 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3793 refreshRate, renderRate, vote, gameMode);
3794 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3795 presentFence,
3796 FrameTracer::FrameEvent::PRESENT_FENCE);
3797 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3798 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3799 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003800 // The HWC doesn't support present fences, so use the present timestamp instead.
3801 const nsecs_t presentTimestamp =
3802 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3803
3804 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3805 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3806 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3807
Patrick Williamsbb25f802022-08-30 23:02:34 +00003808 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3809 refreshRate, renderRate, vote, gameMode);
3810 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3811 mCurrentFrameNumber, actualPresentTime,
3812 FrameTracer::FrameEvent::PRESENT_FENCE);
3813 mFrameTracker.setActualPresentTime(actualPresentTime);
3814 }
3815 }
3816
3817 mFrameTracker.advanceFrame();
3818 mBufferInfo.mFrameLatencyNeeded = false;
3819}
3820
3821bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003822 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
3823 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
3824}
3825
3826bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003827 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3828 getDrawingState().frameNumber);
3829
3830 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3831
3832 if (refreshRequired) {
3833 return refreshRequired;
3834 }
3835
3836 // If the head buffer's acquire fence hasn't signaled yet, return and
3837 // try again later
3838 if (!fenceHasSignaled()) {
3839 ATRACE_NAME("!fenceHasSignaled()");
3840 mFlinger->onLayerUpdate();
3841 return false;
3842 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00003843 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003844 if (mDrawingState.buffer == nullptr) {
3845 return false;
3846 }
3847
3848 // Capture the old state of the layer for comparisons later
3849 BufferInfo oldBufferInfo = mBufferInfo;
3850 const bool oldOpacity = isOpaque(mDrawingState);
3851 mPreviousFrameNumber = mCurrentFrameNumber;
3852 mCurrentFrameNumber = mDrawingState.frameNumber;
3853 gatherBufferInfo();
3854
3855 if (oldBufferInfo.mBuffer == nullptr) {
3856 // the first time we receive a buffer, we need to trigger a
3857 // geometry invalidation.
3858 recomputeVisibleRegions = true;
3859 }
3860
3861 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3862 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3863 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3864 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3865 recomputeVisibleRegions = true;
3866 }
3867
3868 if (oldBufferInfo.mBuffer != nullptr) {
3869 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3870 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3871 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3872 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3873 recomputeVisibleRegions = true;
3874 }
3875 }
3876
3877 if (oldOpacity != isOpaque(mDrawingState)) {
3878 recomputeVisibleRegions = true;
3879 }
3880
3881 return true;
3882}
3883
3884bool Layer::hasReadyFrame() const {
3885 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
3886}
3887
3888bool Layer::isProtected() const {
3889 return (mBufferInfo.mBuffer != nullptr) &&
3890 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
3891}
3892
Patrick Williamsbb25f802022-08-30 23:02:34 +00003893void Layer::latchAndReleaseBuffer() {
3894 if (hasReadyFrame()) {
3895 bool ignored = false;
3896 latchBuffer(ignored, systemTime());
3897 }
3898 releasePendingBuffer(systemTime());
3899}
3900
3901PixelFormat Layer::getPixelFormat() const {
3902 return mBufferInfo.mPixelFormat;
3903}
3904
3905bool Layer::getTransformToDisplayInverse() const {
3906 return mBufferInfo.mTransformToDisplayInverse;
3907}
3908
3909Rect Layer::getBufferCrop() const {
3910 // this is the crop rectangle that applies to the buffer
3911 // itself (as opposed to the window)
3912 if (!mBufferInfo.mCrop.isEmpty()) {
3913 // if the buffer crop is defined, we use that
3914 return mBufferInfo.mCrop;
3915 } else if (mBufferInfo.mBuffer != nullptr) {
3916 // otherwise we use the whole buffer
3917 return mBufferInfo.mBuffer->getBounds();
3918 } else {
3919 // if we don't have a buffer yet, we use an empty/invalid crop
3920 return Rect();
3921 }
3922}
3923
3924uint32_t Layer::getBufferTransform() const {
3925 return mBufferInfo.mTransform;
3926}
3927
3928ui::Dataspace Layer::getDataSpace() const {
3929 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
3930}
3931
3932ui::Dataspace Layer::getRequestedDataSpace() const {
3933 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
3934}
3935
3936ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
3937 ui::Dataspace updatedDataspace = dataspace;
3938 // translate legacy dataspaces to modern dataspaces
3939 switch (dataspace) {
3940 case ui::Dataspace::SRGB:
3941 updatedDataspace = ui::Dataspace::V0_SRGB;
3942 break;
3943 case ui::Dataspace::SRGB_LINEAR:
3944 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
3945 break;
3946 case ui::Dataspace::JFIF:
3947 updatedDataspace = ui::Dataspace::V0_JFIF;
3948 break;
3949 case ui::Dataspace::BT601_625:
3950 updatedDataspace = ui::Dataspace::V0_BT601_625;
3951 break;
3952 case ui::Dataspace::BT601_525:
3953 updatedDataspace = ui::Dataspace::V0_BT601_525;
3954 break;
3955 case ui::Dataspace::BT709:
3956 updatedDataspace = ui::Dataspace::V0_BT709;
3957 break;
3958 default:
3959 break;
3960 }
3961
3962 return updatedDataspace;
3963}
3964
3965sp<GraphicBuffer> Layer::getBuffer() const {
3966 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
3967}
3968
Patrick Williamsbb25f802022-08-30 23:02:34 +00003969void Layer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
3970 mTransformHint = getFixedTransformHint();
3971 if (mTransformHint == ui::Transform::ROT_INVALID) {
3972 mTransformHint = displayTransformHint;
3973 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07003974 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003975}
3976
3977const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
3978 return mBufferInfo.mBuffer;
3979}
3980
3981bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003982 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003983 return false;
3984 }
3985
3986 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00003987 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003988 mDrawingState.modified = true;
3989 setTransactionFlags(eTransactionNeeded);
3990 return true;
3991}
3992
3993bool Layer::fillsColor() const {
3994 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
3995 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
3996}
3997
3998bool Layer::hasBlur() const {
3999 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4000}
4001
Vishnu Nairba354102022-08-01 00:14:18 +00004002void Layer::updateSnapshot(bool updateGeometry) {
4003 if (!getCompositionEngineLayerFE()) {
4004 return;
4005 }
4006
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004007 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004008 if (updateGeometry) {
4009 prepareBasicGeometryCompositionState();
4010 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004011 snapshot->roundedCorner = getRoundedCornerState();
4012 snapshot->stretchEffect = getStretchEffect();
4013 snapshot->transformedBounds = mScreenBounds;
4014 if (mEffectiveShadowRadius > 0.f) {
4015 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4016
4017 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4018 // it if transparent regions are present. This may not be necessary since shadows are
4019 // typically cast by layers without transparent regions.
4020 snapshot->shadowSettings.boundaries = mBounds;
4021
4022 const float casterAlpha = snapshot->alpha;
4023 const bool casterIsOpaque =
4024 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4025
4026 // If the casting layer is translucent, we need to fill in the shadow underneath the
4027 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4028 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4029 snapshot->shadowSettings.ambientColor *= casterAlpha;
4030 snapshot->shadowSettings.spotColor *= casterAlpha;
4031 }
4032 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004033 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004034 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004035 snapshot->layerOpaqueFlagSet =
4036 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004037 snapshot->isHdrY410 = isHdrY410();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004038 sp<Layer> p = mDrawingParent.promote();
4039 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004040 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004041 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004042 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004043 }
4044 snapshot->bufferSize = getBufferSize(mDrawingState);
4045 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004046 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004047 preparePerFrameCompositionState();
4048}
4049
Vishnu Naire14c6b32022-08-06 04:20:15 +00004050void Layer::updateChildrenSnapshots(bool updateGeometry) {
4051 for (const sp<Layer>& child : mDrawingChildren) {
4052 child->updateSnapshot(updateGeometry);
4053 child->updateChildrenSnapshots(updateGeometry);
4054 }
4055}
4056
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004057void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4058 mSnapshot->layerMetadata = parentMetadata;
4059 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4060 for (const sp<Layer>& child : mDrawingChildren) {
4061 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4062 }
4063}
4064
4065void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4066 std::unordered_set<Layer*>& visited) {
4067 if (visited.find(this) != visited.end()) {
4068 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4069 return;
4070 }
4071 visited.insert(this);
4072
4073 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4074
4075 if (mDrawingState.zOrderRelatives.empty()) {
4076 return;
4077 }
4078 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4079 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4080 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4081 sp<Layer> relative = weakRelative.promote();
4082 if (!relative) {
4083 continue;
4084 }
4085 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4086 }
4087}
4088
Chavi Weingarten328a8312023-01-26 21:17:52 +00004089bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004090 TrustedPresentationListener const& listener) {
4091 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4092 mTrustedPresentationListener = listener;
4093 mTrustedPresentationThresholds = thresholds;
4094 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4095 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4096 mFlinger->mNumTrustedPresentationListeners++;
4097 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4098 mFlinger->mNumTrustedPresentationListeners--;
4099 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004100
4101 // Reset trusted presentation states to ensure we start the time again.
4102 mEnteredTrustedPresentationStateTime = -1;
4103 mLastReportedTrustedPresentationState = false;
4104 mLastComputedTrustedPresentationState = false;
4105
4106 // If there's a new trusted presentation listener, the code needs to go through the composite
4107 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4108 // we're already in the requested state.
4109 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004110}
4111
Vishnu Naira156f482023-02-22 00:23:38 +00004112void Layer::updateLastLatchTime(nsecs_t latchTime) {
4113 mLastLatchTime = latchTime;
4114}
4115
Mathias Agopian13127d82013-03-05 17:47:11 -08004116// ---------------------------------------------------------------------------
4117
Marin Shalamanov46084422020-10-13 12:33:42 +02004118std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004119 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4120 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004121}
4122
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004123} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004124
4125#if defined(__gl_h_)
4126#error "don't include gl/gl.h in this file"
4127#endif
4128
4129#if defined(__gl2_h_)
4130#error "don't include gl2/gl2.h in this file"
4131#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004132
4133// TODO(b/129481165): remove the #pragma below and fix conversion issues
4134#pragma clang diagnostic pop // ignored "-Wconversion"