blob: 31ee91ea020277babbc3627a2c67afd0f90391d6 [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);
Vishnu Nair781d7252023-01-30 18:16:01 +0000398 if (outputLayer != nullptr && snapshot != nullptr) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000399 mLastComputedTrustedPresentationState =
Vishnu Nair781d7252023-01-30 18:16:01 +0000400 computeTrustedPresentationState(snapshot->geomLayerBounds,
401 snapshot->sourceBounds(),
Chavi Weingarten076acac2023-01-19 17:20:43 +0000402 outputLayer->getState().coveredRegion,
Vishnu Nair781d7252023-01-30 18:16:01 +0000403 snapshot->transformedBounds, snapshot->alpha,
404 snapshot->geomLayerTransform,
Chavi Weingarten076acac2023-01-19 17:20:43 +0000405 mTrustedPresentationThresholds);
406 }
407 }
408 const bool newState = mLastComputedTrustedPresentationState;
409 if (lastState && !newState) {
410 // We were in the trusted presentation state, but now we left it,
411 // emit the callback if needed
412 if (mLastReportedTrustedPresentationState) {
413 mLastReportedTrustedPresentationState = false;
414 mTrustedPresentationListener.invoke(false);
415 }
416 // Reset the timer
417 mEnteredTrustedPresentationStateTime = -1;
418 } else if (!lastState && newState) {
419 // We were not in the trusted presentation state, but we entered it, begin the timer
420 // and make sure this gets called at least once more!
421 mEnteredTrustedPresentationStateTime = time_in_ms;
422 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
423 }
424
425 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
426 if (!mLastReportedTrustedPresentationState && newState &&
427 (time_in_ms - mEnteredTrustedPresentationStateTime >
428 mTrustedPresentationThresholds.stabilityRequirementMs)) {
429 mLastReportedTrustedPresentationState = true;
430 mTrustedPresentationListener.invoke(true);
431 }
432}
433
434/**
435 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
436 * of how the parameters and thresholds are interpreted. The general spirit is
437 * to produce an upper bound on the amount of the buffer which was presented.
438 */
439bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
440 const Region& coveredRegion,
441 const FloatRect& screenBounds, float alpha,
442 const ui::Transform& effectiveTransform,
443 const TrustedPresentationThresholds& thresholds) {
444 if (alpha < thresholds.minAlpha) {
445 return false;
446 }
447 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
448 return false;
449 }
450 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
451 return false;
452 }
453
454 const float sx = effectiveTransform.dsdx();
455 const float sy = effectiveTransform.dsdy();
456 float fractionRendered = std::min(sx * sy, 1.0f);
457
458 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
459 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
460 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
461
462 Rect coveredBounds = coveredRegion.bounds();
463 fractionRendered *= (1 -
464 ((coveredBounds.width() / (float)screenBounds.getWidth()) *
465 coveredBounds.height() / (float)screenBounds.getHeight()));
466
467 if (fractionRendered < thresholds.minFractionRendered) {
468 return false;
469 }
470
471 return true;
472}
473
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700474void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
475 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800476 const State& s(getDrawingState());
477
478 // Calculate effective layer transform
479 mEffectiveTransform = parentTransform * getActiveTransform(s);
480
Garfield Tan2c1782c2022-02-16 15:25:05 -0800481 if (CC_UNLIKELY(!isTransformValid())) {
482 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
483 getDebugName());
484 return;
485 }
486
Vishnu Nair4351ad52019-02-11 14:13:02 -0800487 // Transform parent bounds to layer space
488 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
489
Vishnu Nairc652ff82019-03-15 12:48:54 -0700490 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800491 mSourceBounds = computeSourceBounds(parentBounds);
492
493 // Calculate bounds by croping diplay frame with layer crop and parent bounds
494 FloatRect bounds = mSourceBounds;
495 const Rect layerCrop = getCrop(s);
496 if (!layerCrop.isEmpty()) {
497 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
498 }
499 bounds = bounds.intersect(parentBounds);
500
501 mBounds = bounds;
502 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700503
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700504 // Use the layer's own shadow radius if set. Otherwise get the radius from
505 // parent.
506 if (s.shadowRadius > 0.f) {
507 mEffectiveShadowRadius = s.shadowRadius;
508 } else {
509 mEffectiveShadowRadius = parentShadowRadius;
510 }
511
512 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
513 // don't pass it to its children.
514 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
515
Vishnu Nair4351ad52019-02-11 14:13:02 -0800516 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700517 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800518 }
Vishnu Nairba354102022-08-01 00:14:18 +0000519
520 if (mPotentialCursor) {
521 prepareCursorCompositionState();
522 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800523}
524
Vishnu Nair60356342018-11-13 13:00:45 -0800525Rect Layer::getCroppedBufferSize(const State& s) const {
526 Rect size = getBufferSize(s);
527 Rect crop = getCrop(s);
528 if (!crop.isEmpty() && size.isValid()) {
529 size.intersect(crop, &size);
530 } else if (!crop.isEmpty()) {
531 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700532 }
Vishnu Nair60356342018-11-13 13:00:45 -0800533 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800534}
535
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700536void Layer::setupRoundedCornersCropCoordinates(Rect win,
537 const FloatRect& roundedCornersCrop) const {
538 // Translate win by the rounded corners rect coordinates, to have all values in
539 // layer coordinate space.
540 win.left -= roundedCornersCrop.left;
541 win.right -= roundedCornersCrop.left;
542 win.top -= roundedCornersCrop.top;
543 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700544}
545
Lloyd Piquede196652020-01-22 17:29:58 -0800546void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800547 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800548 const auto alpha = static_cast<float>(getAlpha());
549 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700550 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800551
552 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
553 if (!opaque || alpha != 1.0f) {
554 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
555 : Hwc2::IComposerClient::BlendMode::COVERAGE;
556 }
557
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000558 auto* snapshot = editLayerSnapshot();
559 snapshot->outputFilter = getOutputFilter();
560 snapshot->isVisible = isVisible();
561 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
562 snapshot->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800563
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000564 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800565 contentDirty = false;
566
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000567 snapshot->geomLayerBounds = mBounds;
568 snapshot->geomLayerTransform = getTransform();
569 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
570 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000571 snapshot->localTransform = getActiveTransform(drawingState);
572 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000573 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
574 snapshot->alpha = alpha;
575 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
576 snapshot->blurRegions = drawingState.blurRegions;
577 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800578}
579
Lloyd Piquede196652020-01-22 17:29:58 -0800580void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800581 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000582 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700583
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000584 snapshot->geomBufferSize = getBufferSize(drawingState);
585 snapshot->geomContentCrop = getBufferCrop();
586 snapshot->geomCrop = getCrop(drawingState);
587 snapshot->geomBufferTransform = getBufferTransform();
588 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
589 snapshot->geomUsesSourceCrop = usesSourceCrop();
590 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800591
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000592 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800593 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
594 for (const auto& [key, mandatory] : supportedMetadata) {
595 const auto& genericLayerMetadataCompatibilityMap =
596 mFlinger->getGenericLayerMetadataKeyMap();
597 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
598 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
599 continue;
600 }
601 const uint32_t id = compatIter->second;
602
603 auto it = drawingState.metadata.mMap.find(id);
604 if (it == std::end(drawingState.metadata.mMap)) {
605 continue;
606 }
607
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000608 snapshot->metadata.emplace(key,
609 compositionengine::GenericLayerMetadataEntry{mandatory,
610 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800611 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800612}
David Sodmanba340492018-08-05 21:51:33 -0700613
Lloyd Piquede196652020-01-22 17:29:58 -0800614void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800615 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000616 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800617
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000618 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800619
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000620 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
621 snapshot->dataspace = getDataSpace();
622 snapshot->colorTransform = getColorTransform();
623 snapshot->colorTransformIsIdentity = !hasColorTransform();
624 snapshot->surfaceDamage = surfaceDamageRegion;
625 snapshot->hasProtectedContent = isProtected();
626 snapshot->dimmingEnabled = isDimmingEnabled();
John Reck68796592023-01-25 13:47:12 -0500627 snapshot->currentSdrHdrRatio = getCurrentSdrHdrRatio();
628 snapshot->desiredSdrHdrRatio = getDesiredSdrHdrRatio();
Lloyd Pique688abd42019-02-15 15:42:24 -0800629
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700630 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700631
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000632 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800633
634 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400635 // Rounded corners no longer force client composition, since we may use a
636 // hole punch so that the layer will appear to have rounded corners.
637 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000638 snapshot->stretchEffect.hasEffect()) {
639 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800640 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700641 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000642 snapshot->blurRegions = drawingState.blurRegions;
643 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400644
645 // Layer framerate is used in caching decisions.
646 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
647 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000648 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000649
650 if (hasBufferOrSidebandStream()) {
651 preparePerFrameBufferCompositionState();
652 } else {
653 preparePerFrameEffectsCompositionState();
654 }
655}
656
657void Layer::preparePerFrameBufferCompositionState() {
658 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000659 auto* snapshot = editLayerSnapshot();
660 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
661 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000662 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
663 return;
664 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000665 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000666 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
667 } else {
668 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000669 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
670 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000671 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
672 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
673 }
674
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000675 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000676 snapshot->acquireFence = mBufferInfo.mFence;
677 snapshot->frameNumber = mBufferInfo.mFrameNumber;
678 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000679}
680
681void Layer::preparePerFrameEffectsCompositionState() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000682 auto* snapshot = editLayerSnapshot();
683 snapshot->color = getColor();
684 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000685 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800686}
687
Lloyd Piquede196652020-01-22 17:29:58 -0800688void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800689 const State& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000690 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800691
692 // Apply the layer's transform, followed by the display's global transform
693 // Here we're guaranteed that the layer's transform preserves rects
694 Rect win = getCroppedBufferSize(drawingState);
695 // Subtract the transparent region and snap to the bounds
696 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
697 Rect frame(getTransform().transform(bounds));
698
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000699 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800700}
701
Lloyd Piquea83776c2019-01-29 18:42:32 -0800702const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700703 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800704}
705
Mathias Agopian13127d82013-03-05 17:47:11 -0800706// ---------------------------------------------------------------------------
707// drawing...
708// ---------------------------------------------------------------------------
709
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500710aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
711 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700712 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800713 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500714 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800715 }
716 if (outputLayer->getState().hwc) {
717 return (*outputLayer->getState().hwc).hwcCompositionType;
718 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500719 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800720 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800721}
722
Mathias Agopian13127d82013-03-05 17:47:11 -0800723// ----------------------------------------------------------------------------
724// local state
725// ----------------------------------------------------------------------------
726
David Sodman41fdfc92017-11-06 16:09:56 -0800727bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800728 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700729 if (s.flags & layer_state_t::eLayerSecure) {
730 return true;
731 }
732
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000733 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700734 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700735}
736
Mathias Agopian13127d82013-03-05 17:47:11 -0800737// ----------------------------------------------------------------------------
738// transaction
739// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800740
Marissa Wall61c58622018-07-18 10:12:20 -0700741uint32_t Layer::doTransaction(uint32_t flags) {
742 ATRACE_CALL();
743
Robert Carr0758e5d2021-03-11 22:15:04 -0800744 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700745 mDrawingStateModified = mDrawingState.modified;
746 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700747
Alec Mourib416efd2018-09-06 21:01:59 +0000748 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700749
Robert Carr6a160312021-05-17 12:08:20 -0700750 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800751 // invalidate and recompute the visible regions if needed
752 flags |= Layer::eVisibleRegion;
753 }
754
Robert Carr6a160312021-05-17 12:08:20 -0700755 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800756 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000757 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800758 flags |= eVisibleRegion;
759 this->contentDirty = true;
760
761 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700762 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800763 }
764
Arthur Hung9ed43392022-05-27 06:31:57 +0000765 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
766 mFlinger->mUpdateInputInfo = true;
767 }
768
Robert Carr6a160312021-05-17 12:08:20 -0700769 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800770
Mathias Agopian13127d82013-03-05 17:47:11 -0800771 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800772}
773
Robert Carr6a160312021-05-17 12:08:20 -0700774void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000775 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
776 // bufferSurfaceFrameTX will be presented in latchBuffer.
777 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
778 if (surfaceFrame->getPresentState() != PresentState::Presented) {
779 // With applyPendingStates, we could end up having presented surfaceframes from previous
780 // states
781 surfaceFrame->setPresentState(PresentState::Presented);
782 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
783 }
784 }
Robert Carr6a160312021-05-17 12:08:20 -0700785 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700786}
787
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700788uint32_t Layer::clearTransactionFlags(uint32_t mask) {
789 const auto flags = mTransactionFlags & mask;
790 mTransactionFlags &= ~mask;
791 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800792}
793
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700794void Layer::setTransactionFlags(uint32_t mask) {
795 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800796}
797
Robert Carr1f0a16a2016-10-24 16:27:39 -0700798bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
799 ssize_t idx = mCurrentChildren.indexOf(childLayer);
800 if (idx < 0) {
801 return false;
802 }
803 if (childLayer->setLayer(z)) {
804 mCurrentChildren.removeAt(idx);
805 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800806 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700807 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800808 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700809}
810
Robert Carr503c7042017-09-27 15:06:08 -0700811bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
812 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
813 ssize_t idx = mCurrentChildren.indexOf(childLayer);
814 if (idx < 0) {
815 return false;
816 }
817 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
818 mCurrentChildren.removeAt(idx);
819 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800820 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700821 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800822 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700823}
824
Robert Carrae060832016-11-28 10:51:00 -0800825bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700826 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
827 mDrawingState.sequence++;
828 mDrawingState.z = z;
829 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700830
Robert Carra70e91c2021-06-11 13:59:52 -0700831 mFlinger->mSomeChildrenChanged = true;
832
Robert Carrdb66e622017-04-10 16:55:57 -0700833 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700834 if (mDrawingState.zOrderRelativeOf != nullptr) {
835 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700836 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700837 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700838 }
chaviw606e5cf2019-03-01 10:12:10 -0800839 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700840 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800841 setTransactionFlags(eTransactionNeeded);
842 return true;
843}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700844
Robert Carrdb66e622017-04-10 16:55:57 -0700845void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700846 mDrawingState.zOrderRelatives.remove(relative);
847 mDrawingState.sequence++;
848 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700849 setTransactionFlags(eTransactionNeeded);
850}
851
852void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700853 mDrawingState.zOrderRelatives.add(relative);
854 mDrawingState.modified = true;
855 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700856 setTransactionFlags(eTransactionNeeded);
857}
858
chaviw606e5cf2019-03-01 10:12:10 -0800859void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700860 mDrawingState.zOrderRelativeOf = relativeOf;
861 mDrawingState.sequence++;
862 mDrawingState.modified = true;
863 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700864
chaviw606e5cf2019-03-01 10:12:10 -0800865 setTransactionFlags(eTransactionNeeded);
866}
867
Robert Carr503d2bd2017-12-04 15:49:47 -0800868bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000869 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700870 if (relative == nullptr) {
871 return false;
872 }
873
Robert Carr6a160312021-05-17 12:08:20 -0700874 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
875 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800876 return false;
877 }
878
Robert Carr88b85e12022-03-21 15:47:35 -0700879 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
880 (relative->mDrawingState.zOrderRelativeOf == this)) {
881 ALOGE("Detected relative layer loop between %s and %s",
882 mName.c_str(), relative->mName.c_str());
883 ALOGE("Ignoring new call to set relative layer");
884 return false;
885 }
886
Robert Carra70e91c2021-06-11 13:59:52 -0700887 mFlinger->mSomeChildrenChanged = true;
888
Robert Carr6a160312021-05-17 12:08:20 -0700889 mDrawingState.sequence++;
890 mDrawingState.modified = true;
891 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700892
Robert Carr6a160312021-05-17 12:08:20 -0700893 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700894 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700895 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700896 }
chaviw606e5cf2019-03-01 10:12:10 -0800897 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700898 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700899
900 setTransactionFlags(eTransactionNeeded);
901
902 return true;
903}
904
Winson Chunga30f7c92021-06-29 15:42:56 -0700905bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
906 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
907 mDrawingState.isTrustedOverlay = isTrustedOverlay;
908 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000909 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700910 setTransactionFlags(eTransactionNeeded);
911 return true;
912}
913
914bool Layer::isTrustedOverlay() const {
915 if (getDrawingState().isTrustedOverlay) {
916 return true;
917 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000918 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700919 return (p != nullptr) && p->isTrustedOverlay();
920}
921
Dan Stoza9e56aa02015-11-02 13:00:03 -0800922bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700923 if (mDrawingState.color.a == alpha) return false;
924 mDrawingState.sequence++;
925 mDrawingState.color.a = alpha;
926 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800927 setTransactionFlags(eTransactionNeeded);
928 return true;
929}
chaviw13fdc492017-06-27 12:40:18 -0700930
Valerie Haudd0b7572019-01-29 14:59:27 -0800931bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700932 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700933 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800934 }
Robert Carr6a160312021-05-17 12:08:20 -0700935 mDrawingState.sequence++;
936 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800937 setTransactionFlags(eTransactionNeeded);
938
Robert Carr6a160312021-05-17 12:08:20 -0700939 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -0800940 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -0800941 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700942 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -0700943 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800944 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700945 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -0700946
Valerie Haudd0b7572019-01-29 14:59:27 -0800947 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -0700948 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -0800949 mFlinger->mLayersAdded = true;
950 // set up SF to handle added color layer
951 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -0700952 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -0800953 }
954 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -0700955 } else if (mDrawingState.bgColorLayer && alpha == 0) {
956 mDrawingState.bgColorLayer->reparent(nullptr);
957 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -0800958 return true;
959 }
960
Robert Carr6a160312021-05-17 12:08:20 -0700961 mDrawingState.bgColorLayer->setColor(color);
962 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
963 mDrawingState.bgColorLayer->setAlpha(alpha);
964 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -0800965
chaviw13fdc492017-06-27 12:40:18 -0700966 return true;
967}
968
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700969bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -0700970 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700971
Robert Carr6a160312021-05-17 12:08:20 -0700972 mDrawingState.sequence++;
973 mDrawingState.cornerRadius = cornerRadius;
974 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700975 setTransactionFlags(eTransactionNeeded);
976 return true;
977}
978
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800979bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -0700980 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -0700981 // If we start or stop drawing blur then the layer's visibility state may change so increment
982 // the magic sequence number.
983 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
984 mDrawingState.sequence++;
985 }
Robert Carr6a160312021-05-17 12:08:20 -0700986 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
987 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800988 setTransactionFlags(eTransactionNeeded);
989 return true;
990}
Marissa Wall61c58622018-07-18 10:12:20 -0700991
Mathias Agopian13127d82013-03-05 17:47:11 -0800992bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +0000993 mDrawingState.sequence++;
994 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -0700995 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800996 setTransactionFlags(eTransactionNeeded);
997 return true;
998}
Ana Krulecc84d09b2019-11-02 23:10:29 +0100999
Lucas Dupinc3800b82020-10-02 16:24:48 -07001000bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001001 // If we start or stop drawing blur then the layer's visibility state may change so increment
1002 // the magic sequence number.
1003 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1004 mDrawingState.sequence++;
1005 }
Robert Carr6a160312021-05-17 12:08:20 -07001006 mDrawingState.blurRegions = blurRegions;
1007 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001008 setTransactionFlags(eTransactionNeeded);
1009 return true;
1010}
1011
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001012bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001013 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1014 if (mDrawingState.flags == newFlags) return false;
1015 mDrawingState.sequence++;
1016 mDrawingState.flags = newFlags;
1017 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001018 setTransactionFlags(eTransactionNeeded);
1019 return true;
1020}
Robert Carr99e27f02016-06-16 15:18:02 -07001021
chaviw25714502021-02-11 10:01:08 -08001022bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001023 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001024 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001025 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001026
Robert Carr6a160312021-05-17 12:08:20 -07001027 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001028 setTransactionFlags(eTransactionNeeded);
1029 return true;
1030}
Robert Carr8d5227b2017-03-16 15:41:03 -07001031
Evan Roskyef876c92019-01-25 17:46:06 -08001032bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001033 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1034 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001035 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001036 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001037}
1038
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001039bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001040 if (mDrawingState.layerStack == layerStack) return false;
1041 mDrawingState.sequence++;
1042 mDrawingState.layerStack = layerStack;
1043 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001044 setTransactionFlags(eTransactionNeeded);
1045 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001046}
1047
Peiyong Linc502cb72019-03-01 15:00:23 -08001048bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001049 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001050 return false;
1051 }
Robert Carr6a160312021-05-17 12:08:20 -07001052 mDrawingState.sequence++;
1053 mDrawingState.colorSpaceAgnostic = agnostic;
1054 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001055 setTransactionFlags(eTransactionNeeded);
1056 return true;
1057}
1058
Sally Qi81d95e62022-03-21 19:41:33 -07001059bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1060 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1061
1062 mDrawingState.sequence++;
1063 mDrawingState.dimmingEnabled = dimmingEnabled;
1064 mDrawingState.modified = true;
1065 setTransactionFlags(eTransactionNeeded);
1066 return true;
1067}
1068
Ana Krulecc84d09b2019-11-02 23:10:29 +01001069bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001070 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1071 mDrawingState.frameRateSelectionPriority = priority;
1072 mDrawingState.sequence++;
1073 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001074 setTransactionFlags(eTransactionNeeded);
1075 return true;
1076}
1077
1078int32_t Layer::getFrameRateSelectionPriority() const {
1079 // Check if layer has priority set.
1080 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1081 return mDrawingState.frameRateSelectionPriority;
1082 }
1083 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001084 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001085 if (parent != nullptr) {
1086 return parent->getFrameRateSelectionPriority();
1087 }
1088
1089 return Layer::PRIORITY_UNSET;
1090}
1091
Andy Labrada096227e2022-06-15 16:58:11 +00001092bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1093 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1094 mDrawingState.defaultFrameRateCompatibility = compatibility;
1095 mDrawingState.modified = true;
1096 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1097 setTransactionFlags(eTransactionNeeded);
1098 return true;
1099}
1100
1101scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1102 return mDrawingState.defaultFrameRateCompatibility;
1103}
1104
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001105bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1106 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1107};
1108
Vishnu Nair73908d12022-10-24 21:46:42 -07001109ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1110 bool useDrawing = state == LayerVector::StateSet::Drawing;
1111 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1112 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001113 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001114 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001115 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001116}
1117
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001118bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001119 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001120 return false;
1121 }
1122
Robert Carr6a160312021-05-17 12:08:20 -07001123 mDrawingState.sequence++;
1124 mDrawingState.shadowRadius = shadowRadius;
1125 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001126 setTransactionFlags(eTransactionNeeded);
1127 return true;
1128}
1129
Vishnu Nair6213bd92020-05-08 17:42:25 -07001130bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001131 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001132 return false;
1133 }
1134
Robert Carr6a160312021-05-17 12:08:20 -07001135 mDrawingState.sequence++;
1136 mDrawingState.fixedTransformHint = fixedTransformHint;
1137 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001138 setTransactionFlags(eTransactionNeeded);
1139 return true;
1140}
1141
John Reckcdb4ed72021-02-04 13:39:33 -05001142bool Layer::setStretchEffect(const StretchEffect& effect) {
1143 StretchEffect temp = effect;
1144 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001145 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001146 return false;
1147 }
Robert Carr6a160312021-05-17 12:08:20 -07001148 mDrawingState.sequence++;
1149 mDrawingState.stretchEffect = temp;
1150 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001151 setTransactionFlags(eTransactionNeeded);
1152 return true;
1153}
1154
John Reckc00c6692021-02-16 11:37:33 -05001155StretchEffect Layer::getStretchEffect() const {
1156 if (mDrawingState.stretchEffect.hasEffect()) {
1157 return mDrawingState.stretchEffect;
1158 }
1159
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001160 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001161 if (parent != nullptr) {
1162 auto effect = parent->getStretchEffect();
1163 if (effect.hasEffect()) {
1164 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1165 return effect;
1166 }
1167 }
1168 return StretchEffect{};
1169}
1170
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001171bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1172 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001173 return false;
1174 }
1175 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001176 mBorderWidth = width;
1177 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001178 return true;
1179}
1180
1181bool Layer::isBorderEnabled() {
1182 return mBorderEnabled;
1183}
1184
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001185float Layer::getBorderWidth() {
1186 return mBorderWidth;
1187}
1188
1189const half4& Layer::getBorderColor() {
1190 return mBorderColor;
1191}
1192
Ady Abrahama850c182021-08-04 13:04:37 -07001193bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1194 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1195 const auto frameRate = [&] {
1196 if (mDrawingState.frameRate.rate.isValid() ||
1197 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1198 return mDrawingState.frameRate;
1199 }
1200
1201 return parentFrameRate;
1202 }();
1203
1204 *transactionNeeded |= setFrameRateForLayerTree(frameRate);
1205
1206 // The frame rate is propagated to the children
1207 bool childrenHaveFrameRate = false;
1208 for (const sp<Layer>& child : mCurrentChildren) {
1209 childrenHaveFrameRate |=
1210 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1211 }
1212
1213 // If we don't have a valid frame rate, but the children do, we set this
1214 // layer as NoVote to allow the children to control the refresh rate
1215 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1216 childrenHaveFrameRate) {
1217 *transactionNeeded |=
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001218 setFrameRateForLayerTree(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001219 }
1220
1221 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1222 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001223 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001224 const auto layerVotedWithDefaultCompatibility =
1225 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1226 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1227 const auto layerVotedWithExactCompatibility =
1228 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1229 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1230 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1231}
1232
Ady Abraham60e42ea2020-03-09 19:17:31 -07001233void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001234 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001235 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001236 while (auto parent = layer->getParent()) {
1237 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001238 }
Ady Abrahama850c182021-08-04 13:04:37 -07001239 return layer;
1240 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001241
Ady Abraham60e42ea2020-03-09 19:17:31 -07001242 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001243 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001244
Ady Abrahama850c182021-08-04 13:04:37 -07001245 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001246 if (transactionNeeded) {
1247 mFlinger->setTransactionFlags(eTraversalNeeded);
1248 }
1249}
1250
Ady Abraham71c437d2020-01-31 15:56:57 -08001251bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001252 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001253 return false;
1254 }
1255
Robert Carr6a160312021-05-17 12:08:20 -07001256 mDrawingState.sequence++;
1257 mDrawingState.frameRate = frameRate;
1258 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001259
1260 updateTreeHasFrameRateVote();
1261
Steven Thomas3172e202020-01-06 19:25:30 -08001262 setTransactionFlags(eTransactionNeeded);
1263 return true;
1264}
1265
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001266void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1267 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001268 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001269
1270 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1271 // there are two transactions with the same token, the first one without a buffer and the
1272 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1273 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001274 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1275 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001276 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001277 mDrawingState.bufferSurfaceFrameTX = it->second;
1278 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1279 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1280 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001281 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001282 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001283 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1284 }
1285}
1286
1287void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1288 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001289 mDrawingState.frameTimelineInfo = info;
1290 mDrawingState.postTime = postTime;
1291 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001292 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001293
Robert Carr6a160312021-05-17 12:08:20 -07001294 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001295 bufferSurfaceFrameTX != nullptr) {
1296 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1297 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1298 // being used for BufferSurfaceFrame, don't create a new one.
1299 return;
1300 }
1301 }
1302 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1303 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1304 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001305 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1306 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001307 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001308 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001309 } else {
1310 if (it->second->getPresentState() == PresentState::Presented) {
1311 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1312 // have been from previous vsync.
1313 it->second = createSurfaceFrameForTransaction(info, postTime);
1314 }
1315 }
1316}
1317
1318void Layer::addSurfaceFrameDroppedForBuffer(
1319 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001320 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001321 surfaceFrame->setPresentState(PresentState::Dropped);
1322 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1323}
1324
1325void Layer::addSurfaceFramePresentedForBuffer(
1326 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1327 nsecs_t currentLatchTime) {
1328 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1329 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1330 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1331 mLastLatchTime = currentLatchTime;
1332}
1333
1334std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1335 const FrameTimelineInfo& info, nsecs_t postTime) {
1336 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001337 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1338 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001339 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001340 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001341 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001342 // For Transactions, the post time is considered to be both queue and acquire fence time.
1343 surfaceFrame->setActualQueueTime(postTime);
1344 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001345 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1346 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001347 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001348 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001349 onSurfaceFrameCreated(surfaceFrame);
1350 return surfaceFrame;
1351}
1352
1353std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1354 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1355 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001356 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001357 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001358 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001359 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001360 // For buffers, acquire fence time will set during latch.
1361 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001362 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1363 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001364 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001365 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001366 onSurfaceFrameCreated(surfaceFrame);
1367 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001368}
1369
Ady Abrahama850c182021-08-04 13:04:37 -07001370bool Layer::setFrameRateForLayerTree(FrameRate frameRate) {
1371 if (mDrawingState.frameRateForLayerTree == frameRate) {
1372 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001373 }
1374
Ady Abrahama850c182021-08-04 13:04:37 -07001375 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001376
Ady Abrahama850c182021-08-04 13:04:37 -07001377 // TODO(b/195668952): we probably don't need to dirty visible regions here
1378 // or even store frameRateForLayerTree in mDrawingState
1379 mDrawingState.sequence++;
1380 mDrawingState.modified = true;
1381 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001382
Dominik Laskowski068173d2021-08-11 17:22:59 -07001383 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
1384 mFlinger->mScheduler->recordLayerHistory(this, systemTime(), LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001385
1386 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001387}
1388
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001389Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1390 return getDrawingState().frameRateForLayerTree;
1391}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001392
Robert Carr1f0a16a2016-10-24 16:27:39 -07001393bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001394 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001395 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001396 if (parent != nullptr && parent->isHiddenByPolicy()) {
1397 return true;
1398 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001399 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1400 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1401 if (zOrderRelativeOf != nullptr) {
1402 if (zOrderRelativeOf->isHiddenByPolicy()) {
1403 return true;
1404 }
1405 }
1406 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001407 if (CC_UNLIKELY(!isTransformValid())) {
1408 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1409 return true;
1410 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001411 return s.flags & layer_state_t::eLayerHidden;
1412}
1413
David Sodman41fdfc92017-11-06 16:09:56 -08001414uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001415 // TODO: should we do something special if mSecure is set?
1416 if (mProtectedByApp) {
1417 // need a hardware-protected path to external video sink
1418 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001419 }
Riley Andrews03414a12014-07-01 14:22:59 -07001420 if (mPotentialCursor) {
1421 usage |= GraphicBuffer::USAGE_CURSOR;
1422 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001423 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001424 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001425}
1426
Vishnu Nair71fcf912022-10-18 09:14:20 -07001427void Layer::skipReportingTransformHint() {
1428 mSkipReportingTransformHint = true;
1429}
1430
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001431void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1432 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1433 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001434 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001435
Vishnu Nair6213bd92020-05-08 17:42:25 -07001436 setTransformHint(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001437}
1438
Mathias Agopian13127d82013-03-05 17:47:11 -08001439// ----------------------------------------------------------------------------
1440// debugging
1441// ----------------------------------------------------------------------------
1442
Marissa Wall61c58622018-07-18 10:12:20 -07001443// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001444gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001445 using namespace std::string_literals;
1446
Huihong Luo05539a12022-02-23 10:29:40 -08001447 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001448 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001449 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001450 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001451 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001452 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001453
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001454 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001455 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001456 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001457 info.mX = ds.transform.tx();
1458 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001459 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001460 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001461 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001462 info.mFlags = ds.flags;
1463 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001464 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001465 info.mMatrix[0][0] = ds.transform[0][0];
1466 info.mMatrix[0][1] = ds.transform[0][1];
1467 info.mMatrix[1][0] = ds.transform[1][0];
1468 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001469 {
chaviwd62d3062019-09-04 14:48:02 -07001470 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001471 if (buffer != 0) {
1472 info.mActiveBufferWidth = buffer->getWidth();
1473 info.mActiveBufferHeight = buffer->getHeight();
1474 info.mActiveBufferStride = buffer->getStride();
1475 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001476 } else {
1477 info.mActiveBufferWidth = 0;
1478 info.mActiveBufferHeight = 0;
1479 info.mActiveBufferStride = 0;
1480 info.mActiveBufferFormat = 0;
1481 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001482 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001483 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001484 info.mIsOpaque = isOpaque(ds);
1485 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001486 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001487 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001488}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001489
Yiwei Zhang5434a782018-12-05 18:06:32 -08001490void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001491 result.append(kDumpTableRowLength, '-');
1492 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001493 result.append(" Layer name\n");
1494 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001495 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001496 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001497 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001498 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001499 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001500 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1501 result.append(kDumpTableRowLength, '-');
1502 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001503}
1504
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001505void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1506 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001507 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001508 return;
1509 }
1510
Yiwei Zhang5434a782018-12-05 18:06:32 -08001511 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001512 if (mName.length() > 77) {
1513 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001514 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001515 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001516 shortened.append(mName, mName.length() - 36);
1517 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001518 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001519 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001520 }
1521
Yiwei Zhang5434a782018-12-05 18:06:32 -08001522 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001523
Alec Mourib416efd2018-09-06 21:01:59 +00001524 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001525 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001526
Chia-I Wu1e043612018-03-01 09:45:09 -08001527 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001528 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001529 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001530 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001531 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001532 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001533 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001534 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1535 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001536 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001537 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001538 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001539 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001540 const auto frameRate = getFrameRateForLayerTree();
1541 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1542 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001543 ftl::enum_string(frameRate.type).c_str(),
1544 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001545 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001546 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001547 }
Dan Stozae22aec72016-08-01 13:20:59 -07001548
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001549 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1550 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1551
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001552 result.append(kDumpTableRowLength, '-');
1553 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001554}
Dan Stozae22aec72016-08-01 13:20:59 -07001555
Yiwei Zhang5434a782018-12-05 18:06:32 -08001556void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001557 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001558}
1559
Svetoslavd85084b2014-03-20 10:28:31 -07001560void Layer::clearFrameStats() {
1561 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001562}
1563
Jamie Gennis6547ff42013-07-16 20:12:42 -07001564void Layer::logFrameStats() {
1565 mFrameTracker.logAndResetStats(mName);
1566}
1567
Svetoslavd85084b2014-03-20 10:28:31 -07001568void Layer::getFrameStats(FrameStats* outStats) const {
1569 mFrameTracker.getStats(outStats);
1570}
1571
Vishnu Nair76554eb2022-12-09 03:38:36 +00001572void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1573 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
1574 StringAppendF(&result, "Layer %s%s pid:%d uid:%d\n", getName().c_str(), hasBuffer.c_str(),
Vishnu Naircb8be502022-10-12 19:03:23 +00001575 mOwnerPid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001576}
1577
Brian Anderson5ea5e592016-12-01 16:54:33 -08001578void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001579 const int32_t layerId = getSequence();
1580 mFlinger->mTimeStats->onDestroy(layerId);
1581 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001582}
1583
Chia-I Wu98f1c102017-05-30 14:54:08 -07001584size_t Layer::getChildrenCount() const {
1585 size_t count = 0;
1586 for (const sp<Layer>& child : mCurrentChildren) {
1587 count += 1 + child->getChildrenCount();
1588 }
1589 return count;
1590}
1591
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001592void Layer::setGameModeForTree(GameMode gameMode) {
1593 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001594 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1595 gameMode =
1596 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001597 }
1598 setGameMode(gameMode);
1599 for (const sp<Layer>& child : mCurrentChildren) {
1600 child->setGameModeForTree(gameMode);
1601 }
1602}
1603
Robert Carr1f0a16a2016-10-24 16:27:39 -07001604void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001605 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001606 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001607
Robert Carr1f0a16a2016-10-24 16:27:39 -07001608 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001609 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001610 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001611 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001612}
1613
1614ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001615 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001616 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001617
Robert Carr1323c952019-01-28 18:13:27 -08001618 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001619 const auto removeResult = mCurrentChildren.remove(layer);
1620
1621 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001622 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001623 layer->updateTreeHasFrameRateVote();
1624
1625 return removeResult;
1626}
1627
Robert Carr15eae092018-03-23 13:43:53 -07001628void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001629 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001630 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001631 const float parentShadowRadius =
1632 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001633 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001634 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001635 }
1636}
1637
chaviwf1961f72017-09-18 16:41:07 -07001638bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001639 sp<Layer> newParent;
1640 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001641 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001642 if (newParent == nullptr) {
1643 ALOGE("Unable to promote Layer handle");
1644 return false;
1645 }
1646 if (newParent == this) {
1647 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1648 return false;
1649 }
1650 }
1651
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001652 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001653 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001654 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001655 }
1656
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001657 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001658 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001659 if (!newParent->isRemovedFromCurrentState()) {
1660 addToCurrentState();
1661 } else {
1662 onRemovedFromCurrentState();
1663 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001664 } else {
1665 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001666 }
1667
chaviw06178942017-07-27 10:25:59 -07001668 return true;
1669}
1670
Peiyong Lind3788632018-09-18 16:01:31 -07001671bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001672 static const mat4 identityMatrix = mat4();
1673
Robert Carr6a160312021-05-17 12:08:20 -07001674 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001675 return false;
1676 }
Robert Carr6a160312021-05-17 12:08:20 -07001677 ++mDrawingState.sequence;
1678 mDrawingState.colorTransform = matrix;
1679 mDrawingState.hasColorTransform = matrix != identityMatrix;
1680 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001681 setTransactionFlags(eTransactionNeeded);
1682 return true;
1683}
1684
chaviwf66724d2018-11-28 16:35:21 -08001685mat4 Layer::getColorTransform() const {
1686 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001687 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001688 colorTransform = parent->getColorTransform() * colorTransform;
1689 }
1690 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001691}
1692
1693bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001694 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001695 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001696 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1697 }
1698 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001699}
1700
Chia-I Wu11481472018-05-04 10:43:19 -07001701bool Layer::isLegacyDataSpace() const {
1702 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001703 return !(getDataSpace() &
1704 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1705 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001706}
1707
Robert Carr1f0a16a2016-10-24 16:27:39 -07001708void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001709 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001710}
1711
Robert Carr6a160312021-05-17 12:08:20 -07001712int32_t Layer::getZ(LayerVector::StateSet) const {
1713 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001714}
1715
Robert Carr1c5481e2019-07-01 14:42:27 -07001716bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001717 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001718 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001719 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001720}
1721
David Sodman41fdfc92017-11-06 16:09:56 -08001722__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001723 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001724 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1725 "makeTraversalList received invalid stateSet");
1726 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1727 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001728 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001729
Robert Carr29abff82017-12-04 13:51:20 -08001730 if (state.zOrderRelatives.size() == 0) {
1731 *outSkipRelativeZUsers = true;
1732 return children;
1733 }
1734
chaviwfd462612018-05-31 16:11:27 -07001735 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001736 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001737 sp<Layer> strongRelative = weakRelative.promote();
1738 if (strongRelative != nullptr) {
1739 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001740 }
1741 }
1742
Dan Stoza412903f2017-04-27 13:42:17 -07001743 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001744 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001745 continue;
1746 }
Robert Carrdb66e622017-04-10 16:55:57 -07001747 traverse.add(child);
1748 }
1749
1750 return traverse;
1751}
1752
Robert Carr1f0a16a2016-10-24 16:27:39 -07001753/**
Robert Carrdb66e622017-04-10 16:55:57 -07001754 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001755 */
Dan Stoza412903f2017-04-27 13:42:17 -07001756void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001757 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1758 // produce a new list for traversing, including our relatives, and not including our children
1759 // who are relatives of another surface. In the case that there are no relative Z,
1760 // makeTraversalList returns our children directly to avoid significant overhead.
1761 // However in this case we need to take the responsibility for filtering children which
1762 // are relatives of another surface here.
1763 bool skipRelativeZUsers = false;
1764 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001765
Robert Carr1f0a16a2016-10-24 16:27:39 -07001766 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001767 for (; i < list.size(); i++) {
1768 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001769 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1770 continue;
1771 }
1772
chaviw301b1d82019-11-06 13:15:09 -08001773 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001774 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001775 }
Dan Stoza412903f2017-04-27 13:42:17 -07001776 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001777 }
Robert Carr29abff82017-12-04 13:51:20 -08001778
Dan Stoza412903f2017-04-27 13:42:17 -07001779 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001780 for (; i < list.size(); i++) {
1781 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001782
Robert Carr29abff82017-12-04 13:51:20 -08001783 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1784 continue;
1785 }
Dan Stoza412903f2017-04-27 13:42:17 -07001786 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001787 }
1788}
1789
1790/**
Robert Carrdb66e622017-04-10 16:55:57 -07001791 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001792 */
Dan Stoza412903f2017-04-27 13:42:17 -07001793void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1794 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001795 // See traverseInZOrder for documentation.
1796 bool skipRelativeZUsers = false;
1797 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001798
Robert Carr1f0a16a2016-10-24 16:27:39 -07001799 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001800 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001801 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001802
1803 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1804 continue;
1805 }
1806
chaviw301b1d82019-11-06 13:15:09 -08001807 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001808 break;
1809 }
Dan Stoza412903f2017-04-27 13:42:17 -07001810 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001811 }
Dan Stoza412903f2017-04-27 13:42:17 -07001812 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001813 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001814 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001815
1816 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1817 continue;
1818 }
1819
Dan Stoza412903f2017-04-27 13:42:17 -07001820 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001821 }
1822}
1823
Edgar Arriaga844fa672020-01-16 14:21:42 -08001824void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1825 visitor(this);
1826 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001827 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001828 for (const sp<Layer>& child : children) {
1829 child->traverse(state, visitor);
1830 }
1831}
1832
chaviw4b129c22018-04-09 16:19:43 -07001833LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1834 const std::vector<Layer*>& layersInTree) {
1835 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1836 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001837 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1838 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001839 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001840
chaviwfd462612018-05-31 16:11:27 -07001841 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001842 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1843 sp<Layer> strongRelative = weakRelative.promote();
1844 // Only add relative layers that are also descendents of the top most parent of the tree.
1845 // If a relative layer is not a descendent, then it should be ignored.
1846 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1847 traverse.add(strongRelative);
1848 }
1849 }
1850
1851 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001852 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001853 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1854 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1855 // the child here since it won't be added later as a relative.
1856 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1857 childState.zOrderRelativeOf.promote().get())) {
1858 continue;
1859 }
1860 traverse.add(child);
1861 }
1862
1863 return traverse;
1864}
1865
1866void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1867 LayerVector::StateSet stateSet,
1868 const LayerVector::Visitor& visitor) {
1869 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001870
1871 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001872 for (; i < list.size(); i++) {
1873 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001874 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001875 break;
1876 }
chaviw4b129c22018-04-09 16:19:43 -07001877 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001878 }
chaviw4b129c22018-04-09 16:19:43 -07001879
chaviwa76b2712017-09-20 12:02:26 -07001880 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001881 for (; i < list.size(); i++) {
1882 const auto& relative = list[i];
1883 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001884 }
1885}
1886
chaviw4b129c22018-04-09 16:19:43 -07001887std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1888 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1889 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1890
1891 std::vector<Layer*> layersInTree = {this};
1892 for (size_t i = 0; i < children.size(); i++) {
1893 const auto& child = children[i];
1894 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1895 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1896 }
1897
1898 return layersInTree;
1899}
1900
1901void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1902 const LayerVector::Visitor& visitor) {
1903 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1904 std::sort(layersInTree.begin(), layersInTree.end());
1905 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1906}
1907
Peiyong Linefefaac2018-08-17 12:27:51 -07001908ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001909 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001910}
1911
Garfield Tan2c1782c2022-02-16 15:25:05 -08001912bool Layer::isTransformValid() const {
1913 float transformDet = getTransform().det();
1914 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1915}
1916
chaviw13fdc492017-06-27 12:40:18 -07001917half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001918 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001919
chaviw13fdc492017-06-27 12:40:18 -07001920 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1921 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07001922}
Robert Carr6452f122017-03-21 10:41:29 -07001923
Vishnu Nair6213bd92020-05-08 17:42:25 -07001924ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07001925 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001926 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
1927 return fixedTransformHint;
1928 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001929 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07001930 if (!p) return fixedTransformHint;
1931 return p->getFixedTransformHint();
1932}
1933
chaviw13fdc492017-06-27 12:40:18 -07001934half4 Layer::getColor() const {
1935 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001936 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07001937}
Robert Carr6452f122017-03-21 10:41:29 -07001938
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001939int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00001940 if (getDrawingState().backgroundBlurRadius == 0) {
1941 return 0;
1942 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01001943
Vishnu Nair29810f72022-07-01 16:38:41 +00001944 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01001945 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1946 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001947}
1948
Galia Peychevae0acf382021-04-12 21:22:34 +02001949const std::vector<BlurRegion> Layer::getBlurRegions() const {
1950 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02001951 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02001952 for (auto& region : regionsCopy) {
1953 region.alpha = region.alpha * layerAlpha;
1954 }
1955 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001956}
1957
Vishnu Naire14c6b32022-08-06 04:20:15 +00001958RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001959 // Get parent settings
1960 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001961 const auto& parent = mDrawingParent.promote();
1962 if (parent != nullptr) {
1963 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001964 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001965 ui::Transform t = getActiveTransform(getDrawingState());
1966 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001967 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001968 parentSettings.radius.x *= t.getScaleX();
1969 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001970 }
1971 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001972
1973 // Get layer settings
1974 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001975 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001976 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001977 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001978
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001979 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001980 // If the parent and the layer have rounded corner settings, use the parent settings if the
1981 // parent crop is entirely inside the layer crop.
1982 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
1983 if (parentSettings.cropRect.left > layerCropRect.left &&
1984 parentSettings.cropRect.top > layerCropRect.top &&
1985 parentSettings.cropRect.right < layerCropRect.right &&
1986 parentSettings.cropRect.bottom < layerCropRect.bottom) {
1987 return parentSettings;
1988 } else {
1989 return layerSettings;
1990 }
Vishnu Nairb1845592021-10-07 12:17:57 -07001991 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001992 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001993 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001994 return parentSettings;
1995 }
1996 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001997}
1998
Robert Carr88b85e12022-03-21 15:47:35 -07001999bool Layer::findInHierarchy(const sp<Layer>& l) {
2000 if (l == this) {
2001 return true;
2002 }
2003 for (auto& child : mDrawingChildren) {
2004 if (child->findInHierarchy(l)) {
2005 return true;
2006 }
2007 }
2008 return false;
2009}
2010
Robert Carr1f0a16a2016-10-24 16:27:39 -07002011void Layer::commitChildList() {
2012 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2013 const auto& child = mCurrentChildren[i];
2014 child->commitChildList();
2015 }
2016 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002017 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002018 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2019 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2020 if (zOrderRelativeOf == nullptr) return;
2021 if (findInHierarchy(zOrderRelativeOf)) {
2022 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2023 zOrderRelativeOf->mName.c_str());
2024 ALOGE("Severing rel Z loop, potentially dangerous");
2025 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002026 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002027 }
2028 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002029}
2030
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002031
chaviw3277faf2021-05-19 16:45:23 -05002032void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002033 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002034 mDrawingState.touchableRegionCrop =
2035 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002036 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002037 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002038 setTransactionFlags(eTransactionNeeded);
2039}
2040
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002041LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002042 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002043 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002044 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2045
Vishnu Nair00b90132021-11-05 14:03:40 -07002046 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002047 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2048
Vishnu Nair60db8c02020-04-02 11:55:16 -07002049 // Only populate for the primary display.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002050 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -05002051 const auto compositionType = getCompositionType(*display);
Vishnu Nair60db8c02020-04-02 11:55:16 -07002052 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002053 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2054 [&]() { return layerProto->mutable_visible_region(); });
Vishnu Nair60db8c02020-04-02 11:55:16 -07002055 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08002056 }
2057
chaviw08f3cb22020-01-13 13:17:21 -08002058 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002059 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002060 }
chaviw6d89e2d2020-01-14 14:42:01 -08002061
2062 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002063}
2064
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002065void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002066 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002067 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002068 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002069 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002070 [&]() { return layerInfo->mutable_active_buffer(); });
2071 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2072 layerInfo->mutable_buffer_transform());
2073 }
2074 layerInfo->set_invalidate(contentDirty);
2075 layerInfo->set_is_protected(isProtected());
2076 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2077 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002078 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002079 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002080 layerInfo->set_corner_radius(
2081 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002082 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2083 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2084 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2085 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2086 [&]() { return layerInfo->mutable_position(); });
2087 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002088 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2089 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002090
Vishnu Nair00b90132021-11-05 14:03:40 -07002091 if (hasColorTransform()) {
2092 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002093 }
2094
Vishnu Nair60db8c02020-04-02 11:55:16 -07002095 LayerProtoHelper::writeToProto(mSourceBounds,
2096 [&]() { return layerInfo->mutable_source_bounds(); });
2097 LayerProtoHelper::writeToProto(mScreenBounds,
2098 [&]() { return layerInfo->mutable_screen_bounds(); });
2099 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2100 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2101 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002102}
2103
2104void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002105 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002106 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2107 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002108 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002109
chaviw766c9c52021-02-10 17:36:47 -08002110 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002111
Vishnu Nair00b90132021-11-05 14:03:40 -07002112 layerInfo->set_id(sequence);
2113 layerInfo->set_name(getName().c_str());
2114 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002115
Vishnu Nair00b90132021-11-05 14:03:40 -07002116 for (const auto& child : children) {
2117 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002118 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002119
Vishnu Nair00b90132021-11-05 14:03:40 -07002120 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2121 sp<Layer> strongRelative = weakRelative.promote();
2122 if (strongRelative != nullptr) {
2123 layerInfo->add_relatives(strongRelative->sequence);
2124 }
2125 }
2126
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002127 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002128 [&]() { return layerInfo->mutable_transparent_region(); });
2129
2130 layerInfo->set_layer_stack(getLayerStack().id);
2131 layerInfo->set_z(state.z);
2132
2133 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2134 return layerInfo->mutable_requested_position();
2135 });
2136
Vishnu Nair00b90132021-11-05 14:03:40 -07002137 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2138
2139 layerInfo->set_is_opaque(isOpaque(state));
2140
2141 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2142 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2143 LayerProtoHelper::writeToProto(state.color,
2144 [&]() { return layerInfo->mutable_requested_color(); });
2145 layerInfo->set_flags(state.flags);
2146
2147 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2148 layerInfo->mutable_requested_transform());
2149
2150 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2151 if (parent != nullptr) {
2152 layerInfo->set_parent(parent->sequence);
2153 } else {
2154 layerInfo->set_parent(-1);
2155 }
2156
2157 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2158 if (zOrderRelativeOf != nullptr) {
2159 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2160 } else {
2161 layerInfo->set_z_order_relative_of(-1);
2162 }
2163
2164 layerInfo->set_is_relative_of(state.isRelativeOf);
2165
2166 layerInfo->set_owner_uid(mOwnerUid);
2167
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002168 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002169 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002170 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002171 info = fillInputInfo(
2172 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002173 } else {
2174 info = state.inputInfo;
2175 }
2176
2177 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002178 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002179 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002180
Vishnu Nair00b90132021-11-05 14:03:40 -07002181 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002182 auto protoMap = layerInfo->mutable_metadata();
2183 for (const auto& entry : state.metadata.mMap) {
2184 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2185 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002186 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002187
2188 LayerProtoHelper::writeToProto(state.destinationFrame,
2189 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002190}
2191
Robert Carr2e102c92018-10-23 12:11:15 -07002192bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002193 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002194}
2195
Prabir Pradhan33da9462022-06-14 14:55:57 +00002196// Applies the given transform to the region, while protecting against overflows caused by any
2197// offsets. If applying the offset in the transform to any of the Rects in the region would result
2198// in an overflow, they are not added to the output Region.
2199static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2200 const std::string& debugWindowName) {
2201 // Round the translation using the same rounding strategy used by ui::Transform.
2202 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2203 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2204
2205 ui::Transform transformWithoutOffset = t;
2206 transformWithoutOffset.set(0.f, 0.f);
2207
2208 const Region transformed = transformWithoutOffset.transform(r);
2209
2210 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2211 Region ret;
2212 for (const auto& rect : transformed) {
2213 Rect newRect;
2214 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2215 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2216 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2217 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2218 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2219 debugWindowName.c_str());
2220 continue;
2221 }
2222 ret.orSelf(newRect);
2223 }
2224 return ret;
2225}
2226
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002227void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
2228 Rect tmpBounds = getInputBounds();
2229 if (!tmpBounds.isValid()) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002230 info.touchableRegion.clear();
2231 // A layer could have invalid input bounds and still expect to receive touch input if it has
2232 // replaceTouchableRegionWithCrop. For that case, the input transform needs to be calculated
2233 // correctly to determine the coordinate space for input events. Use an empty rect so that
2234 // the layer will receive input in its own layer space.
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002235 tmpBounds = Rect::EMPTY_RECT;
chaviw7e72caf2020-12-02 16:50:43 -08002236 }
2237
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002238 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2239 // frame and transform used for the layer, which determines the bounds and the coordinate space
2240 // within which the layer will receive input.
2241 //
2242 // The coordinate space within which each of the bounds are specified is explicitly documented
2243 // in the variable name. For example "inputBoundsInLayer" is specified in layer space. A
2244 // Transform converts one coordinate space to another, which is apparent in its naming. For
2245 // example, "layerToDisplay" transforms layer space to display space.
2246 //
2247 // Coordinate space definitions:
2248 // - display: The display device's coordinate space. Correlates to pixels on the display.
2249 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2250 // - layer: The coordinate space of this layer.
2251 // - input: The coordinate space in which this layer will receive input events. This could be
2252 // different than layer space if a surfaceInset is used, which changes the origin
2253 // of the input space.
2254 const FloatRect inputBoundsInLayer = tmpBounds.toFloatRect();
chaviw7e72caf2020-12-02 16:50:43 -08002255
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002256 // Clamp surface inset to the input bounds.
2257 const auto surfaceInset = static_cast<float>(info.surfaceInset);
2258 const float xSurfaceInset =
2259 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getWidth() / 2.f));
2260 const float ySurfaceInset =
2261 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getHeight() / 2.f));
chaviw1ff3d1e2020-07-01 15:53:47 -07002262
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002263 // Apply the insets to the input bounds.
2264 const FloatRect insetBoundsInLayer(inputBoundsInLayer.left + xSurfaceInset,
2265 inputBoundsInLayer.top + ySurfaceInset,
2266 inputBoundsInLayer.right - xSurfaceInset,
2267 inputBoundsInLayer.bottom - ySurfaceInset);
Ady Abraham282f1d72019-07-24 18:05:56 -07002268
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002269 // Crop the input bounds to ensure it is within the parent's bounds.
2270 const FloatRect croppedInsetBoundsInLayer = mBounds.intersect(insetBoundsInLayer);
Ady Abraham282f1d72019-07-24 18:05:56 -07002271
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002272 const ui::Transform layerToScreen = getInputTransform();
2273 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
Vishnu Nair8033a492018-12-05 07:27:23 -08002274
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002275 const Rect roundedFrameInDisplay{layerToDisplay.transform(croppedInsetBoundsInLayer)};
2276 info.frameLeft = roundedFrameInDisplay.left;
2277 info.frameTop = roundedFrameInDisplay.top;
2278 info.frameRight = roundedFrameInDisplay.right;
2279 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002280
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002281 ui::Transform inputToLayer;
2282 inputToLayer.set(insetBoundsInLayer.left, insetBoundsInLayer.top);
2283 const ui::Transform inputToDisplay = layerToDisplay * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002284
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002285 // InputDispatcher expects a display-to-input transform.
2286 info.transform = inputToDisplay.inverse();
2287
2288 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002289 info.touchableRegion =
2290 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002291}
2292
chaviw3277faf2021-05-19 16:45:23 -05002293void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002294 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002295 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002296 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002297 }
2298 if (p != nullptr) {
2299 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2300 }
2301}
2302
Vishnu Naira066d902021-09-13 18:40:17 -07002303gui::DropInputMode Layer::getDropInputMode() const {
2304 gui::DropInputMode mode = mDrawingState.dropInputMode;
2305 if (mode == gui::DropInputMode::ALL) {
2306 return mode;
2307 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002308 sp<Layer> parent = mDrawingParent.promote();
2309 if (parent) {
2310 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002311 if (parentMode != gui::DropInputMode::NONE) {
2312 return parentMode;
2313 }
2314 }
2315 return mode;
2316}
2317
2318void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002319 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002320 return;
2321 }
2322
2323 // Check if we need to drop input unconditionally
2324 gui::DropInputMode dropInputMode = getDropInputMode();
2325 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002326 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002327 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2328 return;
2329 }
2330
2331 // Check if we need to check if the window is obscured by parent
2332 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2333 return;
2334 }
2335
2336 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002337 sp<Layer> parent = mDrawingParent.promote();
2338 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002339 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002340 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2341 static_cast<float>(getAlpha()));
2342 }
2343
2344 // Check if the parent has cropped the buffer
2345 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2346 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002347 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002348 return;
2349 }
2350
2351 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2352 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2353 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2354 // match then the layer has not been cropped by its parents.
2355 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2356 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2357
2358 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002359 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002360 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2361 getDebugName());
2362 } else {
2363 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2364 // input if the window is obscured. This check should be done in surfaceflinger but the
2365 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2366 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002367 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002368 }
2369}
2370
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002371WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002372 if (!hasInputInfo()) {
2373 mDrawingState.inputInfo.name = getName();
2374 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2375 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002376 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002377 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002378 }
2379
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002380 const ui::Transform& displayTransform =
2381 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2382
chaviw3277faf2021-05-19 16:45:23 -05002383 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002384 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002385 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002386
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002387 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002388
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002389 if (displayArgs.transform == nullptr) {
2390 // Do not let the window receive touches if it is not associated with a valid display
2391 // transform. We still allow the window to receive keys and prevent ANRs.
2392 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2393 }
2394
Robert Carr5dc426e2020-06-10 14:29:14 -07002395 // For compatibility reasons we let layers which can receive input
2396 // receive input before they have actually submitted a buffer. Because
2397 // of this we use canReceiveInput instead of isVisible to check the
2398 // policy-visibility, ignoring the buffer state. However for layers with
2399 // hasInputInfo()==false we can use the real visibility state.
2400 // We are just using these layers for occlusion detection in
2401 // InputDispatcher, and obviously if they aren't visible they can't occlude
2402 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002403 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2404 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2405
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002406 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002407 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002408 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002409
Vishnu Nair16a938f2021-09-24 07:14:54 -07002410 // If the window will be blacked out on a display because the display does not have the secure
2411 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002412 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002413 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002414 }
2415
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002416 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2417 if (info.replaceTouchableRegionWithCrop) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002418 const Rect bounds(cropLayer ? cropLayer->mScreenBounds : mScreenBounds);
2419 info.touchableRegion = Region(displayTransform.transform(bounds));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002420 } else if (cropLayer != nullptr) {
[1;3C2b9fc252021-02-04 16:16:50 -08002421 info.touchableRegion = info.touchableRegion.intersect(
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002422 displayTransform.transform(Rect{cropLayer->mScreenBounds}));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002423 }
2424
Winson Chunga30f7c92021-06-29 15:42:56 -07002425 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2426 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002427 if (isTrustedOverlay()) {
2428 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2429 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002430
chaviwaf87b3e2019-10-01 16:59:28 -07002431 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2432 // touches from going outside the cloned area.
2433 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002434 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002435 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2436 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002437 info.touchableRegion = info.touchableRegion.intersect(rect);
2438 }
2439 }
2440
Robert Carr720e5062018-07-30 17:45:14 -07002441 return info;
2442}
2443
chaviwaf87b3e2019-10-01 16:59:28 -07002444sp<Layer> Layer::getClonedRoot() {
2445 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002446 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002447 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002448 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002449 return nullptr;
2450 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002451 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002452}
2453
Robert Carredd13602020-04-13 17:24:34 -07002454bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002455 return mDrawingState.inputInfo.token != nullptr ||
2456 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002457}
2458
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002459compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002460 const DisplayDevice* display) const {
2461 if (!display) return nullptr;
Lloyd Piquede196652020-01-22 17:29:58 -08002462 return display->getCompositionDisplay()->getOutputLayerForLayer(getCompositionEngineLayerFE());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002463}
2464
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002465Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2466 const auto outputLayer = findOutputLayerForDisplay(display);
2467 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002468}
2469
chaviwb4c6e582019-08-16 14:35:07 -07002470void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002471 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002472 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002473 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2474 mPotentialCursor = clonedFrom->mPotentialCursor;
2475 mProtectedByApp = clonedFrom->mProtectedByApp;
2476 updateCloneBufferInfo();
2477}
2478
2479void Layer::updateCloneBufferInfo() {
2480 if (!isClone() || !isClonedFromAlive()) {
2481 return;
2482 }
2483
2484 sp<Layer> clonedFrom = getClonedFrom();
2485 mBufferInfo = clonedFrom->mBufferInfo;
2486 mSidebandStream = clonedFrom->mSidebandStream;
2487 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2488 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2489 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2490
2491 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2492 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2493 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2494 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2495 // the cloned drawingState again.
2496 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2497 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2498 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2499 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2500
2501 cloneDrawingState(clonedFrom.get());
2502
2503 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2504 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2505 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2506 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002507}
chaviw74b03172019-08-19 11:09:03 -07002508
2509void Layer::updateMirrorInfo() {
2510 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2511 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2512 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2513 // that case, we want to delete the reference to the clone since we want it to get
2514 // destroyed. The root, this layer, will still be around since the client can continue
2515 // to hold a reference, but no cloned layers will be displayed.
2516 mClonedChild = nullptr;
2517 return;
2518 }
2519
2520 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2521 // If the real layer exists and is in current state, add the clone as a child of the root.
2522 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2523 // copied to drawingState for the root layer. So the clonedChild is always removed from
2524 // drawingState and then needs to be added back each traversal.
2525 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2526 addChildToDrawing(mClonedChild);
2527 }
2528
2529 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002530 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002531 mClonedChild->updateClonedRelatives(clonedLayersMap);
2532}
2533
2534void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2535 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2536 // to the clone. If the real layer is no longer alive, continue traversing the children
2537 // since we may be able to pull out other children that are still alive.
2538 if (isClonedFromAlive()) {
2539 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002540 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002541 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002542 }
2543
2544 // The clone layer may have children in drawingState since they may have been created and
2545 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2546 // that already exist, since we can just re-use them.
2547 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2548 // not updated in the regular traversal. They are skipped since the root will lose the
2549 // reference to them when it copies its currentChildren to drawing.
2550 for (sp<Layer>& child : mDrawingChildren) {
2551 child->updateClonedDrawingState(clonedLayersMap);
2552 }
2553}
2554
2555void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2556 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2557 mDrawingChildren.clear();
2558
2559 if (!isClonedFromAlive()) {
2560 return;
2561 }
2562
2563 sp<Layer> clonedFrom = getClonedFrom();
2564 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2565 if (child == mirrorRoot) {
2566 // This is to avoid cyclical mirroring.
2567 continue;
2568 }
2569 sp<Layer> clonedChild = clonedLayersMap[child];
2570 if (clonedChild == nullptr) {
2571 clonedChild = child->createClone();
2572 clonedLayersMap[child] = clonedChild;
2573 }
2574 addChildToDrawing(clonedChild);
2575 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2576 }
2577}
2578
chaviwaf87b3e2019-10-01 16:59:28 -07002579void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2580 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2581 if (cropLayer != nullptr) {
2582 if (clonedLayersMap.count(cropLayer) == 0) {
2583 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2584 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002585 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002586 } else {
2587 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2588 mDrawingState.touchableRegionCrop = clonedCropLayer;
2589 }
2590 }
2591 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2592 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002593 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002594}
2595
2596void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002597 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002598 mDrawingState.zOrderRelatives.clear();
2599
2600 if (!isClonedFromAlive()) {
2601 return;
2602 }
2603
chaviwaf87b3e2019-10-01 16:59:28 -07002604 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002605 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002606 const sp<Layer>& relative = relativeWeak.promote();
2607 if (clonedLayersMap.count(relative) > 0) {
2608 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002609 mDrawingState.zOrderRelatives.add(clonedRelative);
2610 }
2611 }
2612
2613 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2614 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2615 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2616 // still traverse the children, but the layer with the missing relativeOf will not be shown
2617 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002618 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2619 if (clonedLayersMap.count(relativeOf) > 0) {
2620 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002621 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2622 }
2623
chaviwaf87b3e2019-10-01 16:59:28 -07002624 updateClonedInputInfo(clonedLayersMap);
2625
chaviw74b03172019-08-19 11:09:03 -07002626 for (sp<Layer>& child : mDrawingChildren) {
2627 child->updateClonedRelatives(clonedLayersMap);
2628 }
2629}
2630
2631void Layer::addChildToDrawing(const sp<Layer>& layer) {
2632 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002633 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002634}
2635
Steven Thomas62a4cf82020-01-31 12:04:03 -08002636Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2637 switch (compatibility) {
2638 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2639 return FrameRateCompatibility::Default;
2640 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2641 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002642 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2643 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002644 case ANATIVEWINDOW_FRAME_RATE_MIN:
2645 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002646 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2647 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002648 default:
2649 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2650 return FrameRateCompatibility::Default;
2651 }
2652}
2653
Marin Shalamanovc5986772021-03-16 16:09:49 +01002654scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2655 switch (strategy) {
2656 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2657 return Seamlessness::OnlySeamless;
2658 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2659 return Seamlessness::SeamedAndSeamless;
2660 default:
2661 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2662 return Seamlessness::Default;
2663 }
2664}
2665
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002666bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002667 const State& s(mDrawingState);
2668 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2669 return true;
2670 }
2671
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002672 sp<Layer> parent = mDrawingParent.promote();
2673 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002674}
2675
Robert Carr6a0382d2021-07-01 15:57:17 -07002676void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2677 mClonedChild = clonedChild;
2678 mHadClonedChild = true;
2679 mFlinger->mNumClones++;
2680}
2681
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002682bool Layer::setDropInputMode(gui::DropInputMode mode) {
2683 if (mDrawingState.dropInputMode == mode) {
2684 return false;
2685 }
2686 mDrawingState.dropInputMode = mode;
2687 return true;
2688}
2689
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002690void Layer::cloneDrawingState(const Layer* from) {
2691 mDrawingState = from->mDrawingState;
2692 // Skip callback info since they are not applicable for cloned layers.
2693 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002694 // TODO (b/238781169) currently broken for mirror layers because we do not
2695 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002696 mDrawingState.callbackHandles = {};
2697}
2698
Patrick Williamsbb25f802022-08-30 23:02:34 +00002699void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2700 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
2701 const sp<Fence>& releaseFence,
2702 uint32_t currentMaxAcquiredBufferCount) {
2703 if (!listener) {
2704 return;
2705 }
2706 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002707 listener->onReleaseBuffer({buffer->getId(), framenumber},
2708 releaseFence ? releaseFence : Fence::NO_FENCE,
2709 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002710}
2711
2712void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2713 // If we are displayed on multiple displays in a single composition cycle then we would
2714 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2715 // For example we can only use it if all the displays are client comp, and we need
2716 // to merge all the client comp fences. We could do this, but for now we just
2717 // disable the optimization when a layer is composed on multiple displays.
2718 if (mClearClientCompositionFenceOnLayerDisplayed) {
2719 mLastClientCompositionFence = nullptr;
2720 } else {
2721 mClearClientCompositionFenceOnLayerDisplayed = true;
2722 }
2723
2724 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2725 // buffer that was presented on this layer. The first transaction that came in this frame that
2726 // replaced the previous buffer on this layer needs this release fence, because the fence will
2727 // let the client know when that previous buffer is removed from the screen.
2728 //
2729 // Every other transaction on this layer does not need a release fence because no other
2730 // Transactions that were set on this layer this frame are going to have their preceding buffer
2731 // removed from the display this frame.
2732 //
2733 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2734 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2735 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2736 // the previous buffer will be released this frame. The third transaction also contains a
2737 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2738 // transaction will now no longer be presented so it is released immediately and the third
2739 // transaction doesn't need a previous release fence.
2740 sp<CallbackHandle> ch;
2741 for (auto& handle : mDrawingState.callbackHandles) {
2742 if (handle->releasePreviousBuffer &&
2743 mDrawingState.releaseBufferEndpoint == handle->listener) {
2744 ch = handle;
2745 break;
2746 }
2747 }
2748
2749 // Prevent tracing the same release multiple times.
2750 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2751 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2752 }
2753
2754 if (ch != nullptr) {
2755 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2756 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2757 ch->name = mName;
2758 }
2759}
2760
2761void Layer::onSurfaceFrameCreated(
2762 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2763 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2764 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2765 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2766 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002767 if (hasBufferOrSidebandStreamInDrawing()) {
2768 // Only log for layers with a buffer, since we expect the jank data to be drained for
2769 // these, while there may be no jank listeners for bufferless layers.
2770 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2771 mName.c_str());
2772 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2773 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2774 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002775 mPendingJankClassifications.pop_front();
2776 }
2777 mPendingJankClassifications.emplace_back(surfaceFrame);
2778}
2779
2780void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2781 for (const auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair71fcf912022-10-18 09:14:20 -07002782 handle->transformHint = mSkipReportingTransformHint
2783 ? std::nullopt
2784 : std::make_optional<uint32_t>(mTransformHint);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002785 handle->dequeueReadyTime = dequeueReadyTime;
2786 handle->currentMaxAcquiredBufferCount =
2787 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2788 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2789 handle->previousReleaseCallbackId.framenumber);
2790 }
2791
2792 for (auto& handle : mDrawingState.callbackHandles) {
2793 if (handle->releasePreviousBuffer &&
2794 mDrawingState.releaseBufferEndpoint == handle->listener) {
2795 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2796 break;
2797 }
2798 }
2799
2800 std::vector<JankData> jankData;
2801 jankData.reserve(mPendingJankClassifications.size());
2802 while (!mPendingJankClassifications.empty() &&
2803 mPendingJankClassifications.front()->getJankType()) {
2804 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
2805 mPendingJankClassifications.front();
2806 mPendingJankClassifications.pop_front();
2807 jankData.emplace_back(
2808 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
2809 }
2810
2811 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2812 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002813 mDrawingState.callbackHandles = {};
2814}
2815
2816bool Layer::willPresentCurrentTransaction() const {
2817 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2818 return (getSidebandStreamChanged() || getAutoRefresh() ||
2819 (mDrawingState.modified &&
2820 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2821}
2822
2823bool Layer::setTransform(uint32_t transform) {
2824 if (mDrawingState.bufferTransform == transform) return false;
2825 mDrawingState.bufferTransform = transform;
2826 mDrawingState.modified = true;
2827 setTransactionFlags(eTransactionNeeded);
2828 return true;
2829}
2830
2831bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2832 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2833 mDrawingState.sequence++;
2834 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2835 mDrawingState.modified = true;
2836 setTransactionFlags(eTransactionNeeded);
2837 return true;
2838}
2839
2840bool Layer::setBufferCrop(const Rect& bufferCrop) {
2841 if (mDrawingState.bufferCrop == bufferCrop) return false;
2842
2843 mDrawingState.sequence++;
2844 mDrawingState.bufferCrop = bufferCrop;
2845
2846 mDrawingState.modified = true;
2847 setTransactionFlags(eTransactionNeeded);
2848 return true;
2849}
2850
2851bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2852 if (mDrawingState.destinationFrame == destinationFrame) return false;
2853
2854 mDrawingState.sequence++;
2855 mDrawingState.destinationFrame = destinationFrame;
2856
2857 mDrawingState.modified = true;
2858 setTransactionFlags(eTransactionNeeded);
2859 return true;
2860}
2861
2862// Translate destination frame into scale and position. If a destination frame is not set, use the
2863// provided scale and position
2864bool Layer::updateGeometry() {
2865 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2866 mDrawingState.destinationFrame.isEmpty()) {
2867 // If destination frame is not set, use the requested transform set via
2868 // Layer::setPosition and Layer::setMatrix.
2869 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2870 }
2871
2872 Rect destRect = mDrawingState.destinationFrame;
2873 int32_t destW = destRect.width();
2874 int32_t destH = destRect.height();
2875 if (destRect.left < 0) {
2876 destRect.left = 0;
2877 destRect.right = destW;
2878 }
2879 if (destRect.top < 0) {
2880 destRect.top = 0;
2881 destRect.bottom = destH;
2882 }
2883
2884 if (!mDrawingState.buffer) {
2885 ui::Transform t;
2886 t.set(destRect.left, destRect.top);
2887 return assignTransform(&mDrawingState.transform, t);
2888 }
2889
2890 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2891 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2892 // Undo any transformations on the buffer.
2893 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2894 std::swap(bufferWidth, bufferHeight);
2895 }
2896 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
2897 if (mDrawingState.transformToDisplayInverse) {
2898 if (invTransform & ui::Transform::ROT_90) {
2899 std::swap(bufferWidth, bufferHeight);
2900 }
2901 }
2902
2903 float sx = destW / static_cast<float>(bufferWidth);
2904 float sy = destH / static_cast<float>(bufferHeight);
2905 ui::Transform t;
2906 t.set(sx, 0, 0, sy);
2907 t.set(destRect.left, destRect.top);
2908 return assignTransform(&mDrawingState.transform, t);
2909}
2910
2911bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
2912 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
2913 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
2914 return false;
2915 }
2916
2917 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
2918
2919 mDrawingState.sequence++;
2920 mDrawingState.modified = true;
2921 setTransactionFlags(eTransactionNeeded);
2922
2923 return true;
2924}
2925
2926bool Layer::setPosition(float x, float y) {
2927 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
2928 return false;
2929 }
2930
2931 mRequestedTransform.set(x, y);
2932
2933 mDrawingState.sequence++;
2934 mDrawingState.modified = true;
2935 setTransactionFlags(eTransactionNeeded);
2936
2937 return true;
2938}
2939
2940bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
2941 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
2942 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07002943 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00002944 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00002945 if (!buffer) {
2946 return false;
2947 }
2948
2949 const bool frameNumberChanged =
2950 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
2951 const uint64_t frameNumber =
2952 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00002953 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002954
2955 if (mDrawingState.buffer) {
2956 mReleasePreviousBuffer = true;
2957 if (!mBufferInfo.mBuffer ||
2958 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
2959 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
2960 // If mDrawingState has a buffer, and we are about to update again
2961 // before swapping to drawing state, then the first buffer will be
2962 // dropped and we should decrement the pending buffer count and
2963 // call any release buffer callbacks if set.
2964 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
2965 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
2966 mDrawingState.acquireFence,
2967 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
2968 mOwnerUid));
2969 decrementPendingBufferCount();
2970 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
2971 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
2972 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
2973 mDrawingState.bufferSurfaceFrameTX.reset();
2974 }
2975 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
2976 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
2977 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
2978 mLastClientCompositionFence,
2979 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
2980 mOwnerUid));
2981 mLastClientCompositionFence = nullptr;
2982 }
2983 }
2984
2985 mDrawingState.frameNumber = frameNumber;
2986 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
2987 mDrawingState.buffer = std::move(buffer);
2988 mDrawingState.clientCacheId = bufferData.cachedBuffer;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002989 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
2990 ? bufferData.acquireFence
2991 : Fence::NO_FENCE;
2992 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
2993 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
2994 // We latched this buffer unsiganled, so we need to pass the acquire fence
2995 // on the callback instead of just the acquire time, since it's unknown at
2996 // this point.
2997 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
2998 } else {
2999 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3000 }
3001
3002 mDrawingState.modified = true;
3003 setTransactionFlags(eTransactionNeeded);
3004
3005 const int32_t layerId = getSequence();
3006 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3007 mOwnerUid, postTime, getGameMode());
3008 mDrawingState.desiredPresentTime = desiredPresentTime;
3009 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3010
3011 const nsecs_t presentTime = [&] {
3012 if (!isAutoTimestamp) return desiredPresentTime;
3013
3014 const auto prediction =
3015 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
3016 if (prediction.has_value()) return prediction->presentTime;
3017
3018 return static_cast<nsecs_t>(0);
3019 }();
3020
3021 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
3022 mFlinger->mScheduler->recordLayerHistory(this, presentTime, LayerUpdateType::Buffer);
3023
3024 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3025
3026 if (dequeueTime && *dequeueTime != 0) {
3027 const uint64_t bufferId = mDrawingState.buffer->getId();
3028 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3029 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3030 FrameTracer::FrameEvent::DEQUEUE);
3031 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3032 FrameTracer::FrameEvent::QUEUE);
3033 }
3034
3035 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3036 return true;
3037}
3038
3039bool Layer::setDataspace(ui::Dataspace dataspace) {
3040 mDrawingState.dataspaceRequested = true;
3041 if (mDrawingState.dataspace == dataspace) return false;
3042 mDrawingState.dataspace = dataspace;
3043 mDrawingState.modified = true;
3044 setTransactionFlags(eTransactionNeeded);
3045 return true;
3046}
3047
John Reck68796592023-01-25 13:47:12 -05003048bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
3049 if (mDrawingState.currentSdrHdrRatio == currentBufferRatio &&
3050 mDrawingState.desiredSdrHdrRatio == desiredRatio)
3051 return false;
3052 mDrawingState.currentSdrHdrRatio = currentBufferRatio;
3053 mDrawingState.desiredSdrHdrRatio = desiredRatio;
3054 mDrawingState.modified = true;
3055 setTransactionFlags(eTransactionNeeded);
3056 return true;
3057}
3058
Patrick Williamsbb25f802022-08-30 23:02:34 +00003059bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3060 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3061 mDrawingState.hdrMetadata = hdrMetadata;
3062 mDrawingState.modified = true;
3063 setTransactionFlags(eTransactionNeeded);
3064 return true;
3065}
3066
3067bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
3068 mDrawingState.surfaceDamageRegion = surfaceDamage;
3069 mDrawingState.modified = true;
3070 setTransactionFlags(eTransactionNeeded);
3071 return true;
3072}
3073
3074bool Layer::setApi(int32_t api) {
3075 if (mDrawingState.api == api) return false;
3076 mDrawingState.api = api;
3077 mDrawingState.modified = true;
3078 setTransactionFlags(eTransactionNeeded);
3079 return true;
3080}
3081
3082bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3083 if (mDrawingState.sidebandStream == sidebandStream) return false;
3084
3085 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3086 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3087 } else if (sidebandStream != nullptr) {
3088 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3089 }
3090
3091 mDrawingState.sidebandStream = sidebandStream;
3092 mDrawingState.modified = true;
3093 setTransactionFlags(eTransactionNeeded);
3094 if (!mSidebandStreamChanged.exchange(true)) {
3095 // mSidebandStreamChanged was false
3096 mFlinger->onLayerUpdate();
3097 }
3098 return true;
3099}
3100
Vishnu Naird6913222023-02-01 22:56:21 +00003101bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3102 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003103 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3104 if (handles.empty()) {
3105 mReleasePreviousBuffer = false;
3106 return false;
3107 }
3108
Patrick Williamsbb25f802022-08-30 23:02:34 +00003109 for (const auto& handle : handles) {
3110 // If this transaction set a buffer on this layer, release its previous buffer
3111 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3112
3113 // If this layer will be presented in this frame
3114 if (willPresent) {
3115 // If this transaction set an acquire fence on this layer, set its acquire time
3116 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3117 handle->frameNumber = mDrawingState.frameNumber;
3118
3119 // Store so latched time and release fence can be set
3120 mDrawingState.callbackHandles.push_back(handle);
3121
3122 } else { // If this layer will NOT need to be relatched and presented this frame
3123 // Notify the transaction completed thread this handle is done
3124 mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
3125 }
3126 }
3127
3128 mReleasePreviousBuffer = false;
3129 mCallbackHandleAcquireTimeOrFence = -1;
3130
3131 return willPresent;
3132}
3133
3134Rect Layer::getBufferSize(const State& /*s*/) const {
3135 // for buffer state layers we use the display frame size as the buffer size.
3136
3137 if (mBufferInfo.mBuffer == nullptr) {
3138 return Rect::INVALID_RECT;
3139 }
3140
3141 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3142 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3143
3144 // Undo any transformations on the buffer and return the result.
3145 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3146 std::swap(bufWidth, bufHeight);
3147 }
3148
3149 if (getTransformToDisplayInverse()) {
3150 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3151 if (invTransform & ui::Transform::ROT_90) {
3152 std::swap(bufWidth, bufHeight);
3153 }
3154 }
3155
3156 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3157}
3158
3159FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3160 if (mBufferInfo.mBuffer == nullptr) {
3161 return parentBounds;
3162 }
3163
3164 return getBufferSize(getDrawingState()).toFloatRect();
3165}
3166
3167bool Layer::fenceHasSignaled() const {
3168 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3169 return true;
3170 }
3171
3172 const bool fenceSignaled =
3173 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3174 if (!fenceSignaled) {
3175 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3176 TimeStats::LatchSkipReason::LateAcquire);
3177 }
3178
3179 return fenceSignaled;
3180}
3181
Vishnu Naird6913222023-02-01 22:56:21 +00003182void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003183 for (const auto& handle : mDrawingState.callbackHandles) {
3184 handle->refreshStartTime = refreshStartTime;
3185 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003186}
3187
3188void Layer::setAutoRefresh(bool autoRefresh) {
3189 mDrawingState.autoRefresh = autoRefresh;
3190}
3191
3192bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3193 // 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 +00003194 auto* snapshot = editLayerSnapshot();
3195 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003196
3197 if (mSidebandStreamChanged.exchange(false)) {
3198 const State& s(getDrawingState());
3199 // mSidebandStreamChanged was true
3200 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003201 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003202 if (mSidebandStream != nullptr) {
3203 setTransactionFlags(eTransactionNeeded);
3204 mFlinger->setTransactionFlags(eTraversalNeeded);
3205 }
3206 recomputeVisibleRegions = true;
3207
3208 return true;
3209 }
3210 return false;
3211}
3212
3213bool Layer::hasFrameUpdate() const {
3214 const State& c(getDrawingState());
3215 return (mDrawingStateModified || mDrawingState.modified) &&
3216 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3217}
3218
3219void Layer::updateTexImage(nsecs_t latchTime) {
3220 const State& s(getDrawingState());
3221
3222 if (!s.buffer) {
3223 if (s.bgColorLayer) {
3224 for (auto& handle : mDrawingState.callbackHandles) {
3225 handle->latchTime = latchTime;
3226 }
3227 }
3228 return;
3229 }
3230
3231 for (auto& handle : mDrawingState.callbackHandles) {
3232 if (handle->frameNumber == mDrawingState.frameNumber) {
3233 handle->latchTime = latchTime;
3234 }
3235 }
3236
3237 const int32_t layerId = getSequence();
3238 const uint64_t bufferId = mDrawingState.buffer->getId();
3239 const uint64_t frameNumber = mDrawingState.frameNumber;
3240 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3241 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3242 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3243
3244 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3245 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3246 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3247 FrameTracer::FrameEvent::LATCH);
3248
3249 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3250 if (bufferSurfaceFrame != nullptr &&
3251 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3252 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3253 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3254 // are processing the next state.
3255 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3256 mDrawingState.acquireFenceTime->getSignalTime(),
3257 latchTime);
3258 mDrawingState.bufferSurfaceFrameTX.reset();
3259 }
3260
3261 std::deque<sp<CallbackHandle>> remainingHandles;
3262 mFlinger->getTransactionCallbackInvoker()
3263 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3264 mDrawingState.callbackHandles = remainingHandles;
3265
3266 mDrawingStateModified = false;
3267}
3268
3269void Layer::gatherBufferInfo() {
3270 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3271 decrementPendingBufferCount();
3272 }
3273
3274 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3275 mBufferInfo.mBuffer = mDrawingState.buffer;
3276 mBufferInfo.mFence = mDrawingState.acquireFence;
3277 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3278 mBufferInfo.mPixelFormat =
3279 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3280 mBufferInfo.mFrameLatencyNeeded = true;
3281 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3282 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3283 mBufferInfo.mFence = mDrawingState.acquireFence;
3284 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3285 auto lastDataspace = mBufferInfo.mDataspace;
3286 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3287 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003288 mFlinger->mHdrLayerInfoChanged = true;
3289 }
3290 if (mBufferInfo.mDesiredSdrHdrRatio != mDrawingState.desiredSdrHdrRatio) {
3291 mBufferInfo.mDesiredSdrHdrRatio = mDrawingState.desiredSdrHdrRatio;
3292 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003293 }
3294 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3295 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3296 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3297 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3298 mBufferInfo.mApi = mDrawingState.api;
3299 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003300}
3301
3302Rect Layer::computeBufferCrop(const State& s) {
3303 if (s.buffer && !s.bufferCrop.isEmpty()) {
3304 Rect bufferCrop;
3305 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3306 return bufferCrop;
3307 } else if (s.buffer) {
3308 return s.buffer->getBounds();
3309 } else {
3310 return s.bufferCrop;
3311 }
3312}
3313
3314sp<Layer> Layer::createClone() {
3315 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3316 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003317 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003318 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3319 return layer;
3320}
3321
Patrick Williamsbb25f802022-08-30 23:02:34 +00003322void Layer::decrementPendingBufferCount() {
3323 int32_t pendingBuffers = --mPendingBufferTransactions;
3324 tracePendingBufferCount(pendingBuffers);
3325}
3326
3327void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3328 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3329}
3330
3331/*
3332 * We don't want to send the layer's transform to input, but rather the
3333 * parent's transform. This is because Layer's transform is
3334 * information about how the buffer is placed on screen. The parent's
3335 * transform makes more sense to send since it's information about how the
3336 * layer is placed on screen. This transform is used by input to determine
3337 * how to go from screen space back to window space.
3338 */
3339ui::Transform Layer::getInputTransform() const {
3340 if (!hasBufferOrSidebandStream()) {
3341 return getTransform();
3342 }
3343 sp<Layer> parent = mDrawingParent.promote();
3344 if (parent == nullptr) {
3345 return ui::Transform();
3346 }
3347
3348 return parent->getTransform();
3349}
3350
3351/**
3352 * Similar to getInputTransform, we need to update the bounds to include the transform.
3353 * This is because bounds don't include the buffer transform, where the input assumes
3354 * that's already included.
3355 */
3356Rect Layer::getInputBounds() const {
3357 if (!hasBufferOrSidebandStream()) {
3358 return getCroppedBufferSize(getDrawingState());
3359 }
3360
3361 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
3362 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
3363 return bufferBounds;
3364 }
3365 return mDrawingState.transform.transform(bufferBounds);
3366}
3367
3368bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3369 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3370
3371 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3372 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3373 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3374 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3375 layer_state_t::eReparent;
3376
3377 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3378 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3379 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3380 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3381 layer_state_t::eInputInfoChanged;
3382
3383 if ((s.what & requiredFlags) != requiredFlags) {
3384 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3385 (s.what | requiredFlags) & ~s.what);
3386 return false;
3387 }
3388
3389 if (s.what & deniedFlags) {
3390 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3391 return false;
3392 }
3393
3394 if (s.what & allowedFlags) {
3395 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3396 }
3397
3398 if (s.what & layer_state_t::ePositionChanged) {
3399 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3400 ALOGV("%s: false [ePositionChanged changed]", __func__);
3401 return false;
3402 }
3403 }
3404
3405 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003406 if (mDrawingState.color.a != s.color.a) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003407 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3408 return false;
3409 }
3410 }
3411
3412 if (s.what & layer_state_t::eColorTransformChanged) {
3413 if (mDrawingState.colorTransform != s.colorTransform) {
3414 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3415 return false;
3416 }
3417 }
3418
3419 if (s.what & layer_state_t::eBackgroundColorChanged) {
3420 if (mDrawingState.bgColorLayer || s.bgColorAlpha != 0) {
3421 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3422 return false;
3423 }
3424 }
3425
3426 if (s.what & layer_state_t::eMatrixChanged) {
3427 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3428 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3429 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3430 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3431 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3432 return false;
3433 }
3434 }
3435
3436 if (s.what & layer_state_t::eCornerRadiusChanged) {
3437 if (mDrawingState.cornerRadius != s.cornerRadius) {
3438 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3439 return false;
3440 }
3441 }
3442
3443 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3444 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3445 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3446 return false;
3447 }
3448 }
3449
Vishnu Nairbbceb462022-10-10 04:52:13 +00003450 if (s.what & layer_state_t::eBufferTransformChanged) {
3451 if (mDrawingState.bufferTransform != s.bufferTransform) {
3452 ALOGV("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003453 return false;
3454 }
3455 }
3456
3457 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3458 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3459 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3460 return false;
3461 }
3462 }
3463
3464 if (s.what & layer_state_t::eCropChanged) {
3465 if (mDrawingState.crop != s.crop) {
3466 ALOGV("%s: false [eCropChanged changed]", __func__);
3467 return false;
3468 }
3469 }
3470
3471 if (s.what & layer_state_t::eDataspaceChanged) {
3472 if (mDrawingState.dataspace != s.dataspace) {
3473 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3474 return false;
3475 }
3476 }
3477
3478 if (s.what & layer_state_t::eHdrMetadataChanged) {
3479 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3480 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3481 return false;
3482 }
3483 }
3484
3485 if (s.what & layer_state_t::eSidebandStreamChanged) {
3486 if (mDrawingState.sidebandStream != s.sidebandStream) {
3487 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3488 return false;
3489 }
3490 }
3491
3492 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3493 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3494 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3495 return false;
3496 }
3497 }
3498
3499 if (s.what & layer_state_t::eShadowRadiusChanged) {
3500 if (mDrawingState.shadowRadius != s.shadowRadius) {
3501 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3502 return false;
3503 }
3504 }
3505
3506 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3507 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3508 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3509 return false;
3510 }
3511 }
3512
3513 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3514 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3515 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3516 return false;
3517 }
3518 }
3519
3520 if (s.what & layer_state_t::eStretchChanged) {
3521 StretchEffect temp = s.stretchEffect;
3522 temp.sanitize();
3523 if (mDrawingState.stretchEffect != temp) {
3524 ALOGV("%s: false [eStretchChanged changed]", __func__);
3525 return false;
3526 }
3527 }
3528
3529 if (s.what & layer_state_t::eBufferCropChanged) {
3530 if (mDrawingState.bufferCrop != s.bufferCrop) {
3531 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3532 return false;
3533 }
3534 }
3535
3536 if (s.what & layer_state_t::eDestinationFrameChanged) {
3537 if (mDrawingState.destinationFrame != s.destinationFrame) {
3538 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3539 return false;
3540 }
3541 }
3542
3543 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3544 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3545 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3546 return false;
3547 }
3548 }
3549
John Reck68796592023-01-25 13:47:12 -05003550 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
3551 if (mDrawingState.currentSdrHdrRatio != s.currentSdrHdrRatio ||
3552 mDrawingState.desiredSdrHdrRatio != s.desiredSdrHdrRatio) {
3553 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3554 return false;
3555 }
3556 }
3557
Patrick Williamsbb25f802022-08-30 23:02:34 +00003558 ALOGV("%s: true", __func__);
3559 return true;
3560}
3561
3562bool Layer::isHdrY410() const {
3563 // pixel format is HDR Y410 masquerading as RGBA_1010102
3564 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3565 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3566 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3567}
3568
Vishnu Naire14c6b32022-08-06 04:20:15 +00003569sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003570 // 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 +00003571 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003572}
3573
Vishnu Naire14c6b32022-08-06 04:20:15 +00003574const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003575 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003576}
3577
Vishnu Naire14c6b32022-08-06 04:20:15 +00003578LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003579 return mSnapshot.get();
3580}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003581
Vishnu Naird6913222023-02-01 22:56:21 +00003582std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3583 return std::move(mSnapshot);
3584}
3585
3586void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3587 mSnapshot = std::move(snapshot);
3588}
3589
Patrick Williamsbb25f802022-08-30 23:02:34 +00003590const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003591 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003592}
3593
Patrick Williams7584c6a2022-10-29 02:10:58 +00003594sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Naird6913222023-02-01 22:56:21 +00003595 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003596 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3597 return result;
3598}
3599
Vishnu Naird6913222023-02-01 22:56:21 +00003600sp<LayerFE> Layer::getCompositionEngineLayerFE(
3601 const frontend::LayerHierarchy::TraversalPath& path) {
3602 for (auto& [p, layerFE] : mLayerFEs) {
3603 if (p == path) {
3604 return layerFE;
3605 }
3606 }
3607 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3608 mLayerFEs.emplace_back(path, layerFE);
3609 return layerFE;
3610}
3611
Patrick Williamsbb25f802022-08-30 23:02:34 +00003612void Layer::useSurfaceDamage() {
3613 if (mFlinger->mForceFullDamage) {
3614 surfaceDamageRegion = Region::INVALID_REGION;
3615 } else {
3616 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3617 }
3618}
3619
3620void Layer::useEmptyDamage() {
3621 surfaceDamageRegion.clear();
3622}
3623
3624bool Layer::isOpaque(const Layer::State& s) const {
3625 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3626 // layer's opaque flag.
3627 if (!hasSomethingToDraw()) {
3628 return false;
3629 }
3630
3631 // if the layer has the opaque flag, then we're always opaque
3632 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3633 return true;
3634 }
3635
3636 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003637 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003638 return true;
3639 }
3640
3641 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3642 return fillsColor() && getAlpha() == 1.0_hf;
3643}
3644
3645bool Layer::canReceiveInput() const {
3646 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3647}
3648
3649bool Layer::isVisible() const {
3650 if (!hasSomethingToDraw()) {
3651 return false;
3652 }
3653
3654 if (isHiddenByPolicy()) {
3655 return false;
3656 }
3657
3658 return getAlpha() > 0.0f || hasBlur();
3659}
3660
3661void Layer::onPostComposition(const DisplayDevice* display,
3662 const std::shared_ptr<FenceTime>& glDoneFence,
3663 const std::shared_ptr<FenceTime>& presentFence,
3664 const CompositorTiming& compositorTiming) {
3665 // mFrameLatencyNeeded is true when a new frame was latched for the
3666 // composition.
3667 if (!mBufferInfo.mFrameLatencyNeeded) return;
3668
3669 for (const auto& handle : mDrawingState.callbackHandles) {
3670 handle->gpuCompositionDoneFence = glDoneFence;
3671 handle->compositorTiming = compositorTiming;
3672 }
3673
3674 // Update mFrameTracker.
3675 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3676 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3677
3678 const int32_t layerId = getSequence();
3679 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3680
3681 const auto outputLayer = findOutputLayerForDisplay(display);
3682 if (outputLayer && outputLayer->requiresClientComposition()) {
3683 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3684 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3685 clientCompositionTimestamp,
3686 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3687 // Update the SurfaceFrames in the drawing state
3688 if (mDrawingState.bufferSurfaceFrameTX) {
3689 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3690 }
3691 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3692 surfaceFrame->setGpuComposition();
3693 }
3694 }
3695
3696 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3697 if (frameReadyFence->isValid()) {
3698 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3699 } else {
3700 // There was no fence for this frame, so assume that it was ready
3701 // to be presented at the desired present time.
3702 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3703 }
3704
3705 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08003706 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003707 const std::optional<Fps> renderRate =
3708 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3709
3710 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3711 const auto gameMode = getGameMode();
3712
3713 if (presentFence->isValid()) {
3714 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3715 refreshRate, renderRate, vote, gameMode);
3716 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3717 presentFence,
3718 FrameTracer::FrameEvent::PRESENT_FENCE);
3719 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3720 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3721 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003722 // The HWC doesn't support present fences, so use the present timestamp instead.
3723 const nsecs_t presentTimestamp =
3724 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3725
3726 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3727 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3728 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3729
Patrick Williamsbb25f802022-08-30 23:02:34 +00003730 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3731 refreshRate, renderRate, vote, gameMode);
3732 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3733 mCurrentFrameNumber, actualPresentTime,
3734 FrameTracer::FrameEvent::PRESENT_FENCE);
3735 mFrameTracker.setActualPresentTime(actualPresentTime);
3736 }
3737 }
3738
3739 mFrameTracker.advanceFrame();
3740 mBufferInfo.mFrameLatencyNeeded = false;
3741}
3742
3743bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
3744 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3745 getDrawingState().frameNumber);
3746
3747 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3748
3749 if (refreshRequired) {
3750 return refreshRequired;
3751 }
3752
3753 // If the head buffer's acquire fence hasn't signaled yet, return and
3754 // try again later
3755 if (!fenceHasSignaled()) {
3756 ATRACE_NAME("!fenceHasSignaled()");
3757 mFlinger->onLayerUpdate();
3758 return false;
3759 }
3760
3761 updateTexImage(latchTime);
3762 if (mDrawingState.buffer == nullptr) {
3763 return false;
3764 }
3765
3766 // Capture the old state of the layer for comparisons later
3767 BufferInfo oldBufferInfo = mBufferInfo;
3768 const bool oldOpacity = isOpaque(mDrawingState);
3769 mPreviousFrameNumber = mCurrentFrameNumber;
3770 mCurrentFrameNumber = mDrawingState.frameNumber;
3771 gatherBufferInfo();
3772
3773 if (oldBufferInfo.mBuffer == nullptr) {
3774 // the first time we receive a buffer, we need to trigger a
3775 // geometry invalidation.
3776 recomputeVisibleRegions = true;
3777 }
3778
3779 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3780 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3781 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3782 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3783 recomputeVisibleRegions = true;
3784 }
3785
3786 if (oldBufferInfo.mBuffer != nullptr) {
3787 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3788 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3789 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3790 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3791 recomputeVisibleRegions = true;
3792 }
3793 }
3794
3795 if (oldOpacity != isOpaque(mDrawingState)) {
3796 recomputeVisibleRegions = true;
3797 }
3798
3799 return true;
3800}
3801
3802bool Layer::hasReadyFrame() const {
3803 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
3804}
3805
3806bool Layer::isProtected() const {
3807 return (mBufferInfo.mBuffer != nullptr) &&
3808 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
3809}
3810
Patrick Williamsbb25f802022-08-30 23:02:34 +00003811void Layer::latchAndReleaseBuffer() {
3812 if (hasReadyFrame()) {
3813 bool ignored = false;
3814 latchBuffer(ignored, systemTime());
3815 }
3816 releasePendingBuffer(systemTime());
3817}
3818
3819PixelFormat Layer::getPixelFormat() const {
3820 return mBufferInfo.mPixelFormat;
3821}
3822
3823bool Layer::getTransformToDisplayInverse() const {
3824 return mBufferInfo.mTransformToDisplayInverse;
3825}
3826
3827Rect Layer::getBufferCrop() const {
3828 // this is the crop rectangle that applies to the buffer
3829 // itself (as opposed to the window)
3830 if (!mBufferInfo.mCrop.isEmpty()) {
3831 // if the buffer crop is defined, we use that
3832 return mBufferInfo.mCrop;
3833 } else if (mBufferInfo.mBuffer != nullptr) {
3834 // otherwise we use the whole buffer
3835 return mBufferInfo.mBuffer->getBounds();
3836 } else {
3837 // if we don't have a buffer yet, we use an empty/invalid crop
3838 return Rect();
3839 }
3840}
3841
3842uint32_t Layer::getBufferTransform() const {
3843 return mBufferInfo.mTransform;
3844}
3845
3846ui::Dataspace Layer::getDataSpace() const {
3847 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
3848}
3849
3850ui::Dataspace Layer::getRequestedDataSpace() const {
3851 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
3852}
3853
3854ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
3855 ui::Dataspace updatedDataspace = dataspace;
3856 // translate legacy dataspaces to modern dataspaces
3857 switch (dataspace) {
3858 case ui::Dataspace::SRGB:
3859 updatedDataspace = ui::Dataspace::V0_SRGB;
3860 break;
3861 case ui::Dataspace::SRGB_LINEAR:
3862 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
3863 break;
3864 case ui::Dataspace::JFIF:
3865 updatedDataspace = ui::Dataspace::V0_JFIF;
3866 break;
3867 case ui::Dataspace::BT601_625:
3868 updatedDataspace = ui::Dataspace::V0_BT601_625;
3869 break;
3870 case ui::Dataspace::BT601_525:
3871 updatedDataspace = ui::Dataspace::V0_BT601_525;
3872 break;
3873 case ui::Dataspace::BT709:
3874 updatedDataspace = ui::Dataspace::V0_BT709;
3875 break;
3876 default:
3877 break;
3878 }
3879
3880 return updatedDataspace;
3881}
3882
3883sp<GraphicBuffer> Layer::getBuffer() const {
3884 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
3885}
3886
Patrick Williamsbb25f802022-08-30 23:02:34 +00003887void Layer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
3888 mTransformHint = getFixedTransformHint();
3889 if (mTransformHint == ui::Transform::ROT_INVALID) {
3890 mTransformHint = displayTransformHint;
3891 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07003892 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003893}
3894
3895const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
3896 return mBufferInfo.mBuffer;
3897}
3898
3899bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003900 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003901 return false;
3902 }
3903
3904 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00003905 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003906 mDrawingState.modified = true;
3907 setTransactionFlags(eTransactionNeeded);
3908 return true;
3909}
3910
3911bool Layer::fillsColor() const {
3912 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
3913 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
3914}
3915
3916bool Layer::hasBlur() const {
3917 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
3918}
3919
Vishnu Nairba354102022-08-01 00:14:18 +00003920void Layer::updateSnapshot(bool updateGeometry) {
3921 if (!getCompositionEngineLayerFE()) {
3922 return;
3923 }
3924
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003925 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00003926 if (updateGeometry) {
3927 prepareBasicGeometryCompositionState();
3928 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003929 snapshot->roundedCorner = getRoundedCornerState();
3930 snapshot->stretchEffect = getStretchEffect();
3931 snapshot->transformedBounds = mScreenBounds;
3932 if (mEffectiveShadowRadius > 0.f) {
3933 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
3934
3935 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
3936 // it if transparent regions are present. This may not be necessary since shadows are
3937 // typically cast by layers without transparent regions.
3938 snapshot->shadowSettings.boundaries = mBounds;
3939
3940 const float casterAlpha = snapshot->alpha;
3941 const bool casterIsOpaque =
3942 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
3943
3944 // If the casting layer is translucent, we need to fill in the shadow underneath the
3945 // layer. Otherwise the generated shadow will only be shown around the casting layer.
3946 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
3947 snapshot->shadowSettings.ambientColor *= casterAlpha;
3948 snapshot->shadowSettings.spotColor *= casterAlpha;
3949 }
3950 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00003951 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003952 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003953 snapshot->layerOpaqueFlagSet =
3954 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003955 snapshot->isHdrY410 = isHdrY410();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003956 sp<Layer> p = mDrawingParent.promote();
3957 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003958 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003959 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003960 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003961 }
3962 snapshot->bufferSize = getBufferSize(mDrawingState);
3963 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00003964 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00003965 preparePerFrameCompositionState();
3966}
3967
Vishnu Naire14c6b32022-08-06 04:20:15 +00003968void Layer::updateChildrenSnapshots(bool updateGeometry) {
3969 for (const sp<Layer>& child : mDrawingChildren) {
3970 child->updateSnapshot(updateGeometry);
3971 child->updateChildrenSnapshots(updateGeometry);
3972 }
3973}
3974
Vishnu Nair0a4fb002022-08-08 02:40:42 +00003975void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
3976 mSnapshot->layerMetadata = parentMetadata;
3977 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
3978 for (const sp<Layer>& child : mDrawingChildren) {
3979 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
3980 }
3981}
3982
3983void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
3984 std::unordered_set<Layer*>& visited) {
3985 if (visited.find(this) != visited.end()) {
3986 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
3987 return;
3988 }
3989 visited.insert(this);
3990
3991 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
3992
3993 if (mDrawingState.zOrderRelatives.empty()) {
3994 return;
3995 }
3996 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
3997 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
3998 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
3999 sp<Layer> relative = weakRelative.promote();
4000 if (!relative) {
4001 continue;
4002 }
4003 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4004 }
4005}
4006
Chavi Weingarten076acac2023-01-19 17:20:43 +00004007void Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
4008 TrustedPresentationListener const& listener) {
4009 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4010 mTrustedPresentationListener = listener;
4011 mTrustedPresentationThresholds = thresholds;
4012 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4013 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4014 mFlinger->mNumTrustedPresentationListeners++;
4015 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4016 mFlinger->mNumTrustedPresentationListeners--;
4017 }
4018}
4019
Mathias Agopian13127d82013-03-05 17:47:11 -08004020// ---------------------------------------------------------------------------
4021
Marin Shalamanov46084422020-10-13 12:33:42 +02004022std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004023 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4024 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004025}
4026
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004027} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004028
4029#if defined(__gl_h_)
4030#error "don't include gl/gl.h in this file"
4031#endif
4032
4033#if defined(__gl2_h_)
4034#error "don't include gl2/gl2.h in this file"
4035#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004036
4037// TODO(b/129481165): remove the #pragma below and fix conversion issues
4038#pragma clang diagnostic pop // ignored "-Wconversion"