blob: 0a27bddb58508f5970aebc0b58a60474fbb42336 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Dan Stoza9e56aa02015-11-02 13:00:03 -080021//#define LOG_NDEBUG 0
22#undef LOG_TAG
23#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080024#define ATRACE_TAG ATRACE_TAG_GRAPHICS
25
Alec Mourie60041e2019-06-14 18:59:51 -070026#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080027
[1;3C2b9fc252021-02-04 16:16:50 -080028#include <android-base/properties.h>
Yiwei Zhang5434a782018-12-05 18:06:32 -080029#include <android-base/stringprintf.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080030#include <android/native_window.h>
Vishnu Nair0f085c62019-08-30 08:49:12 -070031#include <binder/IPCThreadState.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000032#include <compositionengine/CompositionEngine.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080033#include <compositionengine/Display.h>
Lloyd Piquea83776c2019-01-29 18:42:32 -080034#include <compositionengine/LayerFECompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080035#include <compositionengine/OutputLayer.h>
36#include <compositionengine/impl/OutputLayerCompositionState.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070037#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070038#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070039#include <cutils/properties.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070040#include <ftl/enum.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080041#include <ftl/fake_guard.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080042#include <gui/BufferItem.h>
43#include <gui/LayerDebugInfo.h>
44#include <gui/Surface.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000045#include <gui/TraceUtils.h>
Alec Mourie60041e2019-06-14 18:59:51 -070046#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070047#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070049#include <stdint.h>
50#include <stdlib.h>
51#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000052#include <system/graphics-base-v1.0.h>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070053#include <ui/DataspaceUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080054#include <ui/DebugUtils.h>
55#include <ui/GraphicBuffer.h>
56#include <ui/PixelFormat.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#include <utils/Errors.h>
58#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080059#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080061#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Alec Mourie60041e2019-06-14 18:59:51 -070063#include <algorithm>
64#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070065#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070066#include <sstream>
67
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070068#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080069#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070070#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070071#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +000072#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000073#include "FrontEnd/LayerHandle.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080074#include "LayerProtoHelper.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080076#include "TimeStats/TimeStats.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070077#include "TunnelModeEnabledReporter.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070078
David Sodman41fdfc92017-11-06 16:09:56 -080079#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000080#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082namespace android {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010083namespace {
84constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000085
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000086const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000087
Patrick Williamsbb25f802022-08-30 23:02:34 +000088bool assignTransform(ui::Transform* dst, ui::Transform& from) {
89 if (*dst == from) {
90 return false;
91 }
92 *dst = from;
93 return true;
94}
95
96TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
97 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
98 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
99 const auto frameRateCompatibility = [frameRate] {
100 switch (frameRate.type) {
101 case Layer::FrameRateCompatibility::Default:
102 return FrameRateCompatibility::Default;
103 case Layer::FrameRateCompatibility::ExactOrMultiple:
104 return FrameRateCompatibility::ExactOrMultiple;
105 default:
106 return FrameRateCompatibility::Undefined;
107 }
108 }();
109
110 const auto seamlessness = [frameRate] {
111 switch (frameRate.seamlessness) {
112 case scheduler::Seamlessness::OnlySeamless:
113 return Seamlessness::ShouldBeSeamless;
114 case scheduler::Seamlessness::SeamedAndSeamless:
115 return Seamlessness::NotRequired;
116 default:
117 return Seamlessness::Undefined;
118 }
119 }();
120
121 return TimeStats::SetFrameRateVote{.frameRate = frameRate.rate.getValue(),
122 .frameRateCompatibility = frameRateCompatibility,
123 .seamlessness = seamlessness};
124}
125
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100126} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700128using namespace ftl::flag_operators;
129
Yiwei Zhang5434a782018-12-05 18:06:32 -0800130using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000131using frontend::LayerSnapshot;
132using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800133using gui::GameMode;
134using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500135using gui::WindowInfo;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800136
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700137using PresentState = frametimeline::SurfaceFrame::PresentState;
138
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700139Layer::Layer(const LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000140 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700141 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000142 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700143 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800144 mWindowType(static_cast<WindowInfo::Type>(
145 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000146 mLayerCreationFlags(args.flags),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000147 mBorderEnabled(false),
148 mTextureName(args.textureName),
Vishnu Naird6913222023-02-01 22:56:21 +0000149 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000150 ALOGV("Creating Layer %s", getDebugName());
151
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700152 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700153 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
154 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
155 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700156 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
157 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700158 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700159 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700160 mDrawingState.z = 0;
161 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700162 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700163 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700164 mDrawingState.transform.set(0, 0);
165 mDrawingState.frameNumber = 0;
166 mDrawingState.bufferTransform = 0;
167 mDrawingState.transformToDisplayInverse = false;
168 mDrawingState.crop.makeInvalid();
169 mDrawingState.acquireFence = sp<Fence>::make(-1);
170 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
171 mDrawingState.dataspace = ui::Dataspace::UNKNOWN;
Vishnu Nairbc4ee5c2022-08-16 03:19:37 +0000172 mDrawingState.dataspaceRequested = false;
Robert Carr6a160312021-05-17 12:08:20 -0700173 mDrawingState.hdrMetadata.validTypes = 0;
174 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
175 mDrawingState.cornerRadius = 0.0f;
176 mDrawingState.backgroundBlurRadius = 0;
177 mDrawingState.api = -1;
178 mDrawingState.hasColorTransform = false;
179 mDrawingState.colorSpaceAgnostic = false;
180 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
181 mDrawingState.metadata = args.metadata;
182 mDrawingState.shadowRadius = 0.f;
183 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
184 mDrawingState.frameTimelineInfo = {};
185 mDrawingState.postTime = -1;
186 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000187 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700188 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700189 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000190 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700191
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700192 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
193 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700194 mDrawingState.color.r = -1.0_hf;
195 mDrawingState.color.g = -1.0_hf;
196 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700197 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700198
Dominik Laskowski933f8de2023-01-20 13:15:51 -0500199 mFrameTracker.setDisplayRefreshPeriod(args.flinger->mScheduler->getLeaderVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700200
Vishnu Naircb8be502022-10-12 19:03:23 +0000201 mOwnerUid = args.ownerUid;
202 mOwnerPid = args.ownerPid;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000203
204 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
205 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
206 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
207 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000208
209 mSnapshot->sequence = sequence;
210 mSnapshot->name = getDebugName();
211 mSnapshot->textureName = mTextureName;
212 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000213 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800214}
215
216void Layer::onFirstRef() {
217 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700218}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700219
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700220Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000221 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
222 "Layer destructor called off the main thread.");
223
Patrick Williamsbb25f802022-08-30 23:02:34 +0000224 // The original layer and the clone layer share the same texture and buffer. Therefore, only
225 // one of the layers, in this case the original layer, needs to handle the deletion. The
226 // original layer and the clone should be removed at the same time so there shouldn't be any
227 // issue with the clone layer trying to use the texture.
228 if (mBufferInfo.mBuffer != nullptr) {
229 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
230 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
231 mBufferInfo.mFence,
232 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
233 mOwnerUid));
234 }
235 if (!isClone()) {
236 // The original layer and the clone layer share the same texture. Therefore, only one of
237 // the layers, in this case the original layer, needs to handle the deletion. The original
238 // layer and the clone should be removed at the same time so there shouldn't be any issue
239 // with the clone layer trying to use the deleted texture.
240 mFlinger->deleteTextureAsync(mTextureName);
241 }
242 const int32_t layerId = getSequence();
243 mFlinger->mTimeStats->onDestroy(layerId);
244 mFlinger->mFrameTracer->onDestroy(layerId);
245
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000246 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700247 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700248
249 if (mDrawingState.sidebandStream != nullptr) {
250 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
251 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700252 if (mHadClonedChild) {
253 mFlinger->mNumClones--;
254 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000255 if (hasTrustedPresentationListener()) {
256 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000257 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000258 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700259}
260
Mathias Agopian13127d82013-03-05 17:47:11 -0800261// ---------------------------------------------------------------------------
262// callbacks
263// ---------------------------------------------------------------------------
264
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700265void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700266 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700267 return;
268 }
Robert Carr2e102c92018-10-23 12:11:15 -0700269
Robert Carr6a160312021-05-17 12:08:20 -0700270 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700271 if (strongRelative == nullptr) {
272 setZOrderRelativeOf(nullptr);
273 return;
274 }
275
276 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700277 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700278 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800279 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700280 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700281}
282
283void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700284 if (!mRemovedFromDrawingState) {
285 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700286 mFlinger->mScheduler->deregisterLayer(this);
287 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000288 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000289
Ady Abrahamd11bade2022-08-01 16:18:03 -0700290 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700291}
Chia-I Wu38512252017-05-17 14:36:16 -0700292
chaviw68d4dab2020-06-08 15:07:32 -0700293sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000294 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700295 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700296 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700297 }
298 return parent->getRootLayer();
299}
300
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700301void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700302 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
303 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700304 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700305
306 traverse(LayerVector::StateSet::Current, [&](Layer* layer) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700307 layer->removeFromCurrentState();
308 layer->removeRelativeZ(layersInTree);
chaviw68d4dab2020-06-08 15:07:32 -0700309 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700310}
311
chaviw61626f22018-11-15 16:26:27 -0800312void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700313 if (mRemovedFromDrawingState) {
314 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700315 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700316 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700317 }
chaviw61626f22018-11-15 16:26:27 -0800318
319 for (const auto& child : mCurrentChildren) {
320 child->addToCurrentState();
321 }
322}
323
Mathias Agopian13127d82013-03-05 17:47:11 -0800324// ---------------------------------------------------------------------------
325// set-up
326// ---------------------------------------------------------------------------
327
chaviw13fdc492017-06-27 12:40:18 -0700328bool Layer::getPremultipledAlpha() const {
329 return mPremultipliedAlpha;
330}
331
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700332sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800333 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700334 if (mGetHandleCalled) {
335 ALOGE("Get handle called twice" );
336 return nullptr;
337 }
338 mGetHandleCalled = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000339 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800340}
341
342// ---------------------------------------------------------------------------
343// h/w composer set-up
344// ---------------------------------------------------------------------------
345
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700346static Rect reduce(const Rect& win, const Region& exclude) {
347 if (CC_LIKELY(exclude.isEmpty())) {
348 return win;
349 }
350 if (exclude.isRect()) {
351 return win.reduce(exclude.getBounds());
352 }
353 return Region(win).subtract(exclude).getBounds();
354}
355
Dan Stoza80d61162017-12-20 15:57:52 -0800356static FloatRect reduce(const FloatRect& win, const Region& exclude) {
357 if (CC_LIKELY(exclude.isEmpty())) {
358 return win;
359 }
360 // Convert through Rect (by rounding) for lack of FloatRegion
361 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
362}
363
Vishnu Nair4351ad52019-02-11 14:13:02 -0800364Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800365 if (!reduceTransparentRegion) {
366 return Rect{mScreenBounds};
367 }
368
369 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800370 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800371 // Transform to screen space.
372 bounds = t.transform(bounds);
373 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700374}
375
Vishnu Nair4351ad52019-02-11 14:13:02 -0800376FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000377 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800378 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700379}
380
Vishnu Nairf0c28512019-02-08 12:40:28 -0800381FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
382 // Subtract the transparent region and snap to the bounds.
383 return reduce(mBounds, activeTransparentRegion);
384}
385
Chavi Weingarten076acac2023-01-19 17:20:43 +0000386// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000387void Layer::updateTrustedPresentationState(const DisplayDevice* display,
388 const frontend::LayerSnapshot* snapshot,
389 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000390 if (!hasTrustedPresentationListener()) {
391 return;
392 }
393 const bool lastState = mLastComputedTrustedPresentationState;
394 mLastComputedTrustedPresentationState = false;
395
396 if (!leaveState) {
397 const auto outputLayer = findOutputLayerForDisplay(display);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000398 if (outputLayer != nullptr) {
399 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
400 Region coveredRegion =
401 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
402 mLastComputedTrustedPresentationState =
403 computeTrustedPresentationState(snapshot->geomLayerBounds,
404 snapshot->sourceBounds(), coveredRegion,
405 snapshot->transformedBounds,
406 snapshot->alpha,
407 snapshot->geomLayerTransform,
408 mTrustedPresentationThresholds);
409 } else {
410 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
411 "TrustedPresentationState",
412 getDebugName());
413 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000414 }
415 }
416 const bool newState = mLastComputedTrustedPresentationState;
417 if (lastState && !newState) {
418 // We were in the trusted presentation state, but now we left it,
419 // emit the callback if needed
420 if (mLastReportedTrustedPresentationState) {
421 mLastReportedTrustedPresentationState = false;
422 mTrustedPresentationListener.invoke(false);
423 }
424 // Reset the timer
425 mEnteredTrustedPresentationStateTime = -1;
426 } else if (!lastState && newState) {
427 // We were not in the trusted presentation state, but we entered it, begin the timer
428 // and make sure this gets called at least once more!
429 mEnteredTrustedPresentationStateTime = time_in_ms;
430 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
431 }
432
433 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
434 if (!mLastReportedTrustedPresentationState && newState &&
435 (time_in_ms - mEnteredTrustedPresentationStateTime >
436 mTrustedPresentationThresholds.stabilityRequirementMs)) {
437 mLastReportedTrustedPresentationState = true;
438 mTrustedPresentationListener.invoke(true);
439 }
440}
441
442/**
443 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
444 * of how the parameters and thresholds are interpreted. The general spirit is
445 * to produce an upper bound on the amount of the buffer which was presented.
446 */
447bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
448 const Region& coveredRegion,
449 const FloatRect& screenBounds, float alpha,
450 const ui::Transform& effectiveTransform,
451 const TrustedPresentationThresholds& thresholds) {
452 if (alpha < thresholds.minAlpha) {
453 return false;
454 }
455 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
456 return false;
457 }
458 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
459 return false;
460 }
461
462 const float sx = effectiveTransform.dsdx();
463 const float sy = effectiveTransform.dsdy();
464 float fractionRendered = std::min(sx * sy, 1.0f);
465
466 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
467 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
468 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
469
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000470 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
471 // Compute the size of all the rects since they may be disconnected.
472 float coveredSize = 0;
473 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
474 float size = rect->width() * rect->height();
475 coveredSize += size;
476 }
477
478 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000479
480 if (fractionRendered < thresholds.minFractionRendered) {
481 return false;
482 }
483
484 return true;
485}
486
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700487void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
488 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800489 const State& s(getDrawingState());
490
491 // Calculate effective layer transform
492 mEffectiveTransform = parentTransform * getActiveTransform(s);
493
Garfield Tan2c1782c2022-02-16 15:25:05 -0800494 if (CC_UNLIKELY(!isTransformValid())) {
495 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
496 getDebugName());
497 return;
498 }
499
Vishnu Nair4351ad52019-02-11 14:13:02 -0800500 // Transform parent bounds to layer space
501 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
502
Vishnu Nairc652ff82019-03-15 12:48:54 -0700503 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800504 mSourceBounds = computeSourceBounds(parentBounds);
505
506 // Calculate bounds by croping diplay frame with layer crop and parent bounds
507 FloatRect bounds = mSourceBounds;
508 const Rect layerCrop = getCrop(s);
509 if (!layerCrop.isEmpty()) {
510 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
511 }
512 bounds = bounds.intersect(parentBounds);
513
514 mBounds = bounds;
515 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700516
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700517 // Use the layer's own shadow radius if set. Otherwise get the radius from
518 // parent.
519 if (s.shadowRadius > 0.f) {
520 mEffectiveShadowRadius = s.shadowRadius;
521 } else {
522 mEffectiveShadowRadius = parentShadowRadius;
523 }
524
525 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
526 // don't pass it to its children.
527 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
528
Vishnu Nair4351ad52019-02-11 14:13:02 -0800529 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700530 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800531 }
Vishnu Nairba354102022-08-01 00:14:18 +0000532
533 if (mPotentialCursor) {
534 prepareCursorCompositionState();
535 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800536}
537
Vishnu Nair60356342018-11-13 13:00:45 -0800538Rect Layer::getCroppedBufferSize(const State& s) const {
539 Rect size = getBufferSize(s);
540 Rect crop = getCrop(s);
541 if (!crop.isEmpty() && size.isValid()) {
542 size.intersect(crop, &size);
543 } else if (!crop.isEmpty()) {
544 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700545 }
Vishnu Nair60356342018-11-13 13:00:45 -0800546 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800547}
548
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700549void Layer::setupRoundedCornersCropCoordinates(Rect win,
550 const FloatRect& roundedCornersCrop) const {
551 // Translate win by the rounded corners rect coordinates, to have all values in
552 // layer coordinate space.
553 win.left -= roundedCornersCrop.left;
554 win.right -= roundedCornersCrop.left;
555 win.top -= roundedCornersCrop.top;
556 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700557}
558
Lloyd Piquede196652020-01-22 17:29:58 -0800559void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800560 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800561 const auto alpha = static_cast<float>(getAlpha());
562 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700563 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800564
565 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
566 if (!opaque || alpha != 1.0f) {
567 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
568 : Hwc2::IComposerClient::BlendMode::COVERAGE;
569 }
570
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000571 auto* snapshot = editLayerSnapshot();
572 snapshot->outputFilter = getOutputFilter();
573 snapshot->isVisible = isVisible();
574 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
575 snapshot->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800576
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000577 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800578 contentDirty = false;
579
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000580 snapshot->geomLayerBounds = mBounds;
581 snapshot->geomLayerTransform = getTransform();
582 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
583 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000584 snapshot->localTransform = getActiveTransform(drawingState);
585 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000586 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
587 snapshot->alpha = alpha;
588 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
589 snapshot->blurRegions = drawingState.blurRegions;
590 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800591}
592
Lloyd Piquede196652020-01-22 17:29:58 -0800593void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800594 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000595 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700596
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()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000629 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800630
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000631 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800632
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000633 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
634 snapshot->dataspace = getDataSpace();
635 snapshot->colorTransform = getColorTransform();
636 snapshot->colorTransformIsIdentity = !hasColorTransform();
637 snapshot->surfaceDamage = surfaceDamageRegion;
638 snapshot->hasProtectedContent = isProtected();
639 snapshot->dimmingEnabled = isDimmingEnabled();
John Reck68796592023-01-25 13:47:12 -0500640 snapshot->currentSdrHdrRatio = getCurrentSdrHdrRatio();
641 snapshot->desiredSdrHdrRatio = getDesiredSdrHdrRatio();
Lloyd Pique688abd42019-02-15 15:42:24 -0800642
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700643 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700644
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000645 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800646
647 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400648 // Rounded corners no longer force client composition, since we may use a
649 // hole punch so that the layer will appear to have rounded corners.
650 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000651 snapshot->stretchEffect.hasEffect()) {
652 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800653 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700654 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000655 snapshot->blurRegions = drawingState.blurRegions;
656 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400657
658 // Layer framerate is used in caching decisions.
659 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
660 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000661 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000662
663 if (hasBufferOrSidebandStream()) {
664 preparePerFrameBufferCompositionState();
665 } else {
666 preparePerFrameEffectsCompositionState();
667 }
668}
669
670void Layer::preparePerFrameBufferCompositionState() {
671 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000672 auto* snapshot = editLayerSnapshot();
673 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
674 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000675 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
676 return;
677 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000678 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000679 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
680 } else {
681 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000682 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
683 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000684 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
685 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
686 }
687
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000688 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000689 snapshot->acquireFence = mBufferInfo.mFence;
690 snapshot->frameNumber = mBufferInfo.mFrameNumber;
691 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000692}
693
694void Layer::preparePerFrameEffectsCompositionState() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000695 auto* snapshot = editLayerSnapshot();
696 snapshot->color = getColor();
697 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000698 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800699}
700
Lloyd Piquede196652020-01-22 17:29:58 -0800701void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800702 const State& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000703 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800704
705 // Apply the layer's transform, followed by the display's global transform
706 // Here we're guaranteed that the layer's transform preserves rects
707 Rect win = getCroppedBufferSize(drawingState);
708 // Subtract the transparent region and snap to the bounds
709 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
710 Rect frame(getTransform().transform(bounds));
711
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000712 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800713}
714
Lloyd Piquea83776c2019-01-29 18:42:32 -0800715const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700716 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800717}
718
Mathias Agopian13127d82013-03-05 17:47:11 -0800719// ---------------------------------------------------------------------------
720// drawing...
721// ---------------------------------------------------------------------------
722
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500723aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
724 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700725 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800726 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500727 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800728 }
729 if (outputLayer->getState().hwc) {
730 return (*outputLayer->getState().hwc).hwcCompositionType;
731 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500732 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800733 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800734}
735
Mathias Agopian13127d82013-03-05 17:47:11 -0800736// ----------------------------------------------------------------------------
737// local state
738// ----------------------------------------------------------------------------
739
David Sodman41fdfc92017-11-06 16:09:56 -0800740bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800741 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700742 if (s.flags & layer_state_t::eLayerSecure) {
743 return true;
744 }
745
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000746 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700747 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700748}
749
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100750void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
751 std::vector<JankData>& jankData) {
752 if (mPendingJankClassifications.empty() ||
753 !mPendingJankClassifications.front()->getJankType()) {
754 return;
755 }
756
757 bool includeJankData = false;
758 for (const auto& handle : handles) {
759 for (const auto& cb : handle->callbackIds) {
760 if (cb.includeJankData) {
761 includeJankData = true;
762 break;
763 }
764 }
765
766 if (includeJankData) {
767 jankData.reserve(mPendingJankClassifications.size());
768 break;
769 }
770 }
771
772 while (!mPendingJankClassifications.empty() &&
773 mPendingJankClassifications.front()->getJankType()) {
774 if (includeJankData) {
775 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
776 mPendingJankClassifications.front();
777 jankData.emplace_back(
778 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
779 }
780 mPendingJankClassifications.pop_front();
781 }
782}
783
Mathias Agopian13127d82013-03-05 17:47:11 -0800784// ----------------------------------------------------------------------------
785// transaction
786// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800787
Marissa Wall61c58622018-07-18 10:12:20 -0700788uint32_t Layer::doTransaction(uint32_t flags) {
789 ATRACE_CALL();
790
Robert Carr0758e5d2021-03-11 22:15:04 -0800791 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700792 mDrawingStateModified = mDrawingState.modified;
793 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700794
Alec Mourib416efd2018-09-06 21:01:59 +0000795 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700796
Robert Carr6a160312021-05-17 12:08:20 -0700797 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800798 // invalidate and recompute the visible regions if needed
799 flags |= Layer::eVisibleRegion;
800 }
801
Robert Carr6a160312021-05-17 12:08:20 -0700802 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800803 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000804 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800805 flags |= eVisibleRegion;
806 this->contentDirty = true;
807
808 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700809 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800810 }
811
Arthur Hung9ed43392022-05-27 06:31:57 +0000812 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
813 mFlinger->mUpdateInputInfo = true;
814 }
815
Robert Carr6a160312021-05-17 12:08:20 -0700816 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800817
Mathias Agopian13127d82013-03-05 17:47:11 -0800818 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800819}
820
Robert Carr6a160312021-05-17 12:08:20 -0700821void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000822 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
823 // bufferSurfaceFrameTX will be presented in latchBuffer.
824 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
825 if (surfaceFrame->getPresentState() != PresentState::Presented) {
826 // With applyPendingStates, we could end up having presented surfaceframes from previous
827 // states
828 surfaceFrame->setPresentState(PresentState::Presented);
829 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
830 }
831 }
Robert Carr6a160312021-05-17 12:08:20 -0700832 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700833}
834
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700835uint32_t Layer::clearTransactionFlags(uint32_t mask) {
836 const auto flags = mTransactionFlags & mask;
837 mTransactionFlags &= ~mask;
838 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800839}
840
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700841void Layer::setTransactionFlags(uint32_t mask) {
842 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800843}
844
Robert Carr1f0a16a2016-10-24 16:27:39 -0700845bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
846 ssize_t idx = mCurrentChildren.indexOf(childLayer);
847 if (idx < 0) {
848 return false;
849 }
850 if (childLayer->setLayer(z)) {
851 mCurrentChildren.removeAt(idx);
852 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800853 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700854 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800855 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700856}
857
Robert Carr503c7042017-09-27 15:06:08 -0700858bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
859 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
860 ssize_t idx = mCurrentChildren.indexOf(childLayer);
861 if (idx < 0) {
862 return false;
863 }
864 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
865 mCurrentChildren.removeAt(idx);
866 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800867 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700868 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800869 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700870}
871
Robert Carrae060832016-11-28 10:51:00 -0800872bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700873 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
874 mDrawingState.sequence++;
875 mDrawingState.z = z;
876 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700877
Robert Carra70e91c2021-06-11 13:59:52 -0700878 mFlinger->mSomeChildrenChanged = true;
879
Robert Carrdb66e622017-04-10 16:55:57 -0700880 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700881 if (mDrawingState.zOrderRelativeOf != nullptr) {
882 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700883 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700884 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700885 }
chaviw606e5cf2019-03-01 10:12:10 -0800886 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700887 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800888 setTransactionFlags(eTransactionNeeded);
889 return true;
890}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700891
Robert Carrdb66e622017-04-10 16:55:57 -0700892void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700893 mDrawingState.zOrderRelatives.remove(relative);
894 mDrawingState.sequence++;
895 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700896 setTransactionFlags(eTransactionNeeded);
897}
898
899void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700900 mDrawingState.zOrderRelatives.add(relative);
901 mDrawingState.modified = true;
902 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700903 setTransactionFlags(eTransactionNeeded);
904}
905
chaviw606e5cf2019-03-01 10:12:10 -0800906void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700907 mDrawingState.zOrderRelativeOf = relativeOf;
908 mDrawingState.sequence++;
909 mDrawingState.modified = true;
910 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700911
chaviw606e5cf2019-03-01 10:12:10 -0800912 setTransactionFlags(eTransactionNeeded);
913}
914
Robert Carr503d2bd2017-12-04 15:49:47 -0800915bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000916 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700917 if (relative == nullptr) {
918 return false;
919 }
920
Robert Carr6a160312021-05-17 12:08:20 -0700921 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
922 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800923 return false;
924 }
925
Robert Carr88b85e12022-03-21 15:47:35 -0700926 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
927 (relative->mDrawingState.zOrderRelativeOf == this)) {
928 ALOGE("Detected relative layer loop between %s and %s",
929 mName.c_str(), relative->mName.c_str());
930 ALOGE("Ignoring new call to set relative layer");
931 return false;
932 }
933
Robert Carra70e91c2021-06-11 13:59:52 -0700934 mFlinger->mSomeChildrenChanged = true;
935
Robert Carr6a160312021-05-17 12:08:20 -0700936 mDrawingState.sequence++;
937 mDrawingState.modified = true;
938 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700939
Robert Carr6a160312021-05-17 12:08:20 -0700940 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700941 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700942 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700943 }
chaviw606e5cf2019-03-01 10:12:10 -0800944 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700945 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700946
947 setTransactionFlags(eTransactionNeeded);
948
949 return true;
950}
951
Winson Chunga30f7c92021-06-29 15:42:56 -0700952bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
953 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
954 mDrawingState.isTrustedOverlay = isTrustedOverlay;
955 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000956 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700957 setTransactionFlags(eTransactionNeeded);
958 return true;
959}
960
961bool Layer::isTrustedOverlay() const {
962 if (getDrawingState().isTrustedOverlay) {
963 return true;
964 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000965 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700966 return (p != nullptr) && p->isTrustedOverlay();
967}
968
Dan Stoza9e56aa02015-11-02 13:00:03 -0800969bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700970 if (mDrawingState.color.a == alpha) return false;
971 mDrawingState.sequence++;
972 mDrawingState.color.a = alpha;
973 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800974 setTransactionFlags(eTransactionNeeded);
975 return true;
976}
chaviw13fdc492017-06-27 12:40:18 -0700977
Valerie Haudd0b7572019-01-29 14:59:27 -0800978bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700979 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700980 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800981 }
Robert Carr6a160312021-05-17 12:08:20 -0700982 mDrawingState.sequence++;
983 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800984 setTransactionFlags(eTransactionNeeded);
985
Robert Carr6a160312021-05-17 12:08:20 -0700986 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -0800987 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -0800988 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700989 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -0700990 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800991 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700992 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -0700993
Valerie Haudd0b7572019-01-29 14:59:27 -0800994 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -0700995 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -0800996 mFlinger->mLayersAdded = true;
997 // set up SF to handle added color layer
998 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -0700999 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001000 }
1001 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001002 } else if (mDrawingState.bgColorLayer && alpha == 0) {
1003 mDrawingState.bgColorLayer->reparent(nullptr);
1004 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001005 return true;
1006 }
1007
Robert Carr6a160312021-05-17 12:08:20 -07001008 mDrawingState.bgColorLayer->setColor(color);
1009 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1010 mDrawingState.bgColorLayer->setAlpha(alpha);
1011 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001012
chaviw13fdc492017-06-27 12:40:18 -07001013 return true;
1014}
1015
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001016bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001017 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001018
Robert Carr6a160312021-05-17 12:08:20 -07001019 mDrawingState.sequence++;
1020 mDrawingState.cornerRadius = cornerRadius;
1021 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001022 setTransactionFlags(eTransactionNeeded);
1023 return true;
1024}
1025
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001026bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001027 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001028 // If we start or stop drawing blur then the layer's visibility state may change so increment
1029 // the magic sequence number.
1030 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1031 mDrawingState.sequence++;
1032 }
Robert Carr6a160312021-05-17 12:08:20 -07001033 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1034 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001035 setTransactionFlags(eTransactionNeeded);
1036 return true;
1037}
Marissa Wall61c58622018-07-18 10:12:20 -07001038
Mathias Agopian13127d82013-03-05 17:47:11 -08001039bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001040 mDrawingState.sequence++;
1041 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001042 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001043 setTransactionFlags(eTransactionNeeded);
1044 return true;
1045}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001046
Lucas Dupinc3800b82020-10-02 16:24:48 -07001047bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001048 // If we start or stop drawing blur then the layer's visibility state may change so increment
1049 // the magic sequence number.
1050 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1051 mDrawingState.sequence++;
1052 }
Robert Carr6a160312021-05-17 12:08:20 -07001053 mDrawingState.blurRegions = blurRegions;
1054 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001055 setTransactionFlags(eTransactionNeeded);
1056 return true;
1057}
1058
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001059bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001060 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1061 if (mDrawingState.flags == newFlags) return false;
1062 mDrawingState.sequence++;
1063 mDrawingState.flags = newFlags;
1064 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001065 setTransactionFlags(eTransactionNeeded);
1066 return true;
1067}
Robert Carr99e27f02016-06-16 15:18:02 -07001068
chaviw25714502021-02-11 10:01:08 -08001069bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001070 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001071 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001072 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001073
Robert Carr6a160312021-05-17 12:08:20 -07001074 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001075 setTransactionFlags(eTransactionNeeded);
1076 return true;
1077}
Robert Carr8d5227b2017-03-16 15:41:03 -07001078
Evan Roskyef876c92019-01-25 17:46:06 -08001079bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001080 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1081 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001082 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001083 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001084}
1085
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001086bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001087 if (mDrawingState.layerStack == layerStack) return false;
1088 mDrawingState.sequence++;
1089 mDrawingState.layerStack = layerStack;
1090 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001091 setTransactionFlags(eTransactionNeeded);
1092 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001093}
1094
Peiyong Linc502cb72019-03-01 15:00:23 -08001095bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001096 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001097 return false;
1098 }
Robert Carr6a160312021-05-17 12:08:20 -07001099 mDrawingState.sequence++;
1100 mDrawingState.colorSpaceAgnostic = agnostic;
1101 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001102 setTransactionFlags(eTransactionNeeded);
1103 return true;
1104}
1105
Sally Qi81d95e62022-03-21 19:41:33 -07001106bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1107 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1108
1109 mDrawingState.sequence++;
1110 mDrawingState.dimmingEnabled = dimmingEnabled;
1111 mDrawingState.modified = true;
1112 setTransactionFlags(eTransactionNeeded);
1113 return true;
1114}
1115
Ana Krulecc84d09b2019-11-02 23:10:29 +01001116bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001117 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1118 mDrawingState.frameRateSelectionPriority = priority;
1119 mDrawingState.sequence++;
1120 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001121 setTransactionFlags(eTransactionNeeded);
1122 return true;
1123}
1124
1125int32_t Layer::getFrameRateSelectionPriority() const {
1126 // Check if layer has priority set.
1127 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1128 return mDrawingState.frameRateSelectionPriority;
1129 }
1130 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001131 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001132 if (parent != nullptr) {
1133 return parent->getFrameRateSelectionPriority();
1134 }
1135
1136 return Layer::PRIORITY_UNSET;
1137}
1138
Andy Labrada096227e2022-06-15 16:58:11 +00001139bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1140 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1141 mDrawingState.defaultFrameRateCompatibility = compatibility;
1142 mDrawingState.modified = true;
1143 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1144 setTransactionFlags(eTransactionNeeded);
1145 return true;
1146}
1147
1148scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1149 return mDrawingState.defaultFrameRateCompatibility;
1150}
1151
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001152bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1153 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1154};
1155
Vishnu Nair73908d12022-10-24 21:46:42 -07001156ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1157 bool useDrawing = state == LayerVector::StateSet::Drawing;
1158 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1159 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001160 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001161 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001162 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001163}
1164
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001165bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001166 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001167 return false;
1168 }
1169
Robert Carr6a160312021-05-17 12:08:20 -07001170 mDrawingState.sequence++;
1171 mDrawingState.shadowRadius = shadowRadius;
1172 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001173 setTransactionFlags(eTransactionNeeded);
1174 return true;
1175}
1176
Vishnu Nair6213bd92020-05-08 17:42:25 -07001177bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001178 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001179 return false;
1180 }
1181
Robert Carr6a160312021-05-17 12:08:20 -07001182 mDrawingState.sequence++;
1183 mDrawingState.fixedTransformHint = fixedTransformHint;
1184 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001185 setTransactionFlags(eTransactionNeeded);
1186 return true;
1187}
1188
John Reckcdb4ed72021-02-04 13:39:33 -05001189bool Layer::setStretchEffect(const StretchEffect& effect) {
1190 StretchEffect temp = effect;
1191 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001192 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001193 return false;
1194 }
Robert Carr6a160312021-05-17 12:08:20 -07001195 mDrawingState.sequence++;
1196 mDrawingState.stretchEffect = temp;
1197 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001198 setTransactionFlags(eTransactionNeeded);
1199 return true;
1200}
1201
John Reckc00c6692021-02-16 11:37:33 -05001202StretchEffect Layer::getStretchEffect() const {
1203 if (mDrawingState.stretchEffect.hasEffect()) {
1204 return mDrawingState.stretchEffect;
1205 }
1206
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001207 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001208 if (parent != nullptr) {
1209 auto effect = parent->getStretchEffect();
1210 if (effect.hasEffect()) {
1211 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1212 return effect;
1213 }
1214 }
1215 return StretchEffect{};
1216}
1217
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001218bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1219 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001220 return false;
1221 }
1222 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001223 mBorderWidth = width;
1224 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001225 return true;
1226}
1227
1228bool Layer::isBorderEnabled() {
1229 return mBorderEnabled;
1230}
1231
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001232float Layer::getBorderWidth() {
1233 return mBorderWidth;
1234}
1235
1236const half4& Layer::getBorderColor() {
1237 return mBorderColor;
1238}
1239
Ady Abrahama850c182021-08-04 13:04:37 -07001240bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1241 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1242 const auto frameRate = [&] {
1243 if (mDrawingState.frameRate.rate.isValid() ||
1244 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1245 return mDrawingState.frameRate;
1246 }
1247
1248 return parentFrameRate;
1249 }();
1250
1251 *transactionNeeded |= setFrameRateForLayerTree(frameRate);
1252
1253 // The frame rate is propagated to the children
1254 bool childrenHaveFrameRate = false;
1255 for (const sp<Layer>& child : mCurrentChildren) {
1256 childrenHaveFrameRate |=
1257 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1258 }
1259
1260 // If we don't have a valid frame rate, but the children do, we set this
1261 // layer as NoVote to allow the children to control the refresh rate
1262 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1263 childrenHaveFrameRate) {
1264 *transactionNeeded |=
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001265 setFrameRateForLayerTree(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001266 }
1267
1268 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1269 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001270 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001271 const auto layerVotedWithDefaultCompatibility =
1272 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1273 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1274 const auto layerVotedWithExactCompatibility =
1275 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1276 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1277 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1278}
1279
Ady Abraham60e42ea2020-03-09 19:17:31 -07001280void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001281 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001282 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001283 while (auto parent = layer->getParent()) {
1284 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001285 }
Ady Abrahama850c182021-08-04 13:04:37 -07001286 return layer;
1287 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001288
Ady Abraham60e42ea2020-03-09 19:17:31 -07001289 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001290 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001291
Ady Abrahama850c182021-08-04 13:04:37 -07001292 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001293 if (transactionNeeded) {
1294 mFlinger->setTransactionFlags(eTraversalNeeded);
1295 }
1296}
1297
Ady Abraham71c437d2020-01-31 15:56:57 -08001298bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001299 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001300 return false;
1301 }
1302
Robert Carr6a160312021-05-17 12:08:20 -07001303 mDrawingState.sequence++;
1304 mDrawingState.frameRate = frameRate;
1305 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001306
1307 updateTreeHasFrameRateVote();
1308
Steven Thomas3172e202020-01-06 19:25:30 -08001309 setTransactionFlags(eTransactionNeeded);
1310 return true;
1311}
1312
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001313void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1314 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001315 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001316
1317 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1318 // there are two transactions with the same token, the first one without a buffer and the
1319 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1320 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001321 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1322 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001323 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001324 mDrawingState.bufferSurfaceFrameTX = it->second;
1325 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1326 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1327 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001328 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001329 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001330 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1331 }
1332}
1333
1334void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1335 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001336 mDrawingState.frameTimelineInfo = info;
1337 mDrawingState.postTime = postTime;
1338 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001339 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001340
Robert Carr6a160312021-05-17 12:08:20 -07001341 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001342 bufferSurfaceFrameTX != nullptr) {
1343 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1344 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1345 // being used for BufferSurfaceFrame, don't create a new one.
1346 return;
1347 }
1348 }
1349 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1350 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1351 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001352 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1353 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001354 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001355 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001356 } else {
1357 if (it->second->getPresentState() == PresentState::Presented) {
1358 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1359 // have been from previous vsync.
1360 it->second = createSurfaceFrameForTransaction(info, postTime);
1361 }
1362 }
1363}
1364
1365void Layer::addSurfaceFrameDroppedForBuffer(
1366 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001367 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001368 surfaceFrame->setPresentState(PresentState::Dropped);
1369 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1370}
1371
1372void Layer::addSurfaceFramePresentedForBuffer(
1373 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1374 nsecs_t currentLatchTime) {
1375 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1376 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1377 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1378 mLastLatchTime = currentLatchTime;
1379}
1380
1381std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1382 const FrameTimelineInfo& info, nsecs_t postTime) {
1383 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001384 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1385 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001386 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001387 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001388 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001389 // For Transactions, the post time is considered to be both queue and acquire fence time.
1390 surfaceFrame->setActualQueueTime(postTime);
1391 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001392 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1393 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001394 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001395 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001396 onSurfaceFrameCreated(surfaceFrame);
1397 return surfaceFrame;
1398}
1399
1400std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1401 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1402 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001403 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001404 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001405 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001406 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001407 // For buffers, acquire fence time will set during latch.
1408 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001409 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1410 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001411 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001412 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001413 onSurfaceFrameCreated(surfaceFrame);
1414 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001415}
1416
Ady Abrahama850c182021-08-04 13:04:37 -07001417bool Layer::setFrameRateForLayerTree(FrameRate frameRate) {
1418 if (mDrawingState.frameRateForLayerTree == frameRate) {
1419 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001420 }
1421
Ady Abrahama850c182021-08-04 13:04:37 -07001422 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001423
Ady Abrahama850c182021-08-04 13:04:37 -07001424 // TODO(b/195668952): we probably don't need to dirty visible regions here
1425 // or even store frameRateForLayerTree in mDrawingState
1426 mDrawingState.sequence++;
1427 mDrawingState.modified = true;
1428 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001429
Dominik Laskowski068173d2021-08-11 17:22:59 -07001430 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
1431 mFlinger->mScheduler->recordLayerHistory(this, systemTime(), LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001432
1433 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001434}
1435
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001436Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1437 return getDrawingState().frameRateForLayerTree;
1438}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001439
Robert Carr1f0a16a2016-10-24 16:27:39 -07001440bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001441 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001442 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001443 if (parent != nullptr && parent->isHiddenByPolicy()) {
1444 return true;
1445 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001446 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1447 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1448 if (zOrderRelativeOf != nullptr) {
1449 if (zOrderRelativeOf->isHiddenByPolicy()) {
1450 return true;
1451 }
1452 }
1453 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001454 if (CC_UNLIKELY(!isTransformValid())) {
1455 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1456 return true;
1457 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001458 return s.flags & layer_state_t::eLayerHidden;
1459}
1460
David Sodman41fdfc92017-11-06 16:09:56 -08001461uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001462 // TODO: should we do something special if mSecure is set?
1463 if (mProtectedByApp) {
1464 // need a hardware-protected path to external video sink
1465 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001466 }
Riley Andrews03414a12014-07-01 14:22:59 -07001467 if (mPotentialCursor) {
1468 usage |= GraphicBuffer::USAGE_CURSOR;
1469 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001470 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001471 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001472}
1473
Vishnu Nair71fcf912022-10-18 09:14:20 -07001474void Layer::skipReportingTransformHint() {
1475 mSkipReportingTransformHint = true;
1476}
1477
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001478void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1479 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1480 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001481 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001482
Vishnu Nair6213bd92020-05-08 17:42:25 -07001483 setTransformHint(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001484}
1485
Mathias Agopian13127d82013-03-05 17:47:11 -08001486// ----------------------------------------------------------------------------
1487// debugging
1488// ----------------------------------------------------------------------------
1489
Marissa Wall61c58622018-07-18 10:12:20 -07001490// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001491gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001492 using namespace std::string_literals;
1493
Huihong Luo05539a12022-02-23 10:29:40 -08001494 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001495 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001496 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001497 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001498 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001499 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001500
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001501 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001502 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001503 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001504 info.mX = ds.transform.tx();
1505 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001506 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001507 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001508 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001509 info.mFlags = ds.flags;
1510 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001511 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001512 info.mMatrix[0][0] = ds.transform[0][0];
1513 info.mMatrix[0][1] = ds.transform[0][1];
1514 info.mMatrix[1][0] = ds.transform[1][0];
1515 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001516 {
chaviwd62d3062019-09-04 14:48:02 -07001517 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001518 if (buffer != 0) {
1519 info.mActiveBufferWidth = buffer->getWidth();
1520 info.mActiveBufferHeight = buffer->getHeight();
1521 info.mActiveBufferStride = buffer->getStride();
1522 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001523 } else {
1524 info.mActiveBufferWidth = 0;
1525 info.mActiveBufferHeight = 0;
1526 info.mActiveBufferStride = 0;
1527 info.mActiveBufferFormat = 0;
1528 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001529 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001530 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001531 info.mIsOpaque = isOpaque(ds);
1532 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001533 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001534 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001535}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001536
Yiwei Zhang5434a782018-12-05 18:06:32 -08001537void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001538 result.append(kDumpTableRowLength, '-');
1539 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001540 result.append(" Layer name\n");
1541 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001542 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001543 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001544 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001545 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001546 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001547 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1548 result.append(kDumpTableRowLength, '-');
1549 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001550}
1551
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001552void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1553 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001554 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001555 return;
1556 }
1557
Yiwei Zhang5434a782018-12-05 18:06:32 -08001558 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001559 if (mName.length() > 77) {
1560 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001561 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001562 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001563 shortened.append(mName, mName.length() - 36);
1564 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001565 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001566 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001567 }
1568
Yiwei Zhang5434a782018-12-05 18:06:32 -08001569 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001570
Alec Mourib416efd2018-09-06 21:01:59 +00001571 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001572 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001573
Chia-I Wu1e043612018-03-01 09:45:09 -08001574 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001575 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001576 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001577 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001578 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001579 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001580 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001581 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1582 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001583 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001584 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001585 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001586 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001587 const auto frameRate = getFrameRateForLayerTree();
1588 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1589 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001590 ftl::enum_string(frameRate.type).c_str(),
1591 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001592 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001593 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001594 }
Dan Stozae22aec72016-08-01 13:20:59 -07001595
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001596 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1597 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1598
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001599 result.append(kDumpTableRowLength, '-');
1600 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001601}
Dan Stozae22aec72016-08-01 13:20:59 -07001602
Yiwei Zhang5434a782018-12-05 18:06:32 -08001603void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001604 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001605}
1606
Svetoslavd85084b2014-03-20 10:28:31 -07001607void Layer::clearFrameStats() {
1608 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001609}
1610
Jamie Gennis6547ff42013-07-16 20:12:42 -07001611void Layer::logFrameStats() {
1612 mFrameTracker.logAndResetStats(mName);
1613}
1614
Svetoslavd85084b2014-03-20 10:28:31 -07001615void Layer::getFrameStats(FrameStats* outStats) const {
1616 mFrameTracker.getStats(outStats);
1617}
1618
Vishnu Nair76554eb2022-12-09 03:38:36 +00001619void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1620 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
1621 StringAppendF(&result, "Layer %s%s pid:%d uid:%d\n", getName().c_str(), hasBuffer.c_str(),
Vishnu Naircb8be502022-10-12 19:03:23 +00001622 mOwnerPid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001623}
1624
Brian Anderson5ea5e592016-12-01 16:54:33 -08001625void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001626 const int32_t layerId = getSequence();
1627 mFlinger->mTimeStats->onDestroy(layerId);
1628 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001629}
1630
Chia-I Wu98f1c102017-05-30 14:54:08 -07001631size_t Layer::getChildrenCount() const {
1632 size_t count = 0;
1633 for (const sp<Layer>& child : mCurrentChildren) {
1634 count += 1 + child->getChildrenCount();
1635 }
1636 return count;
1637}
1638
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001639void Layer::setGameModeForTree(GameMode gameMode) {
1640 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001641 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1642 gameMode =
1643 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001644 }
1645 setGameMode(gameMode);
1646 for (const sp<Layer>& child : mCurrentChildren) {
1647 child->setGameModeForTree(gameMode);
1648 }
1649}
1650
Robert Carr1f0a16a2016-10-24 16:27:39 -07001651void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001652 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001653 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001654
Robert Carr1f0a16a2016-10-24 16:27:39 -07001655 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001656 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001657 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001658 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001659}
1660
1661ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001662 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001663 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001664
Robert Carr1323c952019-01-28 18:13:27 -08001665 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001666 const auto removeResult = mCurrentChildren.remove(layer);
1667
1668 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001669 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001670 layer->updateTreeHasFrameRateVote();
1671
1672 return removeResult;
1673}
1674
Robert Carr15eae092018-03-23 13:43:53 -07001675void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001676 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001677 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001678 const float parentShadowRadius =
1679 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001680 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001681 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001682 }
1683}
1684
chaviwf1961f72017-09-18 16:41:07 -07001685bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001686 sp<Layer> newParent;
1687 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001688 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001689 if (newParent == nullptr) {
1690 ALOGE("Unable to promote Layer handle");
1691 return false;
1692 }
1693 if (newParent == this) {
1694 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1695 return false;
1696 }
1697 }
1698
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001699 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001700 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001701 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001702 }
1703
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001704 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001705 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001706 if (!newParent->isRemovedFromCurrentState()) {
1707 addToCurrentState();
1708 } else {
1709 onRemovedFromCurrentState();
1710 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001711 } else {
1712 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001713 }
1714
chaviw06178942017-07-27 10:25:59 -07001715 return true;
1716}
1717
Peiyong Lind3788632018-09-18 16:01:31 -07001718bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001719 static const mat4 identityMatrix = mat4();
1720
Robert Carr6a160312021-05-17 12:08:20 -07001721 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001722 return false;
1723 }
Robert Carr6a160312021-05-17 12:08:20 -07001724 ++mDrawingState.sequence;
1725 mDrawingState.colorTransform = matrix;
1726 mDrawingState.hasColorTransform = matrix != identityMatrix;
1727 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001728 setTransactionFlags(eTransactionNeeded);
1729 return true;
1730}
1731
chaviwf66724d2018-11-28 16:35:21 -08001732mat4 Layer::getColorTransform() const {
1733 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001734 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001735 colorTransform = parent->getColorTransform() * colorTransform;
1736 }
1737 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001738}
1739
1740bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001741 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001742 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001743 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1744 }
1745 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001746}
1747
Chia-I Wu11481472018-05-04 10:43:19 -07001748bool Layer::isLegacyDataSpace() const {
1749 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001750 return !(getDataSpace() &
1751 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1752 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001753}
1754
Robert Carr1f0a16a2016-10-24 16:27:39 -07001755void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001756 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001757}
1758
Robert Carr6a160312021-05-17 12:08:20 -07001759int32_t Layer::getZ(LayerVector::StateSet) const {
1760 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001761}
1762
Robert Carr1c5481e2019-07-01 14:42:27 -07001763bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001764 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001765 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001766 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001767}
1768
David Sodman41fdfc92017-11-06 16:09:56 -08001769__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001770 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001771 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1772 "makeTraversalList received invalid stateSet");
1773 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1774 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001775 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001776
Robert Carr29abff82017-12-04 13:51:20 -08001777 if (state.zOrderRelatives.size() == 0) {
1778 *outSkipRelativeZUsers = true;
1779 return children;
1780 }
1781
chaviwfd462612018-05-31 16:11:27 -07001782 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001783 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001784 sp<Layer> strongRelative = weakRelative.promote();
1785 if (strongRelative != nullptr) {
1786 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001787 }
1788 }
1789
Dan Stoza412903f2017-04-27 13:42:17 -07001790 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001791 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001792 continue;
1793 }
Robert Carrdb66e622017-04-10 16:55:57 -07001794 traverse.add(child);
1795 }
1796
1797 return traverse;
1798}
1799
Robert Carr1f0a16a2016-10-24 16:27:39 -07001800/**
Robert Carrdb66e622017-04-10 16:55:57 -07001801 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001802 */
Dan Stoza412903f2017-04-27 13:42:17 -07001803void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001804 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1805 // produce a new list for traversing, including our relatives, and not including our children
1806 // who are relatives of another surface. In the case that there are no relative Z,
1807 // makeTraversalList returns our children directly to avoid significant overhead.
1808 // However in this case we need to take the responsibility for filtering children which
1809 // are relatives of another surface here.
1810 bool skipRelativeZUsers = false;
1811 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001812
Robert Carr1f0a16a2016-10-24 16:27:39 -07001813 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001814 for (; i < list.size(); i++) {
1815 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001816 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1817 continue;
1818 }
1819
chaviw301b1d82019-11-06 13:15:09 -08001820 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001821 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001822 }
Dan Stoza412903f2017-04-27 13:42:17 -07001823 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001824 }
Robert Carr29abff82017-12-04 13:51:20 -08001825
Dan Stoza412903f2017-04-27 13:42:17 -07001826 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001827 for (; i < list.size(); i++) {
1828 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001829
Robert Carr29abff82017-12-04 13:51:20 -08001830 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1831 continue;
1832 }
Dan Stoza412903f2017-04-27 13:42:17 -07001833 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001834 }
1835}
1836
1837/**
Robert Carrdb66e622017-04-10 16:55:57 -07001838 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001839 */
Dan Stoza412903f2017-04-27 13:42:17 -07001840void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1841 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001842 // See traverseInZOrder for documentation.
1843 bool skipRelativeZUsers = false;
1844 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001845
Robert Carr1f0a16a2016-10-24 16:27:39 -07001846 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001847 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001848 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001849
1850 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1851 continue;
1852 }
1853
chaviw301b1d82019-11-06 13:15:09 -08001854 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001855 break;
1856 }
Dan Stoza412903f2017-04-27 13:42:17 -07001857 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001858 }
Dan Stoza412903f2017-04-27 13:42:17 -07001859 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001860 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001861 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001862
1863 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1864 continue;
1865 }
1866
Dan Stoza412903f2017-04-27 13:42:17 -07001867 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001868 }
1869}
1870
Edgar Arriaga844fa672020-01-16 14:21:42 -08001871void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1872 visitor(this);
1873 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001874 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001875 for (const sp<Layer>& child : children) {
1876 child->traverse(state, visitor);
1877 }
1878}
1879
chaviw4b129c22018-04-09 16:19:43 -07001880LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1881 const std::vector<Layer*>& layersInTree) {
1882 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1883 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001884 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1885 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001886 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001887
chaviwfd462612018-05-31 16:11:27 -07001888 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001889 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1890 sp<Layer> strongRelative = weakRelative.promote();
1891 // Only add relative layers that are also descendents of the top most parent of the tree.
1892 // If a relative layer is not a descendent, then it should be ignored.
1893 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1894 traverse.add(strongRelative);
1895 }
1896 }
1897
1898 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001899 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001900 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1901 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1902 // the child here since it won't be added later as a relative.
1903 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1904 childState.zOrderRelativeOf.promote().get())) {
1905 continue;
1906 }
1907 traverse.add(child);
1908 }
1909
1910 return traverse;
1911}
1912
1913void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1914 LayerVector::StateSet stateSet,
1915 const LayerVector::Visitor& visitor) {
1916 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001917
1918 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001919 for (; i < list.size(); i++) {
1920 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001921 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001922 break;
1923 }
chaviw4b129c22018-04-09 16:19:43 -07001924 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001925 }
chaviw4b129c22018-04-09 16:19:43 -07001926
chaviwa76b2712017-09-20 12:02:26 -07001927 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001928 for (; i < list.size(); i++) {
1929 const auto& relative = list[i];
1930 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001931 }
1932}
1933
chaviw4b129c22018-04-09 16:19:43 -07001934std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1935 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1936 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1937
1938 std::vector<Layer*> layersInTree = {this};
1939 for (size_t i = 0; i < children.size(); i++) {
1940 const auto& child = children[i];
1941 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1942 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1943 }
1944
1945 return layersInTree;
1946}
1947
1948void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1949 const LayerVector::Visitor& visitor) {
1950 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1951 std::sort(layersInTree.begin(), layersInTree.end());
1952 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1953}
1954
Peiyong Linefefaac2018-08-17 12:27:51 -07001955ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001956 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001957}
1958
Garfield Tan2c1782c2022-02-16 15:25:05 -08001959bool Layer::isTransformValid() const {
1960 float transformDet = getTransform().det();
1961 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1962}
1963
chaviw13fdc492017-06-27 12:40:18 -07001964half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001965 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001966
chaviw13fdc492017-06-27 12:40:18 -07001967 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1968 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07001969}
Robert Carr6452f122017-03-21 10:41:29 -07001970
Vishnu Nair6213bd92020-05-08 17:42:25 -07001971ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07001972 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001973 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
1974 return fixedTransformHint;
1975 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001976 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07001977 if (!p) return fixedTransformHint;
1978 return p->getFixedTransformHint();
1979}
1980
chaviw13fdc492017-06-27 12:40:18 -07001981half4 Layer::getColor() const {
1982 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001983 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07001984}
Robert Carr6452f122017-03-21 10:41:29 -07001985
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001986int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00001987 if (getDrawingState().backgroundBlurRadius == 0) {
1988 return 0;
1989 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01001990
Vishnu Nair29810f72022-07-01 16:38:41 +00001991 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01001992 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1993 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001994}
1995
Galia Peychevae0acf382021-04-12 21:22:34 +02001996const std::vector<BlurRegion> Layer::getBlurRegions() const {
1997 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02001998 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02001999 for (auto& region : regionsCopy) {
2000 region.alpha = region.alpha * layerAlpha;
2001 }
2002 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002003}
2004
Vishnu Naire14c6b32022-08-06 04:20:15 +00002005RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002006 // Get parent settings
2007 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002008 const auto& parent = mDrawingParent.promote();
2009 if (parent != nullptr) {
2010 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002011 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002012 ui::Transform t = getActiveTransform(getDrawingState());
2013 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002014 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002015 parentSettings.radius.x *= t.getScaleX();
2016 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002017 }
2018 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002019
2020 // Get layer settings
2021 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002022 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002023 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002024 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002025
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002026 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002027 // If the parent and the layer have rounded corner settings, use the parent settings if the
2028 // parent crop is entirely inside the layer crop.
2029 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2030 if (parentSettings.cropRect.left > layerCropRect.left &&
2031 parentSettings.cropRect.top > layerCropRect.top &&
2032 parentSettings.cropRect.right < layerCropRect.right &&
2033 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2034 return parentSettings;
2035 } else {
2036 return layerSettings;
2037 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002038 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002039 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002040 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002041 return parentSettings;
2042 }
2043 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002044}
2045
Robert Carr88b85e12022-03-21 15:47:35 -07002046bool Layer::findInHierarchy(const sp<Layer>& l) {
2047 if (l == this) {
2048 return true;
2049 }
2050 for (auto& child : mDrawingChildren) {
2051 if (child->findInHierarchy(l)) {
2052 return true;
2053 }
2054 }
2055 return false;
2056}
2057
Robert Carr1f0a16a2016-10-24 16:27:39 -07002058void Layer::commitChildList() {
2059 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2060 const auto& child = mCurrentChildren[i];
2061 child->commitChildList();
2062 }
2063 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002064 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002065 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2066 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2067 if (zOrderRelativeOf == nullptr) return;
2068 if (findInHierarchy(zOrderRelativeOf)) {
2069 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2070 zOrderRelativeOf->mName.c_str());
2071 ALOGE("Severing rel Z loop, potentially dangerous");
2072 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002073 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002074 }
2075 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002076}
2077
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002078
chaviw3277faf2021-05-19 16:45:23 -05002079void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002080 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002081 mDrawingState.touchableRegionCrop =
2082 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002083 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002084 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002085 setTransactionFlags(eTransactionNeeded);
2086}
2087
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002088LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002089 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002090 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002091 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2092
Vishnu Nair00b90132021-11-05 14:03:40 -07002093 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002094 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2095
Vishnu Nair60db8c02020-04-02 11:55:16 -07002096 // Only populate for the primary display.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002097 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -05002098 const auto compositionType = getCompositionType(*display);
Vishnu Nair60db8c02020-04-02 11:55:16 -07002099 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002100 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2101 [&]() { return layerProto->mutable_visible_region(); });
Vishnu Nair60db8c02020-04-02 11:55:16 -07002102 }
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 Naird8f5e9f2022-02-03 10:23:28 -08002112void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002113 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002114 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002115 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002116 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002117 [&]() { return layerInfo->mutable_active_buffer(); });
2118 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2119 layerInfo->mutable_buffer_transform());
2120 }
2121 layerInfo->set_invalidate(contentDirty);
2122 layerInfo->set_is_protected(isProtected());
2123 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2124 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002125 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002126 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002127 layerInfo->set_corner_radius(
2128 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002129 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2130 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2131 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2132 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2133 [&]() { return layerInfo->mutable_position(); });
2134 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002135 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2136 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002137
Vishnu Nair00b90132021-11-05 14:03:40 -07002138 if (hasColorTransform()) {
2139 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002140 }
2141
Vishnu Nair60db8c02020-04-02 11:55:16 -07002142 LayerProtoHelper::writeToProto(mSourceBounds,
2143 [&]() { return layerInfo->mutable_source_bounds(); });
2144 LayerProtoHelper::writeToProto(mScreenBounds,
2145 [&]() { return layerInfo->mutable_screen_bounds(); });
2146 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2147 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2148 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002149}
2150
2151void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002152 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002153 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2154 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002155 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002156
chaviw766c9c52021-02-10 17:36:47 -08002157 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002158
Vishnu Nair00b90132021-11-05 14:03:40 -07002159 layerInfo->set_id(sequence);
2160 layerInfo->set_name(getName().c_str());
2161 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002162
Vishnu Nair00b90132021-11-05 14:03:40 -07002163 for (const auto& child : children) {
2164 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002165 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002166
Vishnu Nair00b90132021-11-05 14:03:40 -07002167 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2168 sp<Layer> strongRelative = weakRelative.promote();
2169 if (strongRelative != nullptr) {
2170 layerInfo->add_relatives(strongRelative->sequence);
2171 }
2172 }
2173
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002174 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002175 [&]() { return layerInfo->mutable_transparent_region(); });
2176
2177 layerInfo->set_layer_stack(getLayerStack().id);
2178 layerInfo->set_z(state.z);
2179
2180 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2181 return layerInfo->mutable_requested_position();
2182 });
2183
Vishnu Nair00b90132021-11-05 14:03:40 -07002184 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2185
2186 layerInfo->set_is_opaque(isOpaque(state));
2187
2188 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2189 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2190 LayerProtoHelper::writeToProto(state.color,
2191 [&]() { return layerInfo->mutable_requested_color(); });
2192 layerInfo->set_flags(state.flags);
2193
2194 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2195 layerInfo->mutable_requested_transform());
2196
2197 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2198 if (parent != nullptr) {
2199 layerInfo->set_parent(parent->sequence);
2200 } else {
2201 layerInfo->set_parent(-1);
2202 }
2203
2204 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2205 if (zOrderRelativeOf != nullptr) {
2206 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2207 } else {
2208 layerInfo->set_z_order_relative_of(-1);
2209 }
2210
2211 layerInfo->set_is_relative_of(state.isRelativeOf);
2212
2213 layerInfo->set_owner_uid(mOwnerUid);
2214
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002215 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002216 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002217 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002218 info = fillInputInfo(
2219 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002220 } else {
2221 info = state.inputInfo;
2222 }
2223
2224 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002225 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002226 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002227
Vishnu Nair00b90132021-11-05 14:03:40 -07002228 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002229 auto protoMap = layerInfo->mutable_metadata();
2230 for (const auto& entry : state.metadata.mMap) {
2231 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2232 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002233 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002234
2235 LayerProtoHelper::writeToProto(state.destinationFrame,
2236 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002237}
2238
Robert Carr2e102c92018-10-23 12:11:15 -07002239bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002240 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002241}
2242
Prabir Pradhan33da9462022-06-14 14:55:57 +00002243// Applies the given transform to the region, while protecting against overflows caused by any
2244// offsets. If applying the offset in the transform to any of the Rects in the region would result
2245// in an overflow, they are not added to the output Region.
2246static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2247 const std::string& debugWindowName) {
2248 // Round the translation using the same rounding strategy used by ui::Transform.
2249 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2250 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2251
2252 ui::Transform transformWithoutOffset = t;
2253 transformWithoutOffset.set(0.f, 0.f);
2254
2255 const Region transformed = transformWithoutOffset.transform(r);
2256
2257 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2258 Region ret;
2259 for (const auto& rect : transformed) {
2260 Rect newRect;
2261 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2262 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2263 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2264 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2265 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2266 debugWindowName.c_str());
2267 continue;
2268 }
2269 ret.orSelf(newRect);
2270 }
2271 return ret;
2272}
2273
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002274void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
2275 Rect tmpBounds = getInputBounds();
2276 if (!tmpBounds.isValid()) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002277 info.touchableRegion.clear();
2278 // A layer could have invalid input bounds and still expect to receive touch input if it has
2279 // replaceTouchableRegionWithCrop. For that case, the input transform needs to be calculated
2280 // correctly to determine the coordinate space for input events. Use an empty rect so that
2281 // the layer will receive input in its own layer space.
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002282 tmpBounds = Rect::EMPTY_RECT;
chaviw7e72caf2020-12-02 16:50:43 -08002283 }
2284
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002285 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2286 // frame and transform used for the layer, which determines the bounds and the coordinate space
2287 // within which the layer will receive input.
2288 //
2289 // The coordinate space within which each of the bounds are specified is explicitly documented
2290 // in the variable name. For example "inputBoundsInLayer" is specified in layer space. A
2291 // Transform converts one coordinate space to another, which is apparent in its naming. For
2292 // example, "layerToDisplay" transforms layer space to display space.
2293 //
2294 // Coordinate space definitions:
2295 // - display: The display device's coordinate space. Correlates to pixels on the display.
2296 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2297 // - layer: The coordinate space of this layer.
2298 // - input: The coordinate space in which this layer will receive input events. This could be
2299 // different than layer space if a surfaceInset is used, which changes the origin
2300 // of the input space.
2301 const FloatRect inputBoundsInLayer = tmpBounds.toFloatRect();
chaviw7e72caf2020-12-02 16:50:43 -08002302
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002303 // Clamp surface inset to the input bounds.
2304 const auto surfaceInset = static_cast<float>(info.surfaceInset);
2305 const float xSurfaceInset =
2306 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getWidth() / 2.f));
2307 const float ySurfaceInset =
2308 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getHeight() / 2.f));
chaviw1ff3d1e2020-07-01 15:53:47 -07002309
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002310 // Apply the insets to the input bounds.
2311 const FloatRect insetBoundsInLayer(inputBoundsInLayer.left + xSurfaceInset,
2312 inputBoundsInLayer.top + ySurfaceInset,
2313 inputBoundsInLayer.right - xSurfaceInset,
2314 inputBoundsInLayer.bottom - ySurfaceInset);
Ady Abraham282f1d72019-07-24 18:05:56 -07002315
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002316 // Crop the input bounds to ensure it is within the parent's bounds.
2317 const FloatRect croppedInsetBoundsInLayer = mBounds.intersect(insetBoundsInLayer);
Ady Abraham282f1d72019-07-24 18:05:56 -07002318
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002319 const ui::Transform layerToScreen = getInputTransform();
2320 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
Vishnu Nair8033a492018-12-05 07:27:23 -08002321
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002322 const Rect roundedFrameInDisplay{layerToDisplay.transform(croppedInsetBoundsInLayer)};
2323 info.frameLeft = roundedFrameInDisplay.left;
2324 info.frameTop = roundedFrameInDisplay.top;
2325 info.frameRight = roundedFrameInDisplay.right;
2326 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002327
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002328 ui::Transform inputToLayer;
2329 inputToLayer.set(insetBoundsInLayer.left, insetBoundsInLayer.top);
2330 const ui::Transform inputToDisplay = layerToDisplay * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002331
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002332 // InputDispatcher expects a display-to-input transform.
2333 info.transform = inputToDisplay.inverse();
2334
2335 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002336 info.touchableRegion =
2337 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002338}
2339
chaviw3277faf2021-05-19 16:45:23 -05002340void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002341 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002342 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002343 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002344 }
2345 if (p != nullptr) {
2346 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2347 }
2348}
2349
Vishnu Naira066d902021-09-13 18:40:17 -07002350gui::DropInputMode Layer::getDropInputMode() const {
2351 gui::DropInputMode mode = mDrawingState.dropInputMode;
2352 if (mode == gui::DropInputMode::ALL) {
2353 return mode;
2354 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002355 sp<Layer> parent = mDrawingParent.promote();
2356 if (parent) {
2357 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002358 if (parentMode != gui::DropInputMode::NONE) {
2359 return parentMode;
2360 }
2361 }
2362 return mode;
2363}
2364
2365void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002366 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002367 return;
2368 }
2369
2370 // Check if we need to drop input unconditionally
2371 gui::DropInputMode dropInputMode = getDropInputMode();
2372 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002373 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002374 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2375 return;
2376 }
2377
2378 // Check if we need to check if the window is obscured by parent
2379 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2380 return;
2381 }
2382
2383 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002384 sp<Layer> parent = mDrawingParent.promote();
2385 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002386 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002387 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2388 static_cast<float>(getAlpha()));
2389 }
2390
2391 // Check if the parent has cropped the buffer
2392 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2393 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002394 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002395 return;
2396 }
2397
2398 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2399 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2400 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2401 // match then the layer has not been cropped by its parents.
2402 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2403 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2404
2405 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002406 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002407 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2408 getDebugName());
2409 } else {
2410 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2411 // input if the window is obscured. This check should be done in surfaceflinger but the
2412 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2413 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002414 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002415 }
2416}
2417
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002418WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002419 if (!hasInputInfo()) {
2420 mDrawingState.inputInfo.name = getName();
2421 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2422 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002423 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002424 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002425 }
2426
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002427 const ui::Transform& displayTransform =
2428 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2429
chaviw3277faf2021-05-19 16:45:23 -05002430 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002431 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002432 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002433
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002434 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002435
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002436 if (displayArgs.transform == nullptr) {
2437 // Do not let the window receive touches if it is not associated with a valid display
2438 // transform. We still allow the window to receive keys and prevent ANRs.
2439 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2440 }
2441
Robert Carr5dc426e2020-06-10 14:29:14 -07002442 // For compatibility reasons we let layers which can receive input
2443 // receive input before they have actually submitted a buffer. Because
2444 // of this we use canReceiveInput instead of isVisible to check the
2445 // policy-visibility, ignoring the buffer state. However for layers with
2446 // hasInputInfo()==false we can use the real visibility state.
2447 // We are just using these layers for occlusion detection in
2448 // InputDispatcher, and obviously if they aren't visible they can't occlude
2449 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002450 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2451 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2452
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002453 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002454 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002455 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002456
Vishnu Nair16a938f2021-09-24 07:14:54 -07002457 // If the window will be blacked out on a display because the display does not have the secure
2458 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002459 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002460 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002461 }
2462
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002463 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2464 if (info.replaceTouchableRegionWithCrop) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002465 const Rect bounds(cropLayer ? cropLayer->mScreenBounds : mScreenBounds);
2466 info.touchableRegion = Region(displayTransform.transform(bounds));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002467 } else if (cropLayer != nullptr) {
[1;3C2b9fc252021-02-04 16:16:50 -08002468 info.touchableRegion = info.touchableRegion.intersect(
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002469 displayTransform.transform(Rect{cropLayer->mScreenBounds}));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002470 }
2471
Winson Chunga30f7c92021-06-29 15:42:56 -07002472 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2473 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002474 if (isTrustedOverlay()) {
2475 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2476 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002477
chaviwaf87b3e2019-10-01 16:59:28 -07002478 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2479 // touches from going outside the cloned area.
2480 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002481 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002482 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2483 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002484 info.touchableRegion = info.touchableRegion.intersect(rect);
2485 }
2486 }
2487
Robert Carr720e5062018-07-30 17:45:14 -07002488 return info;
2489}
2490
chaviwaf87b3e2019-10-01 16:59:28 -07002491sp<Layer> Layer::getClonedRoot() {
2492 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002493 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002494 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002495 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002496 return nullptr;
2497 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002498 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002499}
2500
Robert Carredd13602020-04-13 17:24:34 -07002501bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002502 return mDrawingState.inputInfo.token != nullptr ||
2503 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002504}
2505
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002506compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002507 const DisplayDevice* display) const {
2508 if (!display) return nullptr;
Lloyd Piquede196652020-01-22 17:29:58 -08002509 return display->getCompositionDisplay()->getOutputLayerForLayer(getCompositionEngineLayerFE());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002510}
2511
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002512Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2513 const auto outputLayer = findOutputLayerForDisplay(display);
2514 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002515}
2516
chaviwb4c6e582019-08-16 14:35:07 -07002517void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002518 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002519 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002520 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2521 mPotentialCursor = clonedFrom->mPotentialCursor;
2522 mProtectedByApp = clonedFrom->mProtectedByApp;
2523 updateCloneBufferInfo();
2524}
2525
2526void Layer::updateCloneBufferInfo() {
2527 if (!isClone() || !isClonedFromAlive()) {
2528 return;
2529 }
2530
2531 sp<Layer> clonedFrom = getClonedFrom();
2532 mBufferInfo = clonedFrom->mBufferInfo;
2533 mSidebandStream = clonedFrom->mSidebandStream;
2534 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2535 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2536 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2537
2538 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2539 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2540 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2541 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2542 // the cloned drawingState again.
2543 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2544 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2545 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2546 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2547
2548 cloneDrawingState(clonedFrom.get());
2549
2550 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2551 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2552 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2553 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002554}
chaviw74b03172019-08-19 11:09:03 -07002555
2556void Layer::updateMirrorInfo() {
2557 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2558 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2559 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2560 // that case, we want to delete the reference to the clone since we want it to get
2561 // destroyed. The root, this layer, will still be around since the client can continue
2562 // to hold a reference, but no cloned layers will be displayed.
2563 mClonedChild = nullptr;
2564 return;
2565 }
2566
2567 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2568 // If the real layer exists and is in current state, add the clone as a child of the root.
2569 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2570 // copied to drawingState for the root layer. So the clonedChild is always removed from
2571 // drawingState and then needs to be added back each traversal.
2572 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2573 addChildToDrawing(mClonedChild);
2574 }
2575
2576 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002577 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002578 mClonedChild->updateClonedRelatives(clonedLayersMap);
2579}
2580
2581void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2582 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2583 // to the clone. If the real layer is no longer alive, continue traversing the children
2584 // since we may be able to pull out other children that are still alive.
2585 if (isClonedFromAlive()) {
2586 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002587 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002588 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002589 }
2590
2591 // The clone layer may have children in drawingState since they may have been created and
2592 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2593 // that already exist, since we can just re-use them.
2594 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2595 // not updated in the regular traversal. They are skipped since the root will lose the
2596 // reference to them when it copies its currentChildren to drawing.
2597 for (sp<Layer>& child : mDrawingChildren) {
2598 child->updateClonedDrawingState(clonedLayersMap);
2599 }
2600}
2601
2602void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2603 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2604 mDrawingChildren.clear();
2605
2606 if (!isClonedFromAlive()) {
2607 return;
2608 }
2609
2610 sp<Layer> clonedFrom = getClonedFrom();
2611 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2612 if (child == mirrorRoot) {
2613 // This is to avoid cyclical mirroring.
2614 continue;
2615 }
2616 sp<Layer> clonedChild = clonedLayersMap[child];
2617 if (clonedChild == nullptr) {
2618 clonedChild = child->createClone();
2619 clonedLayersMap[child] = clonedChild;
2620 }
2621 addChildToDrawing(clonedChild);
2622 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2623 }
2624}
2625
chaviwaf87b3e2019-10-01 16:59:28 -07002626void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2627 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2628 if (cropLayer != nullptr) {
2629 if (clonedLayersMap.count(cropLayer) == 0) {
2630 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2631 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002632 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002633 } else {
2634 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2635 mDrawingState.touchableRegionCrop = clonedCropLayer;
2636 }
2637 }
2638 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2639 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002640 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002641}
2642
2643void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002644 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002645 mDrawingState.zOrderRelatives.clear();
2646
2647 if (!isClonedFromAlive()) {
2648 return;
2649 }
2650
chaviwaf87b3e2019-10-01 16:59:28 -07002651 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002652 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002653 const sp<Layer>& relative = relativeWeak.promote();
2654 if (clonedLayersMap.count(relative) > 0) {
2655 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002656 mDrawingState.zOrderRelatives.add(clonedRelative);
2657 }
2658 }
2659
2660 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2661 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2662 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2663 // still traverse the children, but the layer with the missing relativeOf will not be shown
2664 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002665 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2666 if (clonedLayersMap.count(relativeOf) > 0) {
2667 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002668 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2669 }
2670
chaviwaf87b3e2019-10-01 16:59:28 -07002671 updateClonedInputInfo(clonedLayersMap);
2672
chaviw74b03172019-08-19 11:09:03 -07002673 for (sp<Layer>& child : mDrawingChildren) {
2674 child->updateClonedRelatives(clonedLayersMap);
2675 }
2676}
2677
2678void Layer::addChildToDrawing(const sp<Layer>& layer) {
2679 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002680 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002681}
2682
Steven Thomas62a4cf82020-01-31 12:04:03 -08002683Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2684 switch (compatibility) {
2685 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2686 return FrameRateCompatibility::Default;
2687 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2688 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002689 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2690 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002691 case ANATIVEWINDOW_FRAME_RATE_MIN:
2692 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002693 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2694 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002695 default:
2696 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2697 return FrameRateCompatibility::Default;
2698 }
2699}
2700
Marin Shalamanovc5986772021-03-16 16:09:49 +01002701scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2702 switch (strategy) {
2703 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2704 return Seamlessness::OnlySeamless;
2705 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2706 return Seamlessness::SeamedAndSeamless;
2707 default:
2708 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2709 return Seamlessness::Default;
2710 }
2711}
2712
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002713bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002714 const State& s(mDrawingState);
2715 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2716 return true;
2717 }
2718
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002719 sp<Layer> parent = mDrawingParent.promote();
2720 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002721}
2722
Robert Carr6a0382d2021-07-01 15:57:17 -07002723void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2724 mClonedChild = clonedChild;
2725 mHadClonedChild = true;
2726 mFlinger->mNumClones++;
2727}
2728
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002729bool Layer::setDropInputMode(gui::DropInputMode mode) {
2730 if (mDrawingState.dropInputMode == mode) {
2731 return false;
2732 }
2733 mDrawingState.dropInputMode = mode;
2734 return true;
2735}
2736
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002737void Layer::cloneDrawingState(const Layer* from) {
2738 mDrawingState = from->mDrawingState;
2739 // Skip callback info since they are not applicable for cloned layers.
2740 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002741 // TODO (b/238781169) currently broken for mirror layers because we do not
2742 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002743 mDrawingState.callbackHandles = {};
2744}
2745
Patrick Williamsbb25f802022-08-30 23:02:34 +00002746void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2747 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
2748 const sp<Fence>& releaseFence,
2749 uint32_t currentMaxAcquiredBufferCount) {
2750 if (!listener) {
2751 return;
2752 }
2753 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002754 listener->onReleaseBuffer({buffer->getId(), framenumber},
2755 releaseFence ? releaseFence : Fence::NO_FENCE,
2756 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002757}
2758
2759void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2760 // If we are displayed on multiple displays in a single composition cycle then we would
2761 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2762 // For example we can only use it if all the displays are client comp, and we need
2763 // to merge all the client comp fences. We could do this, but for now we just
2764 // disable the optimization when a layer is composed on multiple displays.
2765 if (mClearClientCompositionFenceOnLayerDisplayed) {
2766 mLastClientCompositionFence = nullptr;
2767 } else {
2768 mClearClientCompositionFenceOnLayerDisplayed = true;
2769 }
2770
2771 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2772 // buffer that was presented on this layer. The first transaction that came in this frame that
2773 // replaced the previous buffer on this layer needs this release fence, because the fence will
2774 // let the client know when that previous buffer is removed from the screen.
2775 //
2776 // Every other transaction on this layer does not need a release fence because no other
2777 // Transactions that were set on this layer this frame are going to have their preceding buffer
2778 // removed from the display this frame.
2779 //
2780 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2781 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2782 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2783 // the previous buffer will be released this frame. The third transaction also contains a
2784 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2785 // transaction will now no longer be presented so it is released immediately and the third
2786 // transaction doesn't need a previous release fence.
2787 sp<CallbackHandle> ch;
2788 for (auto& handle : mDrawingState.callbackHandles) {
2789 if (handle->releasePreviousBuffer &&
2790 mDrawingState.releaseBufferEndpoint == handle->listener) {
2791 ch = handle;
2792 break;
2793 }
2794 }
2795
2796 // Prevent tracing the same release multiple times.
2797 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2798 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2799 }
2800
2801 if (ch != nullptr) {
2802 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2803 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2804 ch->name = mName;
2805 }
2806}
2807
2808void Layer::onSurfaceFrameCreated(
2809 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2810 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2811 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2812 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2813 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002814 if (hasBufferOrSidebandStreamInDrawing()) {
2815 // Only log for layers with a buffer, since we expect the jank data to be drained for
2816 // these, while there may be no jank listeners for bufferless layers.
2817 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2818 mName.c_str());
2819 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2820 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2821 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002822 mPendingJankClassifications.pop_front();
2823 }
2824 mPendingJankClassifications.emplace_back(surfaceFrame);
2825}
2826
2827void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2828 for (const auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair71fcf912022-10-18 09:14:20 -07002829 handle->transformHint = mSkipReportingTransformHint
2830 ? std::nullopt
2831 : std::make_optional<uint32_t>(mTransformHint);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002832 handle->dequeueReadyTime = dequeueReadyTime;
2833 handle->currentMaxAcquiredBufferCount =
2834 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2835 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2836 handle->previousReleaseCallbackId.framenumber);
2837 }
2838
2839 for (auto& handle : mDrawingState.callbackHandles) {
2840 if (handle->releasePreviousBuffer &&
2841 mDrawingState.releaseBufferEndpoint == handle->listener) {
2842 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2843 break;
2844 }
2845 }
2846
2847 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002848 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002849 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2850 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002851 mDrawingState.callbackHandles = {};
2852}
2853
2854bool Layer::willPresentCurrentTransaction() const {
2855 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2856 return (getSidebandStreamChanged() || getAutoRefresh() ||
2857 (mDrawingState.modified &&
2858 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2859}
2860
2861bool Layer::setTransform(uint32_t transform) {
2862 if (mDrawingState.bufferTransform == transform) return false;
2863 mDrawingState.bufferTransform = transform;
2864 mDrawingState.modified = true;
2865 setTransactionFlags(eTransactionNeeded);
2866 return true;
2867}
2868
2869bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2870 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2871 mDrawingState.sequence++;
2872 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2873 mDrawingState.modified = true;
2874 setTransactionFlags(eTransactionNeeded);
2875 return true;
2876}
2877
2878bool Layer::setBufferCrop(const Rect& bufferCrop) {
2879 if (mDrawingState.bufferCrop == bufferCrop) return false;
2880
2881 mDrawingState.sequence++;
2882 mDrawingState.bufferCrop = bufferCrop;
2883
2884 mDrawingState.modified = true;
2885 setTransactionFlags(eTransactionNeeded);
2886 return true;
2887}
2888
2889bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2890 if (mDrawingState.destinationFrame == destinationFrame) return false;
2891
2892 mDrawingState.sequence++;
2893 mDrawingState.destinationFrame = destinationFrame;
2894
2895 mDrawingState.modified = true;
2896 setTransactionFlags(eTransactionNeeded);
2897 return true;
2898}
2899
2900// Translate destination frame into scale and position. If a destination frame is not set, use the
2901// provided scale and position
2902bool Layer::updateGeometry() {
2903 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2904 mDrawingState.destinationFrame.isEmpty()) {
2905 // If destination frame is not set, use the requested transform set via
2906 // Layer::setPosition and Layer::setMatrix.
2907 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2908 }
2909
2910 Rect destRect = mDrawingState.destinationFrame;
2911 int32_t destW = destRect.width();
2912 int32_t destH = destRect.height();
2913 if (destRect.left < 0) {
2914 destRect.left = 0;
2915 destRect.right = destW;
2916 }
2917 if (destRect.top < 0) {
2918 destRect.top = 0;
2919 destRect.bottom = destH;
2920 }
2921
2922 if (!mDrawingState.buffer) {
2923 ui::Transform t;
2924 t.set(destRect.left, destRect.top);
2925 return assignTransform(&mDrawingState.transform, t);
2926 }
2927
2928 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2929 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2930 // Undo any transformations on the buffer.
2931 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2932 std::swap(bufferWidth, bufferHeight);
2933 }
2934 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
2935 if (mDrawingState.transformToDisplayInverse) {
2936 if (invTransform & ui::Transform::ROT_90) {
2937 std::swap(bufferWidth, bufferHeight);
2938 }
2939 }
2940
2941 float sx = destW / static_cast<float>(bufferWidth);
2942 float sy = destH / static_cast<float>(bufferHeight);
2943 ui::Transform t;
2944 t.set(sx, 0, 0, sy);
2945 t.set(destRect.left, destRect.top);
2946 return assignTransform(&mDrawingState.transform, t);
2947}
2948
2949bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
2950 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
2951 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
2952 return false;
2953 }
2954
2955 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
2956
2957 mDrawingState.sequence++;
2958 mDrawingState.modified = true;
2959 setTransactionFlags(eTransactionNeeded);
2960
2961 return true;
2962}
2963
2964bool Layer::setPosition(float x, float y) {
2965 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
2966 return false;
2967 }
2968
2969 mRequestedTransform.set(x, y);
2970
2971 mDrawingState.sequence++;
2972 mDrawingState.modified = true;
2973 setTransactionFlags(eTransactionNeeded);
2974
2975 return true;
2976}
2977
2978bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
2979 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
2980 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07002981 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00002982 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00002983 if (!buffer) {
2984 return false;
2985 }
2986
2987 const bool frameNumberChanged =
2988 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
2989 const uint64_t frameNumber =
2990 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00002991 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002992
2993 if (mDrawingState.buffer) {
2994 mReleasePreviousBuffer = true;
2995 if (!mBufferInfo.mBuffer ||
2996 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
2997 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
2998 // If mDrawingState has a buffer, and we are about to update again
2999 // before swapping to drawing state, then the first buffer will be
3000 // dropped and we should decrement the pending buffer count and
3001 // call any release buffer callbacks if set.
3002 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3003 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3004 mDrawingState.acquireFence,
3005 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
3006 mOwnerUid));
3007 decrementPendingBufferCount();
3008 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3009 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3010 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
3011 mDrawingState.bufferSurfaceFrameTX.reset();
3012 }
3013 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3014 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3015 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3016 mLastClientCompositionFence,
3017 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
3018 mOwnerUid));
3019 mLastClientCompositionFence = nullptr;
3020 }
3021 }
3022
3023 mDrawingState.frameNumber = frameNumber;
3024 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3025 mDrawingState.buffer = std::move(buffer);
3026 mDrawingState.clientCacheId = bufferData.cachedBuffer;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003027 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3028 ? bufferData.acquireFence
3029 : Fence::NO_FENCE;
3030 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3031 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3032 // We latched this buffer unsiganled, so we need to pass the acquire fence
3033 // on the callback instead of just the acquire time, since it's unknown at
3034 // this point.
3035 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3036 } else {
3037 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3038 }
3039
3040 mDrawingState.modified = true;
3041 setTransactionFlags(eTransactionNeeded);
3042
3043 const int32_t layerId = getSequence();
3044 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3045 mOwnerUid, postTime, getGameMode());
3046 mDrawingState.desiredPresentTime = desiredPresentTime;
3047 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3048
3049 const nsecs_t presentTime = [&] {
3050 if (!isAutoTimestamp) return desiredPresentTime;
3051
3052 const auto prediction =
3053 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
3054 if (prediction.has_value()) return prediction->presentTime;
3055
3056 return static_cast<nsecs_t>(0);
3057 }();
3058
3059 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
3060 mFlinger->mScheduler->recordLayerHistory(this, presentTime, LayerUpdateType::Buffer);
3061
3062 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3063
3064 if (dequeueTime && *dequeueTime != 0) {
3065 const uint64_t bufferId = mDrawingState.buffer->getId();
3066 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3067 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3068 FrameTracer::FrameEvent::DEQUEUE);
3069 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3070 FrameTracer::FrameEvent::QUEUE);
3071 }
3072
3073 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3074 return true;
3075}
3076
3077bool Layer::setDataspace(ui::Dataspace dataspace) {
3078 mDrawingState.dataspaceRequested = true;
3079 if (mDrawingState.dataspace == dataspace) return false;
3080 mDrawingState.dataspace = dataspace;
3081 mDrawingState.modified = true;
3082 setTransactionFlags(eTransactionNeeded);
3083 return true;
3084}
3085
John Reck68796592023-01-25 13:47:12 -05003086bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
3087 if (mDrawingState.currentSdrHdrRatio == currentBufferRatio &&
3088 mDrawingState.desiredSdrHdrRatio == desiredRatio)
3089 return false;
3090 mDrawingState.currentSdrHdrRatio = currentBufferRatio;
3091 mDrawingState.desiredSdrHdrRatio = desiredRatio;
3092 mDrawingState.modified = true;
3093 setTransactionFlags(eTransactionNeeded);
3094 return true;
3095}
3096
Patrick Williamsbb25f802022-08-30 23:02:34 +00003097bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3098 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3099 mDrawingState.hdrMetadata = hdrMetadata;
3100 mDrawingState.modified = true;
3101 setTransactionFlags(eTransactionNeeded);
3102 return true;
3103}
3104
3105bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
3106 mDrawingState.surfaceDamageRegion = surfaceDamage;
3107 mDrawingState.modified = true;
3108 setTransactionFlags(eTransactionNeeded);
3109 return true;
3110}
3111
3112bool Layer::setApi(int32_t api) {
3113 if (mDrawingState.api == api) return false;
3114 mDrawingState.api = api;
3115 mDrawingState.modified = true;
3116 setTransactionFlags(eTransactionNeeded);
3117 return true;
3118}
3119
3120bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3121 if (mDrawingState.sidebandStream == sidebandStream) return false;
3122
3123 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3124 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3125 } else if (sidebandStream != nullptr) {
3126 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3127 }
3128
3129 mDrawingState.sidebandStream = sidebandStream;
3130 mDrawingState.modified = true;
3131 setTransactionFlags(eTransactionNeeded);
3132 if (!mSidebandStreamChanged.exchange(true)) {
3133 // mSidebandStreamChanged was false
3134 mFlinger->onLayerUpdate();
3135 }
3136 return true;
3137}
3138
Vishnu Naird6913222023-02-01 22:56:21 +00003139bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3140 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003141 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3142 if (handles.empty()) {
3143 mReleasePreviousBuffer = false;
3144 return false;
3145 }
3146
Pascal Muetschard81cef292023-02-06 12:18:52 +01003147 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003148 for (const auto& handle : handles) {
3149 // If this transaction set a buffer on this layer, release its previous buffer
3150 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3151
3152 // If this layer will be presented in this frame
3153 if (willPresent) {
3154 // If this transaction set an acquire fence on this layer, set its acquire time
3155 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3156 handle->frameNumber = mDrawingState.frameNumber;
3157
3158 // Store so latched time and release fence can be set
3159 mDrawingState.callbackHandles.push_back(handle);
3160
3161 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003162 // Queue this handle to be notified below.
3163 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003164 }
3165 }
3166
Pascal Muetschard81cef292023-02-06 12:18:52 +01003167 if (!remainingHandles.empty()) {
3168 // Notify the transaction completed threads these handles are done. These are only the
3169 // handles that were not added to the mDrawingState, which will be notified later.
3170 std::vector<JankData> jankData;
3171 transferAvailableJankData(remainingHandles, jankData);
3172 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3173 }
3174
Patrick Williamsbb25f802022-08-30 23:02:34 +00003175 mReleasePreviousBuffer = false;
3176 mCallbackHandleAcquireTimeOrFence = -1;
3177
3178 return willPresent;
3179}
3180
3181Rect Layer::getBufferSize(const State& /*s*/) const {
3182 // for buffer state layers we use the display frame size as the buffer size.
3183
3184 if (mBufferInfo.mBuffer == nullptr) {
3185 return Rect::INVALID_RECT;
3186 }
3187
3188 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3189 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3190
3191 // Undo any transformations on the buffer and return the result.
3192 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3193 std::swap(bufWidth, bufHeight);
3194 }
3195
3196 if (getTransformToDisplayInverse()) {
3197 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3198 if (invTransform & ui::Transform::ROT_90) {
3199 std::swap(bufWidth, bufHeight);
3200 }
3201 }
3202
3203 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3204}
3205
3206FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3207 if (mBufferInfo.mBuffer == nullptr) {
3208 return parentBounds;
3209 }
3210
3211 return getBufferSize(getDrawingState()).toFloatRect();
3212}
3213
3214bool Layer::fenceHasSignaled() const {
3215 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3216 return true;
3217 }
3218
3219 const bool fenceSignaled =
3220 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3221 if (!fenceSignaled) {
3222 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3223 TimeStats::LatchSkipReason::LateAcquire);
3224 }
3225
3226 return fenceSignaled;
3227}
3228
Vishnu Naird6913222023-02-01 22:56:21 +00003229void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003230 for (const auto& handle : mDrawingState.callbackHandles) {
3231 handle->refreshStartTime = refreshStartTime;
3232 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003233}
3234
3235void Layer::setAutoRefresh(bool autoRefresh) {
3236 mDrawingState.autoRefresh = autoRefresh;
3237}
3238
3239bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3240 // 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 +00003241 auto* snapshot = editLayerSnapshot();
3242 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003243
3244 if (mSidebandStreamChanged.exchange(false)) {
3245 const State& s(getDrawingState());
3246 // mSidebandStreamChanged was true
3247 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003248 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003249 if (mSidebandStream != nullptr) {
3250 setTransactionFlags(eTransactionNeeded);
3251 mFlinger->setTransactionFlags(eTraversalNeeded);
3252 }
3253 recomputeVisibleRegions = true;
3254
3255 return true;
3256 }
3257 return false;
3258}
3259
3260bool Layer::hasFrameUpdate() const {
3261 const State& c(getDrawingState());
3262 return (mDrawingStateModified || mDrawingState.modified) &&
3263 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3264}
3265
3266void Layer::updateTexImage(nsecs_t latchTime) {
3267 const State& s(getDrawingState());
3268
3269 if (!s.buffer) {
3270 if (s.bgColorLayer) {
3271 for (auto& handle : mDrawingState.callbackHandles) {
3272 handle->latchTime = latchTime;
3273 }
3274 }
3275 return;
3276 }
3277
3278 for (auto& handle : mDrawingState.callbackHandles) {
3279 if (handle->frameNumber == mDrawingState.frameNumber) {
3280 handle->latchTime = latchTime;
3281 }
3282 }
3283
3284 const int32_t layerId = getSequence();
3285 const uint64_t bufferId = mDrawingState.buffer->getId();
3286 const uint64_t frameNumber = mDrawingState.frameNumber;
3287 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3288 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3289 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3290
3291 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3292 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3293 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3294 FrameTracer::FrameEvent::LATCH);
3295
3296 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3297 if (bufferSurfaceFrame != nullptr &&
3298 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3299 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3300 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3301 // are processing the next state.
3302 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3303 mDrawingState.acquireFenceTime->getSignalTime(),
3304 latchTime);
3305 mDrawingState.bufferSurfaceFrameTX.reset();
3306 }
3307
3308 std::deque<sp<CallbackHandle>> remainingHandles;
3309 mFlinger->getTransactionCallbackInvoker()
3310 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3311 mDrawingState.callbackHandles = remainingHandles;
3312
3313 mDrawingStateModified = false;
3314}
3315
3316void Layer::gatherBufferInfo() {
3317 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3318 decrementPendingBufferCount();
3319 }
3320
3321 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3322 mBufferInfo.mBuffer = mDrawingState.buffer;
3323 mBufferInfo.mFence = mDrawingState.acquireFence;
3324 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3325 mBufferInfo.mPixelFormat =
3326 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3327 mBufferInfo.mFrameLatencyNeeded = true;
3328 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3329 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3330 mBufferInfo.mFence = mDrawingState.acquireFence;
3331 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3332 auto lastDataspace = mBufferInfo.mDataspace;
3333 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3334 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003335 mFlinger->mHdrLayerInfoChanged = true;
3336 }
3337 if (mBufferInfo.mDesiredSdrHdrRatio != mDrawingState.desiredSdrHdrRatio) {
3338 mBufferInfo.mDesiredSdrHdrRatio = mDrawingState.desiredSdrHdrRatio;
3339 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003340 }
3341 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3342 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3343 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3344 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3345 mBufferInfo.mApi = mDrawingState.api;
3346 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003347}
3348
3349Rect Layer::computeBufferCrop(const State& s) {
3350 if (s.buffer && !s.bufferCrop.isEmpty()) {
3351 Rect bufferCrop;
3352 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3353 return bufferCrop;
3354 } else if (s.buffer) {
3355 return s.buffer->getBounds();
3356 } else {
3357 return s.bufferCrop;
3358 }
3359}
3360
3361sp<Layer> Layer::createClone() {
3362 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3363 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003364 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003365 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3366 return layer;
3367}
3368
Patrick Williamsbb25f802022-08-30 23:02:34 +00003369void Layer::decrementPendingBufferCount() {
3370 int32_t pendingBuffers = --mPendingBufferTransactions;
3371 tracePendingBufferCount(pendingBuffers);
3372}
3373
3374void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3375 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3376}
3377
3378/*
3379 * We don't want to send the layer's transform to input, but rather the
3380 * parent's transform. This is because Layer's transform is
3381 * information about how the buffer is placed on screen. The parent's
3382 * transform makes more sense to send since it's information about how the
3383 * layer is placed on screen. This transform is used by input to determine
3384 * how to go from screen space back to window space.
3385 */
3386ui::Transform Layer::getInputTransform() const {
3387 if (!hasBufferOrSidebandStream()) {
3388 return getTransform();
3389 }
3390 sp<Layer> parent = mDrawingParent.promote();
3391 if (parent == nullptr) {
3392 return ui::Transform();
3393 }
3394
3395 return parent->getTransform();
3396}
3397
3398/**
3399 * Similar to getInputTransform, we need to update the bounds to include the transform.
3400 * This is because bounds don't include the buffer transform, where the input assumes
3401 * that's already included.
3402 */
3403Rect Layer::getInputBounds() const {
3404 if (!hasBufferOrSidebandStream()) {
3405 return getCroppedBufferSize(getDrawingState());
3406 }
3407
3408 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
3409 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
3410 return bufferBounds;
3411 }
3412 return mDrawingState.transform.transform(bufferBounds);
3413}
3414
3415bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3416 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3417
3418 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3419 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3420 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3421 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3422 layer_state_t::eReparent;
3423
3424 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3425 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3426 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3427 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3428 layer_state_t::eInputInfoChanged;
3429
3430 if ((s.what & requiredFlags) != requiredFlags) {
3431 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3432 (s.what | requiredFlags) & ~s.what);
3433 return false;
3434 }
3435
3436 if (s.what & deniedFlags) {
3437 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3438 return false;
3439 }
3440
3441 if (s.what & allowedFlags) {
3442 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3443 }
3444
3445 if (s.what & layer_state_t::ePositionChanged) {
3446 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3447 ALOGV("%s: false [ePositionChanged changed]", __func__);
3448 return false;
3449 }
3450 }
3451
3452 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003453 if (mDrawingState.color.a != s.color.a) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003454 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3455 return false;
3456 }
3457 }
3458
3459 if (s.what & layer_state_t::eColorTransformChanged) {
3460 if (mDrawingState.colorTransform != s.colorTransform) {
3461 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3462 return false;
3463 }
3464 }
3465
3466 if (s.what & layer_state_t::eBackgroundColorChanged) {
3467 if (mDrawingState.bgColorLayer || s.bgColorAlpha != 0) {
3468 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3469 return false;
3470 }
3471 }
3472
3473 if (s.what & layer_state_t::eMatrixChanged) {
3474 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3475 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3476 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3477 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3478 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3479 return false;
3480 }
3481 }
3482
3483 if (s.what & layer_state_t::eCornerRadiusChanged) {
3484 if (mDrawingState.cornerRadius != s.cornerRadius) {
3485 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3486 return false;
3487 }
3488 }
3489
3490 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3491 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3492 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3493 return false;
3494 }
3495 }
3496
Vishnu Nairbbceb462022-10-10 04:52:13 +00003497 if (s.what & layer_state_t::eBufferTransformChanged) {
3498 if (mDrawingState.bufferTransform != s.bufferTransform) {
3499 ALOGV("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003500 return false;
3501 }
3502 }
3503
3504 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3505 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3506 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3507 return false;
3508 }
3509 }
3510
3511 if (s.what & layer_state_t::eCropChanged) {
3512 if (mDrawingState.crop != s.crop) {
3513 ALOGV("%s: false [eCropChanged changed]", __func__);
3514 return false;
3515 }
3516 }
3517
3518 if (s.what & layer_state_t::eDataspaceChanged) {
3519 if (mDrawingState.dataspace != s.dataspace) {
3520 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3521 return false;
3522 }
3523 }
3524
3525 if (s.what & layer_state_t::eHdrMetadataChanged) {
3526 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3527 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3528 return false;
3529 }
3530 }
3531
3532 if (s.what & layer_state_t::eSidebandStreamChanged) {
3533 if (mDrawingState.sidebandStream != s.sidebandStream) {
3534 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3535 return false;
3536 }
3537 }
3538
3539 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3540 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3541 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3542 return false;
3543 }
3544 }
3545
3546 if (s.what & layer_state_t::eShadowRadiusChanged) {
3547 if (mDrawingState.shadowRadius != s.shadowRadius) {
3548 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3549 return false;
3550 }
3551 }
3552
3553 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3554 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3555 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3556 return false;
3557 }
3558 }
3559
3560 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3561 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3562 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3563 return false;
3564 }
3565 }
3566
3567 if (s.what & layer_state_t::eStretchChanged) {
3568 StretchEffect temp = s.stretchEffect;
3569 temp.sanitize();
3570 if (mDrawingState.stretchEffect != temp) {
3571 ALOGV("%s: false [eStretchChanged changed]", __func__);
3572 return false;
3573 }
3574 }
3575
3576 if (s.what & layer_state_t::eBufferCropChanged) {
3577 if (mDrawingState.bufferCrop != s.bufferCrop) {
3578 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3579 return false;
3580 }
3581 }
3582
3583 if (s.what & layer_state_t::eDestinationFrameChanged) {
3584 if (mDrawingState.destinationFrame != s.destinationFrame) {
3585 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3586 return false;
3587 }
3588 }
3589
3590 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3591 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3592 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3593 return false;
3594 }
3595 }
3596
John Reck68796592023-01-25 13:47:12 -05003597 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
3598 if (mDrawingState.currentSdrHdrRatio != s.currentSdrHdrRatio ||
3599 mDrawingState.desiredSdrHdrRatio != s.desiredSdrHdrRatio) {
3600 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3601 return false;
3602 }
3603 }
3604
Patrick Williamsbb25f802022-08-30 23:02:34 +00003605 ALOGV("%s: true", __func__);
3606 return true;
3607}
3608
3609bool Layer::isHdrY410() const {
3610 // pixel format is HDR Y410 masquerading as RGBA_1010102
3611 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3612 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3613 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3614}
3615
Vishnu Naire14c6b32022-08-06 04:20:15 +00003616sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003617 // There's no need to get a CE Layer if the layer isn't going to draw anything.
Vishnu Naird6913222023-02-01 22:56:21 +00003618 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003619}
3620
Vishnu Naire14c6b32022-08-06 04:20:15 +00003621const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003622 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003623}
3624
Vishnu Naire14c6b32022-08-06 04:20:15 +00003625LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003626 return mSnapshot.get();
3627}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003628
Vishnu Naird6913222023-02-01 22:56:21 +00003629std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3630 return std::move(mSnapshot);
3631}
3632
3633void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3634 mSnapshot = std::move(snapshot);
3635}
3636
Patrick Williamsbb25f802022-08-30 23:02:34 +00003637const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003638 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003639}
3640
Patrick Williams7584c6a2022-10-29 02:10:58 +00003641sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Naird6913222023-02-01 22:56:21 +00003642 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003643 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3644 return result;
3645}
3646
Vishnu Naird6913222023-02-01 22:56:21 +00003647sp<LayerFE> Layer::getCompositionEngineLayerFE(
3648 const frontend::LayerHierarchy::TraversalPath& path) {
3649 for (auto& [p, layerFE] : mLayerFEs) {
3650 if (p == path) {
3651 return layerFE;
3652 }
3653 }
3654 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3655 mLayerFEs.emplace_back(path, layerFE);
3656 return layerFE;
3657}
3658
Patrick Williamsbb25f802022-08-30 23:02:34 +00003659void Layer::useSurfaceDamage() {
3660 if (mFlinger->mForceFullDamage) {
3661 surfaceDamageRegion = Region::INVALID_REGION;
3662 } else {
3663 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3664 }
3665}
3666
3667void Layer::useEmptyDamage() {
3668 surfaceDamageRegion.clear();
3669}
3670
3671bool Layer::isOpaque(const Layer::State& s) const {
3672 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3673 // layer's opaque flag.
3674 if (!hasSomethingToDraw()) {
3675 return false;
3676 }
3677
3678 // if the layer has the opaque flag, then we're always opaque
3679 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3680 return true;
3681 }
3682
3683 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003684 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003685 return true;
3686 }
3687
3688 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3689 return fillsColor() && getAlpha() == 1.0_hf;
3690}
3691
3692bool Layer::canReceiveInput() const {
3693 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3694}
3695
3696bool Layer::isVisible() const {
3697 if (!hasSomethingToDraw()) {
3698 return false;
3699 }
3700
3701 if (isHiddenByPolicy()) {
3702 return false;
3703 }
3704
3705 return getAlpha() > 0.0f || hasBlur();
3706}
3707
3708void Layer::onPostComposition(const DisplayDevice* display,
3709 const std::shared_ptr<FenceTime>& glDoneFence,
3710 const std::shared_ptr<FenceTime>& presentFence,
3711 const CompositorTiming& compositorTiming) {
3712 // mFrameLatencyNeeded is true when a new frame was latched for the
3713 // composition.
3714 if (!mBufferInfo.mFrameLatencyNeeded) return;
3715
3716 for (const auto& handle : mDrawingState.callbackHandles) {
3717 handle->gpuCompositionDoneFence = glDoneFence;
3718 handle->compositorTiming = compositorTiming;
3719 }
3720
3721 // Update mFrameTracker.
3722 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3723 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3724
3725 const int32_t layerId = getSequence();
3726 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3727
3728 const auto outputLayer = findOutputLayerForDisplay(display);
3729 if (outputLayer && outputLayer->requiresClientComposition()) {
3730 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3731 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3732 clientCompositionTimestamp,
3733 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3734 // Update the SurfaceFrames in the drawing state
3735 if (mDrawingState.bufferSurfaceFrameTX) {
3736 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3737 }
3738 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3739 surfaceFrame->setGpuComposition();
3740 }
3741 }
3742
3743 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3744 if (frameReadyFence->isValid()) {
3745 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3746 } else {
3747 // There was no fence for this frame, so assume that it was ready
3748 // to be presented at the desired present time.
3749 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3750 }
3751
3752 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08003753 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003754 const std::optional<Fps> renderRate =
3755 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3756
3757 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3758 const auto gameMode = getGameMode();
3759
3760 if (presentFence->isValid()) {
3761 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3762 refreshRate, renderRate, vote, gameMode);
3763 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3764 presentFence,
3765 FrameTracer::FrameEvent::PRESENT_FENCE);
3766 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3767 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3768 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003769 // The HWC doesn't support present fences, so use the present timestamp instead.
3770 const nsecs_t presentTimestamp =
3771 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3772
3773 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3774 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3775 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3776
Patrick Williamsbb25f802022-08-30 23:02:34 +00003777 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3778 refreshRate, renderRate, vote, gameMode);
3779 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3780 mCurrentFrameNumber, actualPresentTime,
3781 FrameTracer::FrameEvent::PRESENT_FENCE);
3782 mFrameTracker.setActualPresentTime(actualPresentTime);
3783 }
3784 }
3785
3786 mFrameTracker.advanceFrame();
3787 mBufferInfo.mFrameLatencyNeeded = false;
3788}
3789
3790bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
3791 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3792 getDrawingState().frameNumber);
3793
3794 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3795
3796 if (refreshRequired) {
3797 return refreshRequired;
3798 }
3799
3800 // If the head buffer's acquire fence hasn't signaled yet, return and
3801 // try again later
3802 if (!fenceHasSignaled()) {
3803 ATRACE_NAME("!fenceHasSignaled()");
3804 mFlinger->onLayerUpdate();
3805 return false;
3806 }
3807
3808 updateTexImage(latchTime);
3809 if (mDrawingState.buffer == nullptr) {
3810 return false;
3811 }
3812
3813 // Capture the old state of the layer for comparisons later
3814 BufferInfo oldBufferInfo = mBufferInfo;
3815 const bool oldOpacity = isOpaque(mDrawingState);
3816 mPreviousFrameNumber = mCurrentFrameNumber;
3817 mCurrentFrameNumber = mDrawingState.frameNumber;
3818 gatherBufferInfo();
3819
3820 if (oldBufferInfo.mBuffer == nullptr) {
3821 // the first time we receive a buffer, we need to trigger a
3822 // geometry invalidation.
3823 recomputeVisibleRegions = true;
3824 }
3825
3826 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3827 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3828 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3829 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3830 recomputeVisibleRegions = true;
3831 }
3832
3833 if (oldBufferInfo.mBuffer != nullptr) {
3834 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3835 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3836 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3837 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3838 recomputeVisibleRegions = true;
3839 }
3840 }
3841
3842 if (oldOpacity != isOpaque(mDrawingState)) {
3843 recomputeVisibleRegions = true;
3844 }
3845
3846 return true;
3847}
3848
3849bool Layer::hasReadyFrame() const {
3850 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
3851}
3852
3853bool Layer::isProtected() const {
3854 return (mBufferInfo.mBuffer != nullptr) &&
3855 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
3856}
3857
Patrick Williamsbb25f802022-08-30 23:02:34 +00003858void Layer::latchAndReleaseBuffer() {
3859 if (hasReadyFrame()) {
3860 bool ignored = false;
3861 latchBuffer(ignored, systemTime());
3862 }
3863 releasePendingBuffer(systemTime());
3864}
3865
3866PixelFormat Layer::getPixelFormat() const {
3867 return mBufferInfo.mPixelFormat;
3868}
3869
3870bool Layer::getTransformToDisplayInverse() const {
3871 return mBufferInfo.mTransformToDisplayInverse;
3872}
3873
3874Rect Layer::getBufferCrop() const {
3875 // this is the crop rectangle that applies to the buffer
3876 // itself (as opposed to the window)
3877 if (!mBufferInfo.mCrop.isEmpty()) {
3878 // if the buffer crop is defined, we use that
3879 return mBufferInfo.mCrop;
3880 } else if (mBufferInfo.mBuffer != nullptr) {
3881 // otherwise we use the whole buffer
3882 return mBufferInfo.mBuffer->getBounds();
3883 } else {
3884 // if we don't have a buffer yet, we use an empty/invalid crop
3885 return Rect();
3886 }
3887}
3888
3889uint32_t Layer::getBufferTransform() const {
3890 return mBufferInfo.mTransform;
3891}
3892
3893ui::Dataspace Layer::getDataSpace() const {
3894 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
3895}
3896
3897ui::Dataspace Layer::getRequestedDataSpace() const {
3898 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
3899}
3900
3901ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
3902 ui::Dataspace updatedDataspace = dataspace;
3903 // translate legacy dataspaces to modern dataspaces
3904 switch (dataspace) {
3905 case ui::Dataspace::SRGB:
3906 updatedDataspace = ui::Dataspace::V0_SRGB;
3907 break;
3908 case ui::Dataspace::SRGB_LINEAR:
3909 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
3910 break;
3911 case ui::Dataspace::JFIF:
3912 updatedDataspace = ui::Dataspace::V0_JFIF;
3913 break;
3914 case ui::Dataspace::BT601_625:
3915 updatedDataspace = ui::Dataspace::V0_BT601_625;
3916 break;
3917 case ui::Dataspace::BT601_525:
3918 updatedDataspace = ui::Dataspace::V0_BT601_525;
3919 break;
3920 case ui::Dataspace::BT709:
3921 updatedDataspace = ui::Dataspace::V0_BT709;
3922 break;
3923 default:
3924 break;
3925 }
3926
3927 return updatedDataspace;
3928}
3929
3930sp<GraphicBuffer> Layer::getBuffer() const {
3931 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
3932}
3933
Patrick Williamsbb25f802022-08-30 23:02:34 +00003934void Layer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
3935 mTransformHint = getFixedTransformHint();
3936 if (mTransformHint == ui::Transform::ROT_INVALID) {
3937 mTransformHint = displayTransformHint;
3938 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07003939 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003940}
3941
3942const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
3943 return mBufferInfo.mBuffer;
3944}
3945
3946bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003947 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003948 return false;
3949 }
3950
3951 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00003952 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003953 mDrawingState.modified = true;
3954 setTransactionFlags(eTransactionNeeded);
3955 return true;
3956}
3957
3958bool Layer::fillsColor() const {
3959 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
3960 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
3961}
3962
3963bool Layer::hasBlur() const {
3964 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
3965}
3966
Vishnu Nairba354102022-08-01 00:14:18 +00003967void Layer::updateSnapshot(bool updateGeometry) {
3968 if (!getCompositionEngineLayerFE()) {
3969 return;
3970 }
3971
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003972 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00003973 if (updateGeometry) {
3974 prepareBasicGeometryCompositionState();
3975 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003976 snapshot->roundedCorner = getRoundedCornerState();
3977 snapshot->stretchEffect = getStretchEffect();
3978 snapshot->transformedBounds = mScreenBounds;
3979 if (mEffectiveShadowRadius > 0.f) {
3980 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
3981
3982 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
3983 // it if transparent regions are present. This may not be necessary since shadows are
3984 // typically cast by layers without transparent regions.
3985 snapshot->shadowSettings.boundaries = mBounds;
3986
3987 const float casterAlpha = snapshot->alpha;
3988 const bool casterIsOpaque =
3989 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
3990
3991 // If the casting layer is translucent, we need to fill in the shadow underneath the
3992 // layer. Otherwise the generated shadow will only be shown around the casting layer.
3993 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
3994 snapshot->shadowSettings.ambientColor *= casterAlpha;
3995 snapshot->shadowSettings.spotColor *= casterAlpha;
3996 }
3997 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00003998 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003999 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004000 snapshot->layerOpaqueFlagSet =
4001 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004002 snapshot->isHdrY410 = isHdrY410();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004003 sp<Layer> p = mDrawingParent.promote();
4004 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004005 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004006 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004007 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004008 }
4009 snapshot->bufferSize = getBufferSize(mDrawingState);
4010 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004011 snapshot->hasReadyFrame = hasReadyFrame();
Chavi Weingarten545da0e2023-02-09 14:55:57 +00004012 snapshot->isInternalDisplayOverlay = isInternalDisplayOverlay();
Vishnu Nairba354102022-08-01 00:14:18 +00004013 preparePerFrameCompositionState();
4014}
4015
Vishnu Naire14c6b32022-08-06 04:20:15 +00004016void Layer::updateChildrenSnapshots(bool updateGeometry) {
4017 for (const sp<Layer>& child : mDrawingChildren) {
4018 child->updateSnapshot(updateGeometry);
4019 child->updateChildrenSnapshots(updateGeometry);
4020 }
4021}
4022
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004023void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4024 mSnapshot->layerMetadata = parentMetadata;
4025 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4026 for (const sp<Layer>& child : mDrawingChildren) {
4027 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4028 }
4029}
4030
4031void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4032 std::unordered_set<Layer*>& visited) {
4033 if (visited.find(this) != visited.end()) {
4034 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4035 return;
4036 }
4037 visited.insert(this);
4038
4039 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4040
4041 if (mDrawingState.zOrderRelatives.empty()) {
4042 return;
4043 }
4044 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4045 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4046 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4047 sp<Layer> relative = weakRelative.promote();
4048 if (!relative) {
4049 continue;
4050 }
4051 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4052 }
4053}
4054
Chavi Weingarten076acac2023-01-19 17:20:43 +00004055void Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
4056 TrustedPresentationListener const& listener) {
4057 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4058 mTrustedPresentationListener = listener;
4059 mTrustedPresentationThresholds = thresholds;
4060 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4061 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4062 mFlinger->mNumTrustedPresentationListeners++;
4063 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4064 mFlinger->mNumTrustedPresentationListeners--;
4065 }
4066}
4067
Mathias Agopian13127d82013-03-05 17:47:11 -08004068// ---------------------------------------------------------------------------
4069
Marin Shalamanov46084422020-10-13 12:33:42 +02004070std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004071 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4072 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004073}
4074
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004075} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004076
4077#if defined(__gl_h_)
4078#error "don't include gl/gl.h in this file"
4079#endif
4080
4081#if defined(__gl2_h_)
4082#error "don't include gl2/gl2.h in this file"
4083#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004084
4085// TODO(b/129481165): remove the #pragma below and fix conversion issues
4086#pragma clang diagnostic pop // ignored "-Wconversion"