blob: 6197e9bb472e01db8a762f9777deff208e8c0a24 [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;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800131using gui::GameMode;
132using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500133using gui::WindowInfo;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800134
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700135using PresentState = frametimeline::SurfaceFrame::PresentState;
136
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700137Layer::Layer(const LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000138 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700139 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000140 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700141 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800142 mWindowType(static_cast<WindowInfo::Type>(
143 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000144 mLayerCreationFlags(args.flags),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000145 mBorderEnabled(false),
146 mTextureName(args.textureName),
Vishnu Naire14c6b32022-08-06 04:20:15 +0000147 mLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000148 ALOGV("Creating Layer %s", getDebugName());
149
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700150 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700151 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
152 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
153 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700154 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
155 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700156 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700157 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700158 mDrawingState.z = 0;
159 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700160 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700161 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700162 mDrawingState.transform.set(0, 0);
163 mDrawingState.frameNumber = 0;
164 mDrawingState.bufferTransform = 0;
165 mDrawingState.transformToDisplayInverse = false;
166 mDrawingState.crop.makeInvalid();
167 mDrawingState.acquireFence = sp<Fence>::make(-1);
168 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
169 mDrawingState.dataspace = ui::Dataspace::UNKNOWN;
Vishnu Nairbc4ee5c2022-08-16 03:19:37 +0000170 mDrawingState.dataspaceRequested = false;
Robert Carr6a160312021-05-17 12:08:20 -0700171 mDrawingState.hdrMetadata.validTypes = 0;
172 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
173 mDrawingState.cornerRadius = 0.0f;
174 mDrawingState.backgroundBlurRadius = 0;
175 mDrawingState.api = -1;
176 mDrawingState.hasColorTransform = false;
177 mDrawingState.colorSpaceAgnostic = false;
178 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
179 mDrawingState.metadata = args.metadata;
180 mDrawingState.shadowRadius = 0.f;
181 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
182 mDrawingState.frameTimelineInfo = {};
183 mDrawingState.postTime = -1;
184 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000185 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700186 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700187 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000188 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700189
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700190 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
191 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700192 mDrawingState.color.r = -1.0_hf;
193 mDrawingState.color.g = -1.0_hf;
194 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700195 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700196
Dominik Laskowski596a2562022-10-28 11:26:12 -0400197 mFrameTracker.setDisplayRefreshPeriod(args.flinger->mScheduler->getLeaderVsyncPeriod());
Robert Carr2e102c92018-10-23 12:11:15 -0700198
Vishnu Naircb8be502022-10-12 19:03:23 +0000199 mOwnerUid = args.ownerUid;
200 mOwnerPid = args.ownerPid;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000201
202 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
203 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
204 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
205 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000206
207 mSnapshot->sequence = sequence;
208 mSnapshot->name = getDebugName();
209 mSnapshot->textureName = mTextureName;
210 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
211 mSnapshot->transform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800212}
213
214void Layer::onFirstRef() {
215 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700216}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700217
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700218Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000219 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
220 "Layer destructor called off the main thread.");
221
Patrick Williamsbb25f802022-08-30 23:02:34 +0000222 // The original layer and the clone layer share the same texture and buffer. Therefore, only
223 // one of the layers, in this case the original layer, needs to handle the deletion. The
224 // original layer and the clone should be removed at the same time so there shouldn't be any
225 // issue with the clone layer trying to use the texture.
226 if (mBufferInfo.mBuffer != nullptr) {
227 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
228 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
229 mBufferInfo.mFence,
230 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
231 mOwnerUid));
232 }
233 if (!isClone()) {
234 // The original layer and the clone layer share the same texture. Therefore, only one of
235 // the layers, in this case the original layer, needs to handle the deletion. The original
236 // layer and the clone should be removed at the same time so there shouldn't be any issue
237 // with the clone layer trying to use the deleted texture.
238 mFlinger->deleteTextureAsync(mTextureName);
239 }
240 const int32_t layerId = getSequence();
241 mFlinger->mTimeStats->onDestroy(layerId);
242 mFlinger->mFrameTracer->onDestroy(layerId);
243
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000244 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700245 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700246
247 if (mDrawingState.sidebandStream != nullptr) {
248 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
249 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700250 if (mHadClonedChild) {
251 mFlinger->mNumClones--;
252 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000253 if (hasTrustedPresentationListener()) {
254 mFlinger->mNumTrustedPresentationListeners--;
255 updateTrustedPresentationState(nullptr, -1 /* time_in_ms */, true /* leaveState*/);
256 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700257}
258
Mathias Agopian13127d82013-03-05 17:47:11 -0800259// ---------------------------------------------------------------------------
260// callbacks
261// ---------------------------------------------------------------------------
262
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700263void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700264 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700265 return;
266 }
Robert Carr2e102c92018-10-23 12:11:15 -0700267
Robert Carr6a160312021-05-17 12:08:20 -0700268 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700269 if (strongRelative == nullptr) {
270 setZOrderRelativeOf(nullptr);
271 return;
272 }
273
274 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700275 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700276 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800277 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700278 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700279}
280
281void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700282 if (!mRemovedFromDrawingState) {
283 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700284 mFlinger->mScheduler->deregisterLayer(this);
285 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000286 updateTrustedPresentationState(nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000287
Ady Abrahamd11bade2022-08-01 16:18:03 -0700288 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700289}
Chia-I Wu38512252017-05-17 14:36:16 -0700290
chaviw68d4dab2020-06-08 15:07:32 -0700291sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000292 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700293 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700294 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700295 }
296 return parent->getRootLayer();
297}
298
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700299void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700300 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
301 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700302 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700303
304 traverse(LayerVector::StateSet::Current, [&](Layer* layer) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700305 layer->removeFromCurrentState();
306 layer->removeRelativeZ(layersInTree);
chaviw68d4dab2020-06-08 15:07:32 -0700307 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700308}
309
chaviw61626f22018-11-15 16:26:27 -0800310void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700311 if (mRemovedFromDrawingState) {
312 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700313 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700314 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700315 }
chaviw61626f22018-11-15 16:26:27 -0800316
317 for (const auto& child : mCurrentChildren) {
318 child->addToCurrentState();
319 }
320}
321
Mathias Agopian13127d82013-03-05 17:47:11 -0800322// ---------------------------------------------------------------------------
323// set-up
324// ---------------------------------------------------------------------------
325
chaviw13fdc492017-06-27 12:40:18 -0700326bool Layer::getPremultipledAlpha() const {
327 return mPremultipliedAlpha;
328}
329
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700330sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800331 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700332 if (mGetHandleCalled) {
333 ALOGE("Get handle called twice" );
334 return nullptr;
335 }
336 mGetHandleCalled = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000337 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800338}
339
340// ---------------------------------------------------------------------------
341// h/w composer set-up
342// ---------------------------------------------------------------------------
343
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700344static Rect reduce(const Rect& win, const Region& exclude) {
345 if (CC_LIKELY(exclude.isEmpty())) {
346 return win;
347 }
348 if (exclude.isRect()) {
349 return win.reduce(exclude.getBounds());
350 }
351 return Region(win).subtract(exclude).getBounds();
352}
353
Dan Stoza80d61162017-12-20 15:57:52 -0800354static FloatRect reduce(const FloatRect& win, const Region& exclude) {
355 if (CC_LIKELY(exclude.isEmpty())) {
356 return win;
357 }
358 // Convert through Rect (by rounding) for lack of FloatRegion
359 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
360}
361
Vishnu Nair4351ad52019-02-11 14:13:02 -0800362Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800363 if (!reduceTransparentRegion) {
364 return Rect{mScreenBounds};
365 }
366
367 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800368 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800369 // Transform to screen space.
370 bounds = t.transform(bounds);
371 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700372}
373
Vishnu Nair4351ad52019-02-11 14:13:02 -0800374FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000375 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800376 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700377}
378
Vishnu Nairf0c28512019-02-08 12:40:28 -0800379FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
380 // Subtract the transparent region and snap to the bounds.
381 return reduce(mBounds, activeTransparentRegion);
382}
383
Chavi Weingarten076acac2023-01-19 17:20:43 +0000384// No early returns.
385void Layer::updateTrustedPresentationState(const DisplayDevice* display, int64_t time_in_ms,
386 bool leaveState) {
387 if (!hasTrustedPresentationListener()) {
388 return;
389 }
390 const bool lastState = mLastComputedTrustedPresentationState;
391 mLastComputedTrustedPresentationState = false;
392
393 if (!leaveState) {
394 const auto outputLayer = findOutputLayerForDisplay(display);
395 if (outputLayer != nullptr) {
396 mLastComputedTrustedPresentationState =
397 computeTrustedPresentationState(mBounds, mSourceBounds,
398 outputLayer->getState().coveredRegion,
399 mScreenBounds, getCompositionState()->alpha,
400 getCompositionState()->geomLayerTransform,
401 mTrustedPresentationThresholds);
402 }
403 }
404 const bool newState = mLastComputedTrustedPresentationState;
405 if (lastState && !newState) {
406 // We were in the trusted presentation state, but now we left it,
407 // emit the callback if needed
408 if (mLastReportedTrustedPresentationState) {
409 mLastReportedTrustedPresentationState = false;
410 mTrustedPresentationListener.invoke(false);
411 }
412 // Reset the timer
413 mEnteredTrustedPresentationStateTime = -1;
414 } else if (!lastState && newState) {
415 // We were not in the trusted presentation state, but we entered it, begin the timer
416 // and make sure this gets called at least once more!
417 mEnteredTrustedPresentationStateTime = time_in_ms;
418 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
419 }
420
421 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
422 if (!mLastReportedTrustedPresentationState && newState &&
423 (time_in_ms - mEnteredTrustedPresentationStateTime >
424 mTrustedPresentationThresholds.stabilityRequirementMs)) {
425 mLastReportedTrustedPresentationState = true;
426 mTrustedPresentationListener.invoke(true);
427 }
428}
429
430/**
431 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
432 * of how the parameters and thresholds are interpreted. The general spirit is
433 * to produce an upper bound on the amount of the buffer which was presented.
434 */
435bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
436 const Region& coveredRegion,
437 const FloatRect& screenBounds, float alpha,
438 const ui::Transform& effectiveTransform,
439 const TrustedPresentationThresholds& thresholds) {
440 if (alpha < thresholds.minAlpha) {
441 return false;
442 }
443 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
444 return false;
445 }
446 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
447 return false;
448 }
449
450 const float sx = effectiveTransform.dsdx();
451 const float sy = effectiveTransform.dsdy();
452 float fractionRendered = std::min(sx * sy, 1.0f);
453
454 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
455 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
456 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
457
458 Rect coveredBounds = coveredRegion.bounds();
459 fractionRendered *= (1 -
460 ((coveredBounds.width() / (float)screenBounds.getWidth()) *
461 coveredBounds.height() / (float)screenBounds.getHeight()));
462
463 if (fractionRendered < thresholds.minFractionRendered) {
464 return false;
465 }
466
467 return true;
468}
469
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700470void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
471 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800472 const State& s(getDrawingState());
473
474 // Calculate effective layer transform
475 mEffectiveTransform = parentTransform * getActiveTransform(s);
476
Garfield Tan2c1782c2022-02-16 15:25:05 -0800477 if (CC_UNLIKELY(!isTransformValid())) {
478 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
479 getDebugName());
480 return;
481 }
482
Vishnu Nair4351ad52019-02-11 14:13:02 -0800483 // Transform parent bounds to layer space
484 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
485
Vishnu Nairc652ff82019-03-15 12:48:54 -0700486 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800487 mSourceBounds = computeSourceBounds(parentBounds);
488
489 // Calculate bounds by croping diplay frame with layer crop and parent bounds
490 FloatRect bounds = mSourceBounds;
491 const Rect layerCrop = getCrop(s);
492 if (!layerCrop.isEmpty()) {
493 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
494 }
495 bounds = bounds.intersect(parentBounds);
496
497 mBounds = bounds;
498 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700499
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700500 // Use the layer's own shadow radius if set. Otherwise get the radius from
501 // parent.
502 if (s.shadowRadius > 0.f) {
503 mEffectiveShadowRadius = s.shadowRadius;
504 } else {
505 mEffectiveShadowRadius = parentShadowRadius;
506 }
507
508 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
509 // don't pass it to its children.
510 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
511
Vishnu Nair4351ad52019-02-11 14:13:02 -0800512 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700513 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800514 }
Vishnu Nairba354102022-08-01 00:14:18 +0000515
516 if (mPotentialCursor) {
517 prepareCursorCompositionState();
518 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800519}
520
Vishnu Nair60356342018-11-13 13:00:45 -0800521Rect Layer::getCroppedBufferSize(const State& s) const {
522 Rect size = getBufferSize(s);
523 Rect crop = getCrop(s);
524 if (!crop.isEmpty() && size.isValid()) {
525 size.intersect(crop, &size);
526 } else if (!crop.isEmpty()) {
527 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700528 }
Vishnu Nair60356342018-11-13 13:00:45 -0800529 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800530}
531
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700532void Layer::setupRoundedCornersCropCoordinates(Rect win,
533 const FloatRect& roundedCornersCrop) const {
534 // Translate win by the rounded corners rect coordinates, to have all values in
535 // layer coordinate space.
536 win.left -= roundedCornersCrop.left;
537 win.right -= roundedCornersCrop.left;
538 win.top -= roundedCornersCrop.top;
539 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700540}
541
Lloyd Piquede196652020-01-22 17:29:58 -0800542void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800543 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800544 const auto alpha = static_cast<float>(getAlpha());
545 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700546 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800547
548 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
549 if (!opaque || alpha != 1.0f) {
550 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
551 : Hwc2::IComposerClient::BlendMode::COVERAGE;
552 }
553
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000554 auto* snapshot = editLayerSnapshot();
555 snapshot->outputFilter = getOutputFilter();
556 snapshot->isVisible = isVisible();
557 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
558 snapshot->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800559
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000560 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800561 contentDirty = false;
562
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000563 snapshot->geomLayerBounds = mBounds;
564 snapshot->geomLayerTransform = getTransform();
565 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
566 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naire7613db2022-11-04 00:07:06 -0700567 snapshot->blurRegionTransform = getActiveTransform(drawingState).inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000568 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
569 snapshot->alpha = alpha;
570 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
571 snapshot->blurRegions = drawingState.blurRegions;
572 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800573}
574
Lloyd Piquede196652020-01-22 17:29:58 -0800575void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800576 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000577 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700578
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000579 snapshot->geomBufferSize = getBufferSize(drawingState);
580 snapshot->geomContentCrop = getBufferCrop();
581 snapshot->geomCrop = getCrop(drawingState);
582 snapshot->geomBufferTransform = getBufferTransform();
583 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
584 snapshot->geomUsesSourceCrop = usesSourceCrop();
585 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800586
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000587 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800588 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
589 for (const auto& [key, mandatory] : supportedMetadata) {
590 const auto& genericLayerMetadataCompatibilityMap =
591 mFlinger->getGenericLayerMetadataKeyMap();
592 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
593 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
594 continue;
595 }
596 const uint32_t id = compatIter->second;
597
598 auto it = drawingState.metadata.mMap.find(id);
599 if (it == std::end(drawingState.metadata.mMap)) {
600 continue;
601 }
602
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000603 snapshot->metadata.emplace(key,
604 compositionengine::GenericLayerMetadataEntry{mandatory,
605 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800606 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800607}
David Sodmanba340492018-08-05 21:51:33 -0700608
Lloyd Piquede196652020-01-22 17:29:58 -0800609void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800610 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000611 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800612
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000613 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800614
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000615 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
616 snapshot->dataspace = getDataSpace();
617 snapshot->colorTransform = getColorTransform();
618 snapshot->colorTransformIsIdentity = !hasColorTransform();
619 snapshot->surfaceDamage = surfaceDamageRegion;
620 snapshot->hasProtectedContent = isProtected();
621 snapshot->dimmingEnabled = isDimmingEnabled();
Lloyd Pique688abd42019-02-15 15:42:24 -0800622
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700623 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700624
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000625 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800626
627 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400628 // Rounded corners no longer force client composition, since we may use a
629 // hole punch so that the layer will appear to have rounded corners.
630 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000631 snapshot->stretchEffect.hasEffect()) {
632 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800633 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700634 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000635 snapshot->blurRegions = drawingState.blurRegions;
636 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400637
638 // Layer framerate is used in caching decisions.
639 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
640 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000641 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000642
643 if (hasBufferOrSidebandStream()) {
644 preparePerFrameBufferCompositionState();
645 } else {
646 preparePerFrameEffectsCompositionState();
647 }
648}
649
650void Layer::preparePerFrameBufferCompositionState() {
651 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000652 auto* snapshot = editLayerSnapshot();
653 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
654 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000655 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
656 return;
657 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000658 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000659 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
660 } else {
661 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000662 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
663 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000664 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
665 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
666 }
667
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000668 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000669 snapshot->acquireFence = mBufferInfo.mFence;
670 snapshot->frameNumber = mBufferInfo.mFrameNumber;
671 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000672}
673
674void Layer::preparePerFrameEffectsCompositionState() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000675 auto* snapshot = editLayerSnapshot();
676 snapshot->color = getColor();
677 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000678 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800679}
680
Lloyd Piquede196652020-01-22 17:29:58 -0800681void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800682 const State& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000683 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800684
685 // Apply the layer's transform, followed by the display's global transform
686 // Here we're guaranteed that the layer's transform preserves rects
687 Rect win = getCroppedBufferSize(drawingState);
688 // Subtract the transparent region and snap to the bounds
689 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
690 Rect frame(getTransform().transform(bounds));
691
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000692 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800693}
694
Lloyd Piquea83776c2019-01-29 18:42:32 -0800695const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700696 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800697}
698
Mathias Agopian13127d82013-03-05 17:47:11 -0800699// ---------------------------------------------------------------------------
700// drawing...
701// ---------------------------------------------------------------------------
702
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500703aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
704 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700705 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800706 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500707 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800708 }
709 if (outputLayer->getState().hwc) {
710 return (*outputLayer->getState().hwc).hwcCompositionType;
711 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500712 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800713 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800714}
715
Mathias Agopian13127d82013-03-05 17:47:11 -0800716// ----------------------------------------------------------------------------
717// local state
718// ----------------------------------------------------------------------------
719
David Sodman41fdfc92017-11-06 16:09:56 -0800720bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800721 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700722 if (s.flags & layer_state_t::eLayerSecure) {
723 return true;
724 }
725
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000726 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700727 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700728}
729
Mathias Agopian13127d82013-03-05 17:47:11 -0800730// ----------------------------------------------------------------------------
731// transaction
732// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800733
Marissa Wall61c58622018-07-18 10:12:20 -0700734uint32_t Layer::doTransaction(uint32_t flags) {
735 ATRACE_CALL();
736
Robert Carr0758e5d2021-03-11 22:15:04 -0800737 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700738 mDrawingStateModified = mDrawingState.modified;
739 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700740
Alec Mourib416efd2018-09-06 21:01:59 +0000741 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700742
Robert Carr6a160312021-05-17 12:08:20 -0700743 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800744 // invalidate and recompute the visible regions if needed
745 flags |= Layer::eVisibleRegion;
746 }
747
Robert Carr6a160312021-05-17 12:08:20 -0700748 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800749 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000750 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800751 flags |= eVisibleRegion;
752 this->contentDirty = true;
753
754 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700755 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800756 }
757
Arthur Hung9ed43392022-05-27 06:31:57 +0000758 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
759 mFlinger->mUpdateInputInfo = true;
760 }
761
Robert Carr6a160312021-05-17 12:08:20 -0700762 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800763
Mathias Agopian13127d82013-03-05 17:47:11 -0800764 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800765}
766
Robert Carr6a160312021-05-17 12:08:20 -0700767void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000768 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
769 // bufferSurfaceFrameTX will be presented in latchBuffer.
770 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
771 if (surfaceFrame->getPresentState() != PresentState::Presented) {
772 // With applyPendingStates, we could end up having presented surfaceframes from previous
773 // states
774 surfaceFrame->setPresentState(PresentState::Presented);
775 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
776 }
777 }
Robert Carr6a160312021-05-17 12:08:20 -0700778 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700779}
780
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700781uint32_t Layer::clearTransactionFlags(uint32_t mask) {
782 const auto flags = mTransactionFlags & mask;
783 mTransactionFlags &= ~mask;
784 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800785}
786
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700787void Layer::setTransactionFlags(uint32_t mask) {
788 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800789}
790
Robert Carr1f0a16a2016-10-24 16:27:39 -0700791bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
792 ssize_t idx = mCurrentChildren.indexOf(childLayer);
793 if (idx < 0) {
794 return false;
795 }
796 if (childLayer->setLayer(z)) {
797 mCurrentChildren.removeAt(idx);
798 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800799 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700800 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800801 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700802}
803
Robert Carr503c7042017-09-27 15:06:08 -0700804bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
805 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
806 ssize_t idx = mCurrentChildren.indexOf(childLayer);
807 if (idx < 0) {
808 return false;
809 }
810 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
811 mCurrentChildren.removeAt(idx);
812 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800813 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700814 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800815 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700816}
817
Robert Carrae060832016-11-28 10:51:00 -0800818bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700819 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
820 mDrawingState.sequence++;
821 mDrawingState.z = z;
822 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700823
Robert Carra70e91c2021-06-11 13:59:52 -0700824 mFlinger->mSomeChildrenChanged = true;
825
Robert Carrdb66e622017-04-10 16:55:57 -0700826 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700827 if (mDrawingState.zOrderRelativeOf != nullptr) {
828 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700829 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700830 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700831 }
chaviw606e5cf2019-03-01 10:12:10 -0800832 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700833 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800834 setTransactionFlags(eTransactionNeeded);
835 return true;
836}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700837
Robert Carrdb66e622017-04-10 16:55:57 -0700838void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700839 mDrawingState.zOrderRelatives.remove(relative);
840 mDrawingState.sequence++;
841 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700842 setTransactionFlags(eTransactionNeeded);
843}
844
845void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700846 mDrawingState.zOrderRelatives.add(relative);
847 mDrawingState.modified = true;
848 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700849 setTransactionFlags(eTransactionNeeded);
850}
851
chaviw606e5cf2019-03-01 10:12:10 -0800852void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700853 mDrawingState.zOrderRelativeOf = relativeOf;
854 mDrawingState.sequence++;
855 mDrawingState.modified = true;
856 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700857
chaviw606e5cf2019-03-01 10:12:10 -0800858 setTransactionFlags(eTransactionNeeded);
859}
860
Robert Carr503d2bd2017-12-04 15:49:47 -0800861bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000862 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700863 if (relative == nullptr) {
864 return false;
865 }
866
Robert Carr6a160312021-05-17 12:08:20 -0700867 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
868 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800869 return false;
870 }
871
Robert Carr88b85e12022-03-21 15:47:35 -0700872 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
873 (relative->mDrawingState.zOrderRelativeOf == this)) {
874 ALOGE("Detected relative layer loop between %s and %s",
875 mName.c_str(), relative->mName.c_str());
876 ALOGE("Ignoring new call to set relative layer");
877 return false;
878 }
879
Robert Carra70e91c2021-06-11 13:59:52 -0700880 mFlinger->mSomeChildrenChanged = true;
881
Robert Carr6a160312021-05-17 12:08:20 -0700882 mDrawingState.sequence++;
883 mDrawingState.modified = true;
884 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700885
Robert Carr6a160312021-05-17 12:08:20 -0700886 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700887 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700888 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700889 }
chaviw606e5cf2019-03-01 10:12:10 -0800890 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700891 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700892
893 setTransactionFlags(eTransactionNeeded);
894
895 return true;
896}
897
Winson Chunga30f7c92021-06-29 15:42:56 -0700898bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
899 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
900 mDrawingState.isTrustedOverlay = isTrustedOverlay;
901 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000902 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700903 setTransactionFlags(eTransactionNeeded);
904 return true;
905}
906
907bool Layer::isTrustedOverlay() const {
908 if (getDrawingState().isTrustedOverlay) {
909 return true;
910 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000911 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700912 return (p != nullptr) && p->isTrustedOverlay();
913}
914
Dan Stoza9e56aa02015-11-02 13:00:03 -0800915bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700916 if (mDrawingState.color.a == alpha) return false;
917 mDrawingState.sequence++;
918 mDrawingState.color.a = alpha;
919 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800920 setTransactionFlags(eTransactionNeeded);
921 return true;
922}
chaviw13fdc492017-06-27 12:40:18 -0700923
Valerie Haudd0b7572019-01-29 14:59:27 -0800924bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700925 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700926 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800927 }
Robert Carr6a160312021-05-17 12:08:20 -0700928 mDrawingState.sequence++;
929 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800930 setTransactionFlags(eTransactionNeeded);
931
Robert Carr6a160312021-05-17 12:08:20 -0700932 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -0800933 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -0800934 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700935 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -0700936 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800937 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700938 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -0700939
Valerie Haudd0b7572019-01-29 14:59:27 -0800940 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -0700941 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -0800942 mFlinger->mLayersAdded = true;
943 // set up SF to handle added color layer
944 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -0700945 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -0800946 }
947 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -0700948 } else if (mDrawingState.bgColorLayer && alpha == 0) {
949 mDrawingState.bgColorLayer->reparent(nullptr);
950 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -0800951 return true;
952 }
953
Robert Carr6a160312021-05-17 12:08:20 -0700954 mDrawingState.bgColorLayer->setColor(color);
955 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
956 mDrawingState.bgColorLayer->setAlpha(alpha);
957 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -0800958
chaviw13fdc492017-06-27 12:40:18 -0700959 return true;
960}
961
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700962bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -0700963 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700964
Robert Carr6a160312021-05-17 12:08:20 -0700965 mDrawingState.sequence++;
966 mDrawingState.cornerRadius = cornerRadius;
967 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700968 setTransactionFlags(eTransactionNeeded);
969 return true;
970}
971
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800972bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -0700973 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -0700974 // If we start or stop drawing blur then the layer's visibility state may change so increment
975 // the magic sequence number.
976 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
977 mDrawingState.sequence++;
978 }
Robert Carr6a160312021-05-17 12:08:20 -0700979 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
980 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800981 setTransactionFlags(eTransactionNeeded);
982 return true;
983}
Marissa Wall61c58622018-07-18 10:12:20 -0700984
Mathias Agopian13127d82013-03-05 17:47:11 -0800985bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +0000986 mDrawingState.sequence++;
987 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -0700988 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800989 setTransactionFlags(eTransactionNeeded);
990 return true;
991}
Ana Krulecc84d09b2019-11-02 23:10:29 +0100992
Lucas Dupinc3800b82020-10-02 16:24:48 -0700993bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -0700994 // If we start or stop drawing blur then the layer's visibility state may change so increment
995 // the magic sequence number.
996 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
997 mDrawingState.sequence++;
998 }
Robert Carr6a160312021-05-17 12:08:20 -0700999 mDrawingState.blurRegions = blurRegions;
1000 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001001 setTransactionFlags(eTransactionNeeded);
1002 return true;
1003}
1004
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001005bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001006 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1007 if (mDrawingState.flags == newFlags) return false;
1008 mDrawingState.sequence++;
1009 mDrawingState.flags = newFlags;
1010 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001011 setTransactionFlags(eTransactionNeeded);
1012 return true;
1013}
Robert Carr99e27f02016-06-16 15:18:02 -07001014
chaviw25714502021-02-11 10:01:08 -08001015bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001016 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001017 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001018 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001019
Robert Carr6a160312021-05-17 12:08:20 -07001020 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001021 setTransactionFlags(eTransactionNeeded);
1022 return true;
1023}
Robert Carr8d5227b2017-03-16 15:41:03 -07001024
Evan Roskyef876c92019-01-25 17:46:06 -08001025bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001026 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1027 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001028 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001029 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001030}
1031
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001032bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001033 if (mDrawingState.layerStack == layerStack) return false;
1034 mDrawingState.sequence++;
1035 mDrawingState.layerStack = layerStack;
1036 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001037 setTransactionFlags(eTransactionNeeded);
1038 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001039}
1040
Peiyong Linc502cb72019-03-01 15:00:23 -08001041bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001042 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001043 return false;
1044 }
Robert Carr6a160312021-05-17 12:08:20 -07001045 mDrawingState.sequence++;
1046 mDrawingState.colorSpaceAgnostic = agnostic;
1047 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001048 setTransactionFlags(eTransactionNeeded);
1049 return true;
1050}
1051
Sally Qi81d95e62022-03-21 19:41:33 -07001052bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1053 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1054
1055 mDrawingState.sequence++;
1056 mDrawingState.dimmingEnabled = dimmingEnabled;
1057 mDrawingState.modified = true;
1058 setTransactionFlags(eTransactionNeeded);
1059 return true;
1060}
1061
Ana Krulecc84d09b2019-11-02 23:10:29 +01001062bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001063 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1064 mDrawingState.frameRateSelectionPriority = priority;
1065 mDrawingState.sequence++;
1066 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001067 setTransactionFlags(eTransactionNeeded);
1068 return true;
1069}
1070
1071int32_t Layer::getFrameRateSelectionPriority() const {
1072 // Check if layer has priority set.
1073 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1074 return mDrawingState.frameRateSelectionPriority;
1075 }
1076 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001077 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001078 if (parent != nullptr) {
1079 return parent->getFrameRateSelectionPriority();
1080 }
1081
1082 return Layer::PRIORITY_UNSET;
1083}
1084
Andy Labrada096227e2022-06-15 16:58:11 +00001085bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1086 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1087 mDrawingState.defaultFrameRateCompatibility = compatibility;
1088 mDrawingState.modified = true;
1089 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1090 setTransactionFlags(eTransactionNeeded);
1091 return true;
1092}
1093
1094scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1095 return mDrawingState.defaultFrameRateCompatibility;
1096}
1097
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001098bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1099 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1100};
1101
Vishnu Nair73908d12022-10-24 21:46:42 -07001102ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1103 bool useDrawing = state == LayerVector::StateSet::Drawing;
1104 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1105 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001106 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001107 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001108 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001109}
1110
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001111bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001112 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001113 return false;
1114 }
1115
Robert Carr6a160312021-05-17 12:08:20 -07001116 mDrawingState.sequence++;
1117 mDrawingState.shadowRadius = shadowRadius;
1118 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001119 setTransactionFlags(eTransactionNeeded);
1120 return true;
1121}
1122
Vishnu Nair6213bd92020-05-08 17:42:25 -07001123bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001124 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001125 return false;
1126 }
1127
Robert Carr6a160312021-05-17 12:08:20 -07001128 mDrawingState.sequence++;
1129 mDrawingState.fixedTransformHint = fixedTransformHint;
1130 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001131 setTransactionFlags(eTransactionNeeded);
1132 return true;
1133}
1134
John Reckcdb4ed72021-02-04 13:39:33 -05001135bool Layer::setStretchEffect(const StretchEffect& effect) {
1136 StretchEffect temp = effect;
1137 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001138 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001139 return false;
1140 }
Robert Carr6a160312021-05-17 12:08:20 -07001141 mDrawingState.sequence++;
1142 mDrawingState.stretchEffect = temp;
1143 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001144 setTransactionFlags(eTransactionNeeded);
1145 return true;
1146}
1147
John Reckc00c6692021-02-16 11:37:33 -05001148StretchEffect Layer::getStretchEffect() const {
1149 if (mDrawingState.stretchEffect.hasEffect()) {
1150 return mDrawingState.stretchEffect;
1151 }
1152
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001153 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001154 if (parent != nullptr) {
1155 auto effect = parent->getStretchEffect();
1156 if (effect.hasEffect()) {
1157 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1158 return effect;
1159 }
1160 }
1161 return StretchEffect{};
1162}
1163
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001164bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1165 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001166 return false;
1167 }
1168 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001169 mBorderWidth = width;
1170 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001171 return true;
1172}
1173
1174bool Layer::isBorderEnabled() {
1175 return mBorderEnabled;
1176}
1177
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001178float Layer::getBorderWidth() {
1179 return mBorderWidth;
1180}
1181
1182const half4& Layer::getBorderColor() {
1183 return mBorderColor;
1184}
1185
Ady Abrahama850c182021-08-04 13:04:37 -07001186bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1187 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1188 const auto frameRate = [&] {
1189 if (mDrawingState.frameRate.rate.isValid() ||
1190 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1191 return mDrawingState.frameRate;
1192 }
1193
1194 return parentFrameRate;
1195 }();
1196
1197 *transactionNeeded |= setFrameRateForLayerTree(frameRate);
1198
1199 // The frame rate is propagated to the children
1200 bool childrenHaveFrameRate = false;
1201 for (const sp<Layer>& child : mCurrentChildren) {
1202 childrenHaveFrameRate |=
1203 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1204 }
1205
1206 // If we don't have a valid frame rate, but the children do, we set this
1207 // layer as NoVote to allow the children to control the refresh rate
1208 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1209 childrenHaveFrameRate) {
1210 *transactionNeeded |=
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001211 setFrameRateForLayerTree(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001212 }
1213
1214 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1215 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001216 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001217 const auto layerVotedWithDefaultCompatibility =
1218 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1219 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1220 const auto layerVotedWithExactCompatibility =
1221 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1222 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1223 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1224}
1225
Ady Abraham60e42ea2020-03-09 19:17:31 -07001226void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001227 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001228 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001229 while (auto parent = layer->getParent()) {
1230 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001231 }
Ady Abrahama850c182021-08-04 13:04:37 -07001232 return layer;
1233 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001234
Ady Abraham60e42ea2020-03-09 19:17:31 -07001235 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001236 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001237
Ady Abrahama850c182021-08-04 13:04:37 -07001238 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001239 if (transactionNeeded) {
1240 mFlinger->setTransactionFlags(eTraversalNeeded);
1241 }
1242}
1243
Ady Abraham71c437d2020-01-31 15:56:57 -08001244bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001245 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001246 return false;
1247 }
1248
Robert Carr6a160312021-05-17 12:08:20 -07001249 mDrawingState.sequence++;
1250 mDrawingState.frameRate = frameRate;
1251 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001252
1253 updateTreeHasFrameRateVote();
1254
Steven Thomas3172e202020-01-06 19:25:30 -08001255 setTransactionFlags(eTransactionNeeded);
1256 return true;
1257}
1258
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001259void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1260 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001261 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001262
1263 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1264 // there are two transactions with the same token, the first one without a buffer and the
1265 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1266 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001267 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1268 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001269 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001270 mDrawingState.bufferSurfaceFrameTX = it->second;
1271 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1272 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1273 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001274 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001275 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001276 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1277 }
1278}
1279
1280void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1281 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001282 mDrawingState.frameTimelineInfo = info;
1283 mDrawingState.postTime = postTime;
1284 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001285 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001286
Robert Carr6a160312021-05-17 12:08:20 -07001287 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001288 bufferSurfaceFrameTX != nullptr) {
1289 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1290 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1291 // being used for BufferSurfaceFrame, don't create a new one.
1292 return;
1293 }
1294 }
1295 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1296 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1297 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001298 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1299 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001300 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001301 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001302 } else {
1303 if (it->second->getPresentState() == PresentState::Presented) {
1304 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1305 // have been from previous vsync.
1306 it->second = createSurfaceFrameForTransaction(info, postTime);
1307 }
1308 }
1309}
1310
1311void Layer::addSurfaceFrameDroppedForBuffer(
1312 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001313 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001314 surfaceFrame->setPresentState(PresentState::Dropped);
1315 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1316}
1317
1318void Layer::addSurfaceFramePresentedForBuffer(
1319 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1320 nsecs_t currentLatchTime) {
1321 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1322 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1323 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1324 mLastLatchTime = currentLatchTime;
1325}
1326
1327std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1328 const FrameTimelineInfo& info, nsecs_t postTime) {
1329 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001330 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1331 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001332 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001333 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001334 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001335 // For Transactions, the post time is considered to be both queue and acquire fence time.
1336 surfaceFrame->setActualQueueTime(postTime);
1337 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001338 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1339 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001340 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001341 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001342 onSurfaceFrameCreated(surfaceFrame);
1343 return surfaceFrame;
1344}
1345
1346std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1347 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1348 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001349 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001350 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001351 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001352 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001353 // For buffers, acquire fence time will set during latch.
1354 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001355 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1356 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001357 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001358 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001359 onSurfaceFrameCreated(surfaceFrame);
1360 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001361}
1362
Ady Abrahama850c182021-08-04 13:04:37 -07001363bool Layer::setFrameRateForLayerTree(FrameRate frameRate) {
1364 if (mDrawingState.frameRateForLayerTree == frameRate) {
1365 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001366 }
1367
Ady Abrahama850c182021-08-04 13:04:37 -07001368 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001369
Ady Abrahama850c182021-08-04 13:04:37 -07001370 // TODO(b/195668952): we probably don't need to dirty visible regions here
1371 // or even store frameRateForLayerTree in mDrawingState
1372 mDrawingState.sequence++;
1373 mDrawingState.modified = true;
1374 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001375
Dominik Laskowski068173d2021-08-11 17:22:59 -07001376 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
1377 mFlinger->mScheduler->recordLayerHistory(this, systemTime(), LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001378
1379 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001380}
1381
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001382Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1383 return getDrawingState().frameRateForLayerTree;
1384}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001385
Robert Carr1f0a16a2016-10-24 16:27:39 -07001386bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001387 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001388 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001389 if (parent != nullptr && parent->isHiddenByPolicy()) {
1390 return true;
1391 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001392 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1393 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1394 if (zOrderRelativeOf != nullptr) {
1395 if (zOrderRelativeOf->isHiddenByPolicy()) {
1396 return true;
1397 }
1398 }
1399 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001400 if (CC_UNLIKELY(!isTransformValid())) {
1401 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1402 return true;
1403 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001404 return s.flags & layer_state_t::eLayerHidden;
1405}
1406
David Sodman41fdfc92017-11-06 16:09:56 -08001407uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001408 // TODO: should we do something special if mSecure is set?
1409 if (mProtectedByApp) {
1410 // need a hardware-protected path to external video sink
1411 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001412 }
Riley Andrews03414a12014-07-01 14:22:59 -07001413 if (mPotentialCursor) {
1414 usage |= GraphicBuffer::USAGE_CURSOR;
1415 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001416 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001417 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001418}
1419
Vishnu Nair71fcf912022-10-18 09:14:20 -07001420void Layer::skipReportingTransformHint() {
1421 mSkipReportingTransformHint = true;
1422}
1423
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001424void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1425 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1426 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001427 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001428
Vishnu Nair6213bd92020-05-08 17:42:25 -07001429 setTransformHint(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001430}
1431
Mathias Agopian13127d82013-03-05 17:47:11 -08001432// ----------------------------------------------------------------------------
1433// debugging
1434// ----------------------------------------------------------------------------
1435
Marissa Wall61c58622018-07-18 10:12:20 -07001436// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001437gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001438 using namespace std::string_literals;
1439
Huihong Luo05539a12022-02-23 10:29:40 -08001440 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001441 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001442 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001443 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001444 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001445 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001446
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001447 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001448 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001449 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001450 info.mX = ds.transform.tx();
1451 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001452 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001453 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001454 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001455 info.mFlags = ds.flags;
1456 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001457 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001458 info.mMatrix[0][0] = ds.transform[0][0];
1459 info.mMatrix[0][1] = ds.transform[0][1];
1460 info.mMatrix[1][0] = ds.transform[1][0];
1461 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001462 {
chaviwd62d3062019-09-04 14:48:02 -07001463 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001464 if (buffer != 0) {
1465 info.mActiveBufferWidth = buffer->getWidth();
1466 info.mActiveBufferHeight = buffer->getHeight();
1467 info.mActiveBufferStride = buffer->getStride();
1468 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001469 } else {
1470 info.mActiveBufferWidth = 0;
1471 info.mActiveBufferHeight = 0;
1472 info.mActiveBufferStride = 0;
1473 info.mActiveBufferFormat = 0;
1474 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001475 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001476 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001477 info.mIsOpaque = isOpaque(ds);
1478 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001479 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001480 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001481}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001482
Yiwei Zhang5434a782018-12-05 18:06:32 -08001483void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001484 result.append(kDumpTableRowLength, '-');
1485 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001486 result.append(" Layer name\n");
1487 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001488 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001489 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001490 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001491 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001492 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001493 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1494 result.append(kDumpTableRowLength, '-');
1495 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001496}
1497
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001498void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1499 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001500 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001501 return;
1502 }
1503
Yiwei Zhang5434a782018-12-05 18:06:32 -08001504 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001505 if (mName.length() > 77) {
1506 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001507 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001508 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001509 shortened.append(mName, mName.length() - 36);
1510 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001511 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001512 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001513 }
1514
Yiwei Zhang5434a782018-12-05 18:06:32 -08001515 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001516
Alec Mourib416efd2018-09-06 21:01:59 +00001517 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001518 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001519
Chia-I Wu1e043612018-03-01 09:45:09 -08001520 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001521 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001522 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001523 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001524 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001525 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001526 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001527 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1528 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001529 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001530 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001531 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001532 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001533 const auto frameRate = getFrameRateForLayerTree();
1534 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1535 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001536 ftl::enum_string(frameRate.type).c_str(),
1537 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001538 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001539 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001540 }
Dan Stozae22aec72016-08-01 13:20:59 -07001541
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001542 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1543 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1544
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001545 result.append(kDumpTableRowLength, '-');
1546 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001547}
Dan Stozae22aec72016-08-01 13:20:59 -07001548
Yiwei Zhang5434a782018-12-05 18:06:32 -08001549void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001550 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001551}
1552
Svetoslavd85084b2014-03-20 10:28:31 -07001553void Layer::clearFrameStats() {
1554 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001555}
1556
Jamie Gennis6547ff42013-07-16 20:12:42 -07001557void Layer::logFrameStats() {
1558 mFrameTracker.logAndResetStats(mName);
1559}
1560
Svetoslavd85084b2014-03-20 10:28:31 -07001561void Layer::getFrameStats(FrameStats* outStats) const {
1562 mFrameTracker.getStats(outStats);
1563}
1564
Vishnu Nair76554eb2022-12-09 03:38:36 +00001565void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1566 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
1567 StringAppendF(&result, "Layer %s%s pid:%d uid:%d\n", getName().c_str(), hasBuffer.c_str(),
Vishnu Naircb8be502022-10-12 19:03:23 +00001568 mOwnerPid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001569}
1570
Brian Anderson5ea5e592016-12-01 16:54:33 -08001571void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001572 const int32_t layerId = getSequence();
1573 mFlinger->mTimeStats->onDestroy(layerId);
1574 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001575}
1576
Chia-I Wu98f1c102017-05-30 14:54:08 -07001577size_t Layer::getChildrenCount() const {
1578 size_t count = 0;
1579 for (const sp<Layer>& child : mCurrentChildren) {
1580 count += 1 + child->getChildrenCount();
1581 }
1582 return count;
1583}
1584
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001585void Layer::setGameModeForTree(GameMode gameMode) {
1586 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001587 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1588 gameMode =
1589 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001590 }
1591 setGameMode(gameMode);
1592 for (const sp<Layer>& child : mCurrentChildren) {
1593 child->setGameModeForTree(gameMode);
1594 }
1595}
1596
Robert Carr1f0a16a2016-10-24 16:27:39 -07001597void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001598 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001599 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001600
Robert Carr1f0a16a2016-10-24 16:27:39 -07001601 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001602 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001603 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001604 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001605}
1606
1607ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001608 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001609 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001610
Robert Carr1323c952019-01-28 18:13:27 -08001611 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001612 const auto removeResult = mCurrentChildren.remove(layer);
1613
1614 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001615 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001616 layer->updateTreeHasFrameRateVote();
1617
1618 return removeResult;
1619}
1620
Robert Carr15eae092018-03-23 13:43:53 -07001621void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001622 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001623 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001624 const float parentShadowRadius =
1625 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001626 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001627 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001628 }
1629}
1630
chaviwf1961f72017-09-18 16:41:07 -07001631bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001632 sp<Layer> newParent;
1633 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001634 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001635 if (newParent == nullptr) {
1636 ALOGE("Unable to promote Layer handle");
1637 return false;
1638 }
1639 if (newParent == this) {
1640 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1641 return false;
1642 }
1643 }
1644
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001645 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001646 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001647 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001648 }
1649
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001650 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001651 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001652 if (!newParent->isRemovedFromCurrentState()) {
1653 addToCurrentState();
1654 } else {
1655 onRemovedFromCurrentState();
1656 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001657 } else {
1658 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001659 }
1660
chaviw06178942017-07-27 10:25:59 -07001661 return true;
1662}
1663
Peiyong Lind3788632018-09-18 16:01:31 -07001664bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001665 static const mat4 identityMatrix = mat4();
1666
Robert Carr6a160312021-05-17 12:08:20 -07001667 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001668 return false;
1669 }
Robert Carr6a160312021-05-17 12:08:20 -07001670 ++mDrawingState.sequence;
1671 mDrawingState.colorTransform = matrix;
1672 mDrawingState.hasColorTransform = matrix != identityMatrix;
1673 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001674 setTransactionFlags(eTransactionNeeded);
1675 return true;
1676}
1677
chaviwf66724d2018-11-28 16:35:21 -08001678mat4 Layer::getColorTransform() const {
1679 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001680 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001681 colorTransform = parent->getColorTransform() * colorTransform;
1682 }
1683 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001684}
1685
1686bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001687 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001688 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001689 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1690 }
1691 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001692}
1693
Chia-I Wu11481472018-05-04 10:43:19 -07001694bool Layer::isLegacyDataSpace() const {
1695 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001696 return !(getDataSpace() &
1697 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1698 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001699}
1700
Robert Carr1f0a16a2016-10-24 16:27:39 -07001701void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001702 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001703}
1704
Robert Carr6a160312021-05-17 12:08:20 -07001705int32_t Layer::getZ(LayerVector::StateSet) const {
1706 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001707}
1708
Robert Carr1c5481e2019-07-01 14:42:27 -07001709bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001710 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001711 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001712 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001713}
1714
David Sodman41fdfc92017-11-06 16:09:56 -08001715__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001716 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001717 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1718 "makeTraversalList received invalid stateSet");
1719 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1720 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001721 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001722
Robert Carr29abff82017-12-04 13:51:20 -08001723 if (state.zOrderRelatives.size() == 0) {
1724 *outSkipRelativeZUsers = true;
1725 return children;
1726 }
1727
chaviwfd462612018-05-31 16:11:27 -07001728 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001729 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001730 sp<Layer> strongRelative = weakRelative.promote();
1731 if (strongRelative != nullptr) {
1732 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001733 }
1734 }
1735
Dan Stoza412903f2017-04-27 13:42:17 -07001736 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001737 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001738 continue;
1739 }
Robert Carrdb66e622017-04-10 16:55:57 -07001740 traverse.add(child);
1741 }
1742
1743 return traverse;
1744}
1745
Robert Carr1f0a16a2016-10-24 16:27:39 -07001746/**
Robert Carrdb66e622017-04-10 16:55:57 -07001747 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001748 */
Dan Stoza412903f2017-04-27 13:42:17 -07001749void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001750 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1751 // produce a new list for traversing, including our relatives, and not including our children
1752 // who are relatives of another surface. In the case that there are no relative Z,
1753 // makeTraversalList returns our children directly to avoid significant overhead.
1754 // However in this case we need to take the responsibility for filtering children which
1755 // are relatives of another surface here.
1756 bool skipRelativeZUsers = false;
1757 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001758
Robert Carr1f0a16a2016-10-24 16:27:39 -07001759 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001760 for (; i < list.size(); i++) {
1761 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001762 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1763 continue;
1764 }
1765
chaviw301b1d82019-11-06 13:15:09 -08001766 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001767 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001768 }
Dan Stoza412903f2017-04-27 13:42:17 -07001769 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001770 }
Robert Carr29abff82017-12-04 13:51:20 -08001771
Dan Stoza412903f2017-04-27 13:42:17 -07001772 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001773 for (; i < list.size(); i++) {
1774 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001775
Robert Carr29abff82017-12-04 13:51:20 -08001776 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1777 continue;
1778 }
Dan Stoza412903f2017-04-27 13:42:17 -07001779 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001780 }
1781}
1782
1783/**
Robert Carrdb66e622017-04-10 16:55:57 -07001784 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001785 */
Dan Stoza412903f2017-04-27 13:42:17 -07001786void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1787 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001788 // See traverseInZOrder for documentation.
1789 bool skipRelativeZUsers = false;
1790 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001791
Robert Carr1f0a16a2016-10-24 16:27:39 -07001792 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001793 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001794 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001795
1796 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1797 continue;
1798 }
1799
chaviw301b1d82019-11-06 13:15:09 -08001800 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001801 break;
1802 }
Dan Stoza412903f2017-04-27 13:42:17 -07001803 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001804 }
Dan Stoza412903f2017-04-27 13:42:17 -07001805 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001806 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001807 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001808
1809 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1810 continue;
1811 }
1812
Dan Stoza412903f2017-04-27 13:42:17 -07001813 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001814 }
1815}
1816
Edgar Arriaga844fa672020-01-16 14:21:42 -08001817void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1818 visitor(this);
1819 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001820 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001821 for (const sp<Layer>& child : children) {
1822 child->traverse(state, visitor);
1823 }
1824}
1825
chaviw4b129c22018-04-09 16:19:43 -07001826LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1827 const std::vector<Layer*>& layersInTree) {
1828 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1829 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001830 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1831 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001832 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001833
chaviwfd462612018-05-31 16:11:27 -07001834 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001835 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1836 sp<Layer> strongRelative = weakRelative.promote();
1837 // Only add relative layers that are also descendents of the top most parent of the tree.
1838 // If a relative layer is not a descendent, then it should be ignored.
1839 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1840 traverse.add(strongRelative);
1841 }
1842 }
1843
1844 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001845 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001846 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1847 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1848 // the child here since it won't be added later as a relative.
1849 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1850 childState.zOrderRelativeOf.promote().get())) {
1851 continue;
1852 }
1853 traverse.add(child);
1854 }
1855
1856 return traverse;
1857}
1858
1859void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1860 LayerVector::StateSet stateSet,
1861 const LayerVector::Visitor& visitor) {
1862 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001863
1864 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001865 for (; i < list.size(); i++) {
1866 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001867 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001868 break;
1869 }
chaviw4b129c22018-04-09 16:19:43 -07001870 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001871 }
chaviw4b129c22018-04-09 16:19:43 -07001872
chaviwa76b2712017-09-20 12:02:26 -07001873 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001874 for (; i < list.size(); i++) {
1875 const auto& relative = list[i];
1876 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001877 }
1878}
1879
chaviw4b129c22018-04-09 16:19:43 -07001880std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1881 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1882 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1883
1884 std::vector<Layer*> layersInTree = {this};
1885 for (size_t i = 0; i < children.size(); i++) {
1886 const auto& child = children[i];
1887 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1888 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1889 }
1890
1891 return layersInTree;
1892}
1893
1894void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1895 const LayerVector::Visitor& visitor) {
1896 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1897 std::sort(layersInTree.begin(), layersInTree.end());
1898 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1899}
1900
Peiyong Linefefaac2018-08-17 12:27:51 -07001901ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001902 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001903}
1904
Garfield Tan2c1782c2022-02-16 15:25:05 -08001905bool Layer::isTransformValid() const {
1906 float transformDet = getTransform().det();
1907 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1908}
1909
chaviw13fdc492017-06-27 12:40:18 -07001910half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001911 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001912
chaviw13fdc492017-06-27 12:40:18 -07001913 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1914 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07001915}
Robert Carr6452f122017-03-21 10:41:29 -07001916
Vishnu Nair6213bd92020-05-08 17:42:25 -07001917ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07001918 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001919 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
1920 return fixedTransformHint;
1921 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001922 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07001923 if (!p) return fixedTransformHint;
1924 return p->getFixedTransformHint();
1925}
1926
chaviw13fdc492017-06-27 12:40:18 -07001927half4 Layer::getColor() const {
1928 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001929 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07001930}
Robert Carr6452f122017-03-21 10:41:29 -07001931
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001932int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00001933 if (getDrawingState().backgroundBlurRadius == 0) {
1934 return 0;
1935 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01001936
Vishnu Nair29810f72022-07-01 16:38:41 +00001937 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01001938 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1939 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001940}
1941
Galia Peychevae0acf382021-04-12 21:22:34 +02001942const std::vector<BlurRegion> Layer::getBlurRegions() const {
1943 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02001944 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02001945 for (auto& region : regionsCopy) {
1946 region.alpha = region.alpha * layerAlpha;
1947 }
1948 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001949}
1950
Vishnu Naire14c6b32022-08-06 04:20:15 +00001951RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001952 // Get parent settings
1953 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001954 const auto& parent = mDrawingParent.promote();
1955 if (parent != nullptr) {
1956 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001957 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001958 ui::Transform t = getActiveTransform(getDrawingState());
1959 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001960 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001961 parentSettings.radius.x *= t.getScaleX();
1962 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001963 }
1964 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001965
1966 // Get layer settings
1967 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001968 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001969 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001970 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001971
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001972 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001973 // If the parent and the layer have rounded corner settings, use the parent settings if the
1974 // parent crop is entirely inside the layer crop.
1975 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
1976 if (parentSettings.cropRect.left > layerCropRect.left &&
1977 parentSettings.cropRect.top > layerCropRect.top &&
1978 parentSettings.cropRect.right < layerCropRect.right &&
1979 parentSettings.cropRect.bottom < layerCropRect.bottom) {
1980 return parentSettings;
1981 } else {
1982 return layerSettings;
1983 }
Vishnu Nairb1845592021-10-07 12:17:57 -07001984 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001985 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001986 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001987 return parentSettings;
1988 }
1989 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001990}
1991
Robert Carr88b85e12022-03-21 15:47:35 -07001992bool Layer::findInHierarchy(const sp<Layer>& l) {
1993 if (l == this) {
1994 return true;
1995 }
1996 for (auto& child : mDrawingChildren) {
1997 if (child->findInHierarchy(l)) {
1998 return true;
1999 }
2000 }
2001 return false;
2002}
2003
Robert Carr1f0a16a2016-10-24 16:27:39 -07002004void Layer::commitChildList() {
2005 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2006 const auto& child = mCurrentChildren[i];
2007 child->commitChildList();
2008 }
2009 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002010 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002011 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2012 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2013 if (zOrderRelativeOf == nullptr) return;
2014 if (findInHierarchy(zOrderRelativeOf)) {
2015 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2016 zOrderRelativeOf->mName.c_str());
2017 ALOGE("Severing rel Z loop, potentially dangerous");
2018 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002019 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002020 }
2021 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002022}
2023
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002024
chaviw3277faf2021-05-19 16:45:23 -05002025void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002026 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002027 mDrawingState.touchableRegionCrop =
2028 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002029 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002030 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002031 setTransactionFlags(eTransactionNeeded);
2032}
2033
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002034LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002035 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002036 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002037 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2038
Vishnu Nair00b90132021-11-05 14:03:40 -07002039 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002040 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2041
Vishnu Nair60db8c02020-04-02 11:55:16 -07002042 // Only populate for the primary display.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002043 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -05002044 const auto compositionType = getCompositionType(*display);
Vishnu Nair60db8c02020-04-02 11:55:16 -07002045 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002046 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2047 [&]() { return layerProto->mutable_visible_region(); });
Vishnu Nair60db8c02020-04-02 11:55:16 -07002048 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08002049 }
2050
chaviw08f3cb22020-01-13 13:17:21 -08002051 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002052 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002053 }
chaviw6d89e2d2020-01-14 14:42:01 -08002054
2055 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002056}
2057
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002058void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002059 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002060 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002061 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002062 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002063 [&]() { return layerInfo->mutable_active_buffer(); });
2064 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2065 layerInfo->mutable_buffer_transform());
2066 }
2067 layerInfo->set_invalidate(contentDirty);
2068 layerInfo->set_is_protected(isProtected());
2069 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2070 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002071 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002072 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002073 layerInfo->set_corner_radius(
2074 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002075 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2076 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2077 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2078 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2079 [&]() { return layerInfo->mutable_position(); });
2080 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002081 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2082 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002083
Vishnu Nair00b90132021-11-05 14:03:40 -07002084 if (hasColorTransform()) {
2085 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002086 }
2087
Vishnu Nair60db8c02020-04-02 11:55:16 -07002088 LayerProtoHelper::writeToProto(mSourceBounds,
2089 [&]() { return layerInfo->mutable_source_bounds(); });
2090 LayerProtoHelper::writeToProto(mScreenBounds,
2091 [&]() { return layerInfo->mutable_screen_bounds(); });
2092 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2093 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2094 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002095}
2096
2097void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002098 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002099 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2100 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002101 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002102
chaviw766c9c52021-02-10 17:36:47 -08002103 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002104
Vishnu Nair00b90132021-11-05 14:03:40 -07002105 layerInfo->set_id(sequence);
2106 layerInfo->set_name(getName().c_str());
2107 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002108
Vishnu Nair00b90132021-11-05 14:03:40 -07002109 for (const auto& child : children) {
2110 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002111 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002112
Vishnu Nair00b90132021-11-05 14:03:40 -07002113 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2114 sp<Layer> strongRelative = weakRelative.promote();
2115 if (strongRelative != nullptr) {
2116 layerInfo->add_relatives(strongRelative->sequence);
2117 }
2118 }
2119
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002120 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002121 [&]() { return layerInfo->mutable_transparent_region(); });
2122
2123 layerInfo->set_layer_stack(getLayerStack().id);
2124 layerInfo->set_z(state.z);
2125
2126 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2127 return layerInfo->mutable_requested_position();
2128 });
2129
Vishnu Nair00b90132021-11-05 14:03:40 -07002130 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2131
2132 layerInfo->set_is_opaque(isOpaque(state));
2133
2134 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2135 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2136 LayerProtoHelper::writeToProto(state.color,
2137 [&]() { return layerInfo->mutable_requested_color(); });
2138 layerInfo->set_flags(state.flags);
2139
2140 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2141 layerInfo->mutable_requested_transform());
2142
2143 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2144 if (parent != nullptr) {
2145 layerInfo->set_parent(parent->sequence);
2146 } else {
2147 layerInfo->set_parent(-1);
2148 }
2149
2150 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2151 if (zOrderRelativeOf != nullptr) {
2152 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2153 } else {
2154 layerInfo->set_z_order_relative_of(-1);
2155 }
2156
2157 layerInfo->set_is_relative_of(state.isRelativeOf);
2158
2159 layerInfo->set_owner_uid(mOwnerUid);
2160
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002161 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002162 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002163 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002164 info = fillInputInfo(
2165 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002166 } else {
2167 info = state.inputInfo;
2168 }
2169
2170 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002171 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002172 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002173
Vishnu Nair00b90132021-11-05 14:03:40 -07002174 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002175 auto protoMap = layerInfo->mutable_metadata();
2176 for (const auto& entry : state.metadata.mMap) {
2177 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2178 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002179 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002180
2181 LayerProtoHelper::writeToProto(state.destinationFrame,
2182 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002183}
2184
Robert Carr2e102c92018-10-23 12:11:15 -07002185bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002186 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002187}
2188
Prabir Pradhan33da9462022-06-14 14:55:57 +00002189// Applies the given transform to the region, while protecting against overflows caused by any
2190// offsets. If applying the offset in the transform to any of the Rects in the region would result
2191// in an overflow, they are not added to the output Region.
2192static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2193 const std::string& debugWindowName) {
2194 // Round the translation using the same rounding strategy used by ui::Transform.
2195 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2196 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2197
2198 ui::Transform transformWithoutOffset = t;
2199 transformWithoutOffset.set(0.f, 0.f);
2200
2201 const Region transformed = transformWithoutOffset.transform(r);
2202
2203 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2204 Region ret;
2205 for (const auto& rect : transformed) {
2206 Rect newRect;
2207 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2208 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2209 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2210 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2211 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2212 debugWindowName.c_str());
2213 continue;
2214 }
2215 ret.orSelf(newRect);
2216 }
2217 return ret;
2218}
2219
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002220void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
2221 Rect tmpBounds = getInputBounds();
2222 if (!tmpBounds.isValid()) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002223 info.touchableRegion.clear();
2224 // A layer could have invalid input bounds and still expect to receive touch input if it has
2225 // replaceTouchableRegionWithCrop. For that case, the input transform needs to be calculated
2226 // correctly to determine the coordinate space for input events. Use an empty rect so that
2227 // the layer will receive input in its own layer space.
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002228 tmpBounds = Rect::EMPTY_RECT;
chaviw7e72caf2020-12-02 16:50:43 -08002229 }
2230
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002231 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2232 // frame and transform used for the layer, which determines the bounds and the coordinate space
2233 // within which the layer will receive input.
2234 //
2235 // The coordinate space within which each of the bounds are specified is explicitly documented
2236 // in the variable name. For example "inputBoundsInLayer" is specified in layer space. A
2237 // Transform converts one coordinate space to another, which is apparent in its naming. For
2238 // example, "layerToDisplay" transforms layer space to display space.
2239 //
2240 // Coordinate space definitions:
2241 // - display: The display device's coordinate space. Correlates to pixels on the display.
2242 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2243 // - layer: The coordinate space of this layer.
2244 // - input: The coordinate space in which this layer will receive input events. This could be
2245 // different than layer space if a surfaceInset is used, which changes the origin
2246 // of the input space.
2247 const FloatRect inputBoundsInLayer = tmpBounds.toFloatRect();
chaviw7e72caf2020-12-02 16:50:43 -08002248
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002249 // Clamp surface inset to the input bounds.
2250 const auto surfaceInset = static_cast<float>(info.surfaceInset);
2251 const float xSurfaceInset =
2252 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getWidth() / 2.f));
2253 const float ySurfaceInset =
2254 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getHeight() / 2.f));
chaviw1ff3d1e2020-07-01 15:53:47 -07002255
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002256 // Apply the insets to the input bounds.
2257 const FloatRect insetBoundsInLayer(inputBoundsInLayer.left + xSurfaceInset,
2258 inputBoundsInLayer.top + ySurfaceInset,
2259 inputBoundsInLayer.right - xSurfaceInset,
2260 inputBoundsInLayer.bottom - ySurfaceInset);
Ady Abraham282f1d72019-07-24 18:05:56 -07002261
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002262 // Crop the input bounds to ensure it is within the parent's bounds.
2263 const FloatRect croppedInsetBoundsInLayer = mBounds.intersect(insetBoundsInLayer);
Ady Abraham282f1d72019-07-24 18:05:56 -07002264
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002265 const ui::Transform layerToScreen = getInputTransform();
2266 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
Vishnu Nair8033a492018-12-05 07:27:23 -08002267
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002268 const Rect roundedFrameInDisplay{layerToDisplay.transform(croppedInsetBoundsInLayer)};
2269 info.frameLeft = roundedFrameInDisplay.left;
2270 info.frameTop = roundedFrameInDisplay.top;
2271 info.frameRight = roundedFrameInDisplay.right;
2272 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002273
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002274 ui::Transform inputToLayer;
2275 inputToLayer.set(insetBoundsInLayer.left, insetBoundsInLayer.top);
2276 const ui::Transform inputToDisplay = layerToDisplay * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002277
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002278 // InputDispatcher expects a display-to-input transform.
2279 info.transform = inputToDisplay.inverse();
2280
2281 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002282 info.touchableRegion =
2283 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002284}
2285
chaviw3277faf2021-05-19 16:45:23 -05002286void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002287 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002288 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002289 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002290 }
2291 if (p != nullptr) {
2292 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2293 }
2294}
2295
Vishnu Naira066d902021-09-13 18:40:17 -07002296gui::DropInputMode Layer::getDropInputMode() const {
2297 gui::DropInputMode mode = mDrawingState.dropInputMode;
2298 if (mode == gui::DropInputMode::ALL) {
2299 return mode;
2300 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002301 sp<Layer> parent = mDrawingParent.promote();
2302 if (parent) {
2303 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002304 if (parentMode != gui::DropInputMode::NONE) {
2305 return parentMode;
2306 }
2307 }
2308 return mode;
2309}
2310
2311void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002312 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002313 return;
2314 }
2315
2316 // Check if we need to drop input unconditionally
2317 gui::DropInputMode dropInputMode = getDropInputMode();
2318 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002319 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002320 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2321 return;
2322 }
2323
2324 // Check if we need to check if the window is obscured by parent
2325 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2326 return;
2327 }
2328
2329 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002330 sp<Layer> parent = mDrawingParent.promote();
2331 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002332 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002333 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2334 static_cast<float>(getAlpha()));
2335 }
2336
2337 // Check if the parent has cropped the buffer
2338 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2339 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002340 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002341 return;
2342 }
2343
2344 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2345 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2346 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2347 // match then the layer has not been cropped by its parents.
2348 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2349 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2350
2351 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002352 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002353 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2354 getDebugName());
2355 } else {
2356 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2357 // input if the window is obscured. This check should be done in surfaceflinger but the
2358 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2359 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002360 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002361 }
2362}
2363
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002364WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002365 if (!hasInputInfo()) {
2366 mDrawingState.inputInfo.name = getName();
2367 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2368 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002369 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002370 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002371 }
2372
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002373 const ui::Transform& displayTransform =
2374 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2375
chaviw3277faf2021-05-19 16:45:23 -05002376 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002377 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002378 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002379
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002380 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002381
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002382 if (displayArgs.transform == nullptr) {
2383 // Do not let the window receive touches if it is not associated with a valid display
2384 // transform. We still allow the window to receive keys and prevent ANRs.
2385 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2386 }
2387
Robert Carr5dc426e2020-06-10 14:29:14 -07002388 // For compatibility reasons we let layers which can receive input
2389 // receive input before they have actually submitted a buffer. Because
2390 // of this we use canReceiveInput instead of isVisible to check the
2391 // policy-visibility, ignoring the buffer state. However for layers with
2392 // hasInputInfo()==false we can use the real visibility state.
2393 // We are just using these layers for occlusion detection in
2394 // InputDispatcher, and obviously if they aren't visible they can't occlude
2395 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002396 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2397 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2398
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002399 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002400 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002401 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002402
Vishnu Nair16a938f2021-09-24 07:14:54 -07002403 // If the window will be blacked out on a display because the display does not have the secure
2404 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002405 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002406 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002407 }
2408
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002409 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2410 if (info.replaceTouchableRegionWithCrop) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002411 const Rect bounds(cropLayer ? cropLayer->mScreenBounds : mScreenBounds);
2412 info.touchableRegion = Region(displayTransform.transform(bounds));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002413 } else if (cropLayer != nullptr) {
[1;3C2b9fc252021-02-04 16:16:50 -08002414 info.touchableRegion = info.touchableRegion.intersect(
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002415 displayTransform.transform(Rect{cropLayer->mScreenBounds}));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002416 }
2417
Winson Chunga30f7c92021-06-29 15:42:56 -07002418 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2419 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002420 if (isTrustedOverlay()) {
2421 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2422 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002423
chaviwaf87b3e2019-10-01 16:59:28 -07002424 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2425 // touches from going outside the cloned area.
2426 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002427 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002428 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2429 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002430 info.touchableRegion = info.touchableRegion.intersect(rect);
2431 }
2432 }
2433
Robert Carr720e5062018-07-30 17:45:14 -07002434 return info;
2435}
2436
chaviwaf87b3e2019-10-01 16:59:28 -07002437sp<Layer> Layer::getClonedRoot() {
2438 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002439 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002440 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002441 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002442 return nullptr;
2443 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002444 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002445}
2446
Robert Carredd13602020-04-13 17:24:34 -07002447bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002448 return mDrawingState.inputInfo.token != nullptr ||
2449 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002450}
2451
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002452compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002453 const DisplayDevice* display) const {
2454 if (!display) return nullptr;
Lloyd Piquede196652020-01-22 17:29:58 -08002455 return display->getCompositionDisplay()->getOutputLayerForLayer(getCompositionEngineLayerFE());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002456}
2457
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002458Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2459 const auto outputLayer = findOutputLayerForDisplay(display);
2460 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002461}
2462
chaviwb4c6e582019-08-16 14:35:07 -07002463void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002464 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002465 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002466 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2467 mPotentialCursor = clonedFrom->mPotentialCursor;
2468 mProtectedByApp = clonedFrom->mProtectedByApp;
2469 updateCloneBufferInfo();
2470}
2471
2472void Layer::updateCloneBufferInfo() {
2473 if (!isClone() || !isClonedFromAlive()) {
2474 return;
2475 }
2476
2477 sp<Layer> clonedFrom = getClonedFrom();
2478 mBufferInfo = clonedFrom->mBufferInfo;
2479 mSidebandStream = clonedFrom->mSidebandStream;
2480 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2481 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2482 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2483
2484 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2485 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2486 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2487 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2488 // the cloned drawingState again.
2489 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2490 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2491 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2492 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2493
2494 cloneDrawingState(clonedFrom.get());
2495
2496 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2497 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2498 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2499 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002500}
chaviw74b03172019-08-19 11:09:03 -07002501
2502void Layer::updateMirrorInfo() {
2503 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2504 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2505 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2506 // that case, we want to delete the reference to the clone since we want it to get
2507 // destroyed. The root, this layer, will still be around since the client can continue
2508 // to hold a reference, but no cloned layers will be displayed.
2509 mClonedChild = nullptr;
2510 return;
2511 }
2512
2513 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2514 // If the real layer exists and is in current state, add the clone as a child of the root.
2515 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2516 // copied to drawingState for the root layer. So the clonedChild is always removed from
2517 // drawingState and then needs to be added back each traversal.
2518 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2519 addChildToDrawing(mClonedChild);
2520 }
2521
2522 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002523 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002524 mClonedChild->updateClonedRelatives(clonedLayersMap);
2525}
2526
2527void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2528 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2529 // to the clone. If the real layer is no longer alive, continue traversing the children
2530 // since we may be able to pull out other children that are still alive.
2531 if (isClonedFromAlive()) {
2532 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002533 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002534 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002535 }
2536
2537 // The clone layer may have children in drawingState since they may have been created and
2538 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2539 // that already exist, since we can just re-use them.
2540 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2541 // not updated in the regular traversal. They are skipped since the root will lose the
2542 // reference to them when it copies its currentChildren to drawing.
2543 for (sp<Layer>& child : mDrawingChildren) {
2544 child->updateClonedDrawingState(clonedLayersMap);
2545 }
2546}
2547
2548void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2549 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2550 mDrawingChildren.clear();
2551
2552 if (!isClonedFromAlive()) {
2553 return;
2554 }
2555
2556 sp<Layer> clonedFrom = getClonedFrom();
2557 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2558 if (child == mirrorRoot) {
2559 // This is to avoid cyclical mirroring.
2560 continue;
2561 }
2562 sp<Layer> clonedChild = clonedLayersMap[child];
2563 if (clonedChild == nullptr) {
2564 clonedChild = child->createClone();
2565 clonedLayersMap[child] = clonedChild;
2566 }
2567 addChildToDrawing(clonedChild);
2568 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2569 }
2570}
2571
chaviwaf87b3e2019-10-01 16:59:28 -07002572void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2573 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2574 if (cropLayer != nullptr) {
2575 if (clonedLayersMap.count(cropLayer) == 0) {
2576 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2577 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002578 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002579 } else {
2580 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2581 mDrawingState.touchableRegionCrop = clonedCropLayer;
2582 }
2583 }
2584 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2585 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002586 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002587}
2588
2589void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002590 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002591 mDrawingState.zOrderRelatives.clear();
2592
2593 if (!isClonedFromAlive()) {
2594 return;
2595 }
2596
chaviwaf87b3e2019-10-01 16:59:28 -07002597 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002598 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002599 const sp<Layer>& relative = relativeWeak.promote();
2600 if (clonedLayersMap.count(relative) > 0) {
2601 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002602 mDrawingState.zOrderRelatives.add(clonedRelative);
2603 }
2604 }
2605
2606 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2607 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2608 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2609 // still traverse the children, but the layer with the missing relativeOf will not be shown
2610 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002611 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2612 if (clonedLayersMap.count(relativeOf) > 0) {
2613 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002614 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2615 }
2616
chaviwaf87b3e2019-10-01 16:59:28 -07002617 updateClonedInputInfo(clonedLayersMap);
2618
chaviw74b03172019-08-19 11:09:03 -07002619 for (sp<Layer>& child : mDrawingChildren) {
2620 child->updateClonedRelatives(clonedLayersMap);
2621 }
2622}
2623
2624void Layer::addChildToDrawing(const sp<Layer>& layer) {
2625 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002626 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002627}
2628
Steven Thomas62a4cf82020-01-31 12:04:03 -08002629Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2630 switch (compatibility) {
2631 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2632 return FrameRateCompatibility::Default;
2633 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2634 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002635 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2636 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002637 case ANATIVEWINDOW_FRAME_RATE_MIN:
2638 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002639 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2640 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002641 default:
2642 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2643 return FrameRateCompatibility::Default;
2644 }
2645}
2646
Marin Shalamanovc5986772021-03-16 16:09:49 +01002647scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2648 switch (strategy) {
2649 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2650 return Seamlessness::OnlySeamless;
2651 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2652 return Seamlessness::SeamedAndSeamless;
2653 default:
2654 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2655 return Seamlessness::Default;
2656 }
2657}
2658
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002659bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002660 const State& s(mDrawingState);
2661 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2662 return true;
2663 }
2664
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002665 sp<Layer> parent = mDrawingParent.promote();
2666 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002667}
2668
Robert Carr6a0382d2021-07-01 15:57:17 -07002669void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2670 mClonedChild = clonedChild;
2671 mHadClonedChild = true;
2672 mFlinger->mNumClones++;
2673}
2674
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002675bool Layer::setDropInputMode(gui::DropInputMode mode) {
2676 if (mDrawingState.dropInputMode == mode) {
2677 return false;
2678 }
2679 mDrawingState.dropInputMode = mode;
2680 return true;
2681}
2682
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002683void Layer::cloneDrawingState(const Layer* from) {
2684 mDrawingState = from->mDrawingState;
2685 // Skip callback info since they are not applicable for cloned layers.
2686 mDrawingState.releaseBufferListener = nullptr;
2687 mDrawingState.callbackHandles = {};
2688}
2689
Patrick Williamsbb25f802022-08-30 23:02:34 +00002690void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2691 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
2692 const sp<Fence>& releaseFence,
2693 uint32_t currentMaxAcquiredBufferCount) {
2694 if (!listener) {
2695 return;
2696 }
2697 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002698 listener->onReleaseBuffer({buffer->getId(), framenumber},
2699 releaseFence ? releaseFence : Fence::NO_FENCE,
2700 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002701}
2702
2703void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2704 // If we are displayed on multiple displays in a single composition cycle then we would
2705 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2706 // For example we can only use it if all the displays are client comp, and we need
2707 // to merge all the client comp fences. We could do this, but for now we just
2708 // disable the optimization when a layer is composed on multiple displays.
2709 if (mClearClientCompositionFenceOnLayerDisplayed) {
2710 mLastClientCompositionFence = nullptr;
2711 } else {
2712 mClearClientCompositionFenceOnLayerDisplayed = true;
2713 }
2714
2715 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2716 // buffer that was presented on this layer. The first transaction that came in this frame that
2717 // replaced the previous buffer on this layer needs this release fence, because the fence will
2718 // let the client know when that previous buffer is removed from the screen.
2719 //
2720 // Every other transaction on this layer does not need a release fence because no other
2721 // Transactions that were set on this layer this frame are going to have their preceding buffer
2722 // removed from the display this frame.
2723 //
2724 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2725 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2726 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2727 // the previous buffer will be released this frame. The third transaction also contains a
2728 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2729 // transaction will now no longer be presented so it is released immediately and the third
2730 // transaction doesn't need a previous release fence.
2731 sp<CallbackHandle> ch;
2732 for (auto& handle : mDrawingState.callbackHandles) {
2733 if (handle->releasePreviousBuffer &&
2734 mDrawingState.releaseBufferEndpoint == handle->listener) {
2735 ch = handle;
2736 break;
2737 }
2738 }
2739
2740 // Prevent tracing the same release multiple times.
2741 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2742 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2743 }
2744
2745 if (ch != nullptr) {
2746 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2747 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2748 ch->name = mName;
2749 }
2750}
2751
2752void Layer::onSurfaceFrameCreated(
2753 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Vishnu Nair22491b82022-10-18 14:59:14 -07002754 if (!hasBufferOrSidebandStreamInDrawing()) {
2755 return;
2756 }
2757
Patrick Williamsbb25f802022-08-30 23:02:34 +00002758 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2759 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2760 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2761 // leak.
2762 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2763 mName.c_str());
2764 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2765 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2766 mPendingJankClassifications.pop_front();
2767 }
2768 mPendingJankClassifications.emplace_back(surfaceFrame);
2769}
2770
2771void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2772 for (const auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair71fcf912022-10-18 09:14:20 -07002773 handle->transformHint = mSkipReportingTransformHint
2774 ? std::nullopt
2775 : std::make_optional<uint32_t>(mTransformHint);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002776 handle->dequeueReadyTime = dequeueReadyTime;
2777 handle->currentMaxAcquiredBufferCount =
2778 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2779 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2780 handle->previousReleaseCallbackId.framenumber);
2781 }
2782
2783 for (auto& handle : mDrawingState.callbackHandles) {
2784 if (handle->releasePreviousBuffer &&
2785 mDrawingState.releaseBufferEndpoint == handle->listener) {
2786 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2787 break;
2788 }
2789 }
2790
2791 std::vector<JankData> jankData;
2792 jankData.reserve(mPendingJankClassifications.size());
2793 while (!mPendingJankClassifications.empty() &&
2794 mPendingJankClassifications.front()->getJankType()) {
2795 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
2796 mPendingJankClassifications.front();
2797 mPendingJankClassifications.pop_front();
2798 jankData.emplace_back(
2799 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
2800 }
2801
2802 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2803 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002804 mDrawingState.callbackHandles = {};
2805}
2806
2807bool Layer::willPresentCurrentTransaction() const {
2808 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2809 return (getSidebandStreamChanged() || getAutoRefresh() ||
2810 (mDrawingState.modified &&
2811 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2812}
2813
2814bool Layer::setTransform(uint32_t transform) {
2815 if (mDrawingState.bufferTransform == transform) return false;
2816 mDrawingState.bufferTransform = transform;
2817 mDrawingState.modified = true;
2818 setTransactionFlags(eTransactionNeeded);
2819 return true;
2820}
2821
2822bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2823 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2824 mDrawingState.sequence++;
2825 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2826 mDrawingState.modified = true;
2827 setTransactionFlags(eTransactionNeeded);
2828 return true;
2829}
2830
2831bool Layer::setBufferCrop(const Rect& bufferCrop) {
2832 if (mDrawingState.bufferCrop == bufferCrop) return false;
2833
2834 mDrawingState.sequence++;
2835 mDrawingState.bufferCrop = bufferCrop;
2836
2837 mDrawingState.modified = true;
2838 setTransactionFlags(eTransactionNeeded);
2839 return true;
2840}
2841
2842bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2843 if (mDrawingState.destinationFrame == destinationFrame) return false;
2844
2845 mDrawingState.sequence++;
2846 mDrawingState.destinationFrame = destinationFrame;
2847
2848 mDrawingState.modified = true;
2849 setTransactionFlags(eTransactionNeeded);
2850 return true;
2851}
2852
2853// Translate destination frame into scale and position. If a destination frame is not set, use the
2854// provided scale and position
2855bool Layer::updateGeometry() {
2856 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2857 mDrawingState.destinationFrame.isEmpty()) {
2858 // If destination frame is not set, use the requested transform set via
2859 // Layer::setPosition and Layer::setMatrix.
2860 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2861 }
2862
2863 Rect destRect = mDrawingState.destinationFrame;
2864 int32_t destW = destRect.width();
2865 int32_t destH = destRect.height();
2866 if (destRect.left < 0) {
2867 destRect.left = 0;
2868 destRect.right = destW;
2869 }
2870 if (destRect.top < 0) {
2871 destRect.top = 0;
2872 destRect.bottom = destH;
2873 }
2874
2875 if (!mDrawingState.buffer) {
2876 ui::Transform t;
2877 t.set(destRect.left, destRect.top);
2878 return assignTransform(&mDrawingState.transform, t);
2879 }
2880
2881 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2882 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2883 // Undo any transformations on the buffer.
2884 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2885 std::swap(bufferWidth, bufferHeight);
2886 }
2887 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
2888 if (mDrawingState.transformToDisplayInverse) {
2889 if (invTransform & ui::Transform::ROT_90) {
2890 std::swap(bufferWidth, bufferHeight);
2891 }
2892 }
2893
2894 float sx = destW / static_cast<float>(bufferWidth);
2895 float sy = destH / static_cast<float>(bufferHeight);
2896 ui::Transform t;
2897 t.set(sx, 0, 0, sy);
2898 t.set(destRect.left, destRect.top);
2899 return assignTransform(&mDrawingState.transform, t);
2900}
2901
2902bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
2903 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
2904 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
2905 return false;
2906 }
2907
2908 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
2909
2910 mDrawingState.sequence++;
2911 mDrawingState.modified = true;
2912 setTransactionFlags(eTransactionNeeded);
2913
2914 return true;
2915}
2916
2917bool Layer::setPosition(float x, float y) {
2918 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
2919 return false;
2920 }
2921
2922 mRequestedTransform.set(x, y);
2923
2924 mDrawingState.sequence++;
2925 mDrawingState.modified = true;
2926 setTransactionFlags(eTransactionNeeded);
2927
2928 return true;
2929}
2930
2931bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
2932 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
2933 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07002934 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00002935 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00002936 if (!buffer) {
2937 return false;
2938 }
2939
2940 const bool frameNumberChanged =
2941 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
2942 const uint64_t frameNumber =
2943 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00002944 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002945
2946 if (mDrawingState.buffer) {
2947 mReleasePreviousBuffer = true;
2948 if (!mBufferInfo.mBuffer ||
2949 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
2950 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
2951 // If mDrawingState has a buffer, and we are about to update again
2952 // before swapping to drawing state, then the first buffer will be
2953 // dropped and we should decrement the pending buffer count and
2954 // call any release buffer callbacks if set.
2955 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
2956 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
2957 mDrawingState.acquireFence,
2958 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
2959 mOwnerUid));
2960 decrementPendingBufferCount();
2961 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
2962 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
2963 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
2964 mDrawingState.bufferSurfaceFrameTX.reset();
2965 }
2966 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
2967 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
2968 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
2969 mLastClientCompositionFence,
2970 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
2971 mOwnerUid));
2972 mLastClientCompositionFence = nullptr;
2973 }
2974 }
2975
2976 mDrawingState.frameNumber = frameNumber;
2977 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
2978 mDrawingState.buffer = std::move(buffer);
2979 mDrawingState.clientCacheId = bufferData.cachedBuffer;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002980 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
2981 ? bufferData.acquireFence
2982 : Fence::NO_FENCE;
2983 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
2984 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
2985 // We latched this buffer unsiganled, so we need to pass the acquire fence
2986 // on the callback instead of just the acquire time, since it's unknown at
2987 // this point.
2988 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
2989 } else {
2990 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
2991 }
2992
2993 mDrawingState.modified = true;
2994 setTransactionFlags(eTransactionNeeded);
2995
2996 const int32_t layerId = getSequence();
2997 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
2998 mOwnerUid, postTime, getGameMode());
2999 mDrawingState.desiredPresentTime = desiredPresentTime;
3000 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3001
3002 const nsecs_t presentTime = [&] {
3003 if (!isAutoTimestamp) return desiredPresentTime;
3004
3005 const auto prediction =
3006 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
3007 if (prediction.has_value()) return prediction->presentTime;
3008
3009 return static_cast<nsecs_t>(0);
3010 }();
3011
3012 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
3013 mFlinger->mScheduler->recordLayerHistory(this, presentTime, LayerUpdateType::Buffer);
3014
3015 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3016
3017 if (dequeueTime && *dequeueTime != 0) {
3018 const uint64_t bufferId = mDrawingState.buffer->getId();
3019 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3020 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3021 FrameTracer::FrameEvent::DEQUEUE);
3022 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3023 FrameTracer::FrameEvent::QUEUE);
3024 }
3025
3026 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3027 return true;
3028}
3029
3030bool Layer::setDataspace(ui::Dataspace dataspace) {
3031 mDrawingState.dataspaceRequested = true;
3032 if (mDrawingState.dataspace == dataspace) return false;
3033 mDrawingState.dataspace = dataspace;
3034 mDrawingState.modified = true;
3035 setTransactionFlags(eTransactionNeeded);
3036 return true;
3037}
3038
3039bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3040 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3041 mDrawingState.hdrMetadata = hdrMetadata;
3042 mDrawingState.modified = true;
3043 setTransactionFlags(eTransactionNeeded);
3044 return true;
3045}
3046
3047bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
3048 mDrawingState.surfaceDamageRegion = surfaceDamage;
3049 mDrawingState.modified = true;
3050 setTransactionFlags(eTransactionNeeded);
3051 return true;
3052}
3053
3054bool Layer::setApi(int32_t api) {
3055 if (mDrawingState.api == api) return false;
3056 mDrawingState.api = api;
3057 mDrawingState.modified = true;
3058 setTransactionFlags(eTransactionNeeded);
3059 return true;
3060}
3061
3062bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3063 if (mDrawingState.sidebandStream == sidebandStream) return false;
3064
3065 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3066 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3067 } else if (sidebandStream != nullptr) {
3068 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3069 }
3070
3071 mDrawingState.sidebandStream = sidebandStream;
3072 mDrawingState.modified = true;
3073 setTransactionFlags(eTransactionNeeded);
3074 if (!mSidebandStreamChanged.exchange(true)) {
3075 // mSidebandStreamChanged was false
3076 mFlinger->onLayerUpdate();
3077 }
3078 return true;
3079}
3080
3081bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles) {
3082 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3083 if (handles.empty()) {
3084 mReleasePreviousBuffer = false;
3085 return false;
3086 }
3087
3088 const bool willPresent = willPresentCurrentTransaction();
3089
3090 for (const auto& handle : handles) {
3091 // If this transaction set a buffer on this layer, release its previous buffer
3092 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3093
3094 // If this layer will be presented in this frame
3095 if (willPresent) {
3096 // If this transaction set an acquire fence on this layer, set its acquire time
3097 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3098 handle->frameNumber = mDrawingState.frameNumber;
3099
3100 // Store so latched time and release fence can be set
3101 mDrawingState.callbackHandles.push_back(handle);
3102
3103 } else { // If this layer will NOT need to be relatched and presented this frame
3104 // Notify the transaction completed thread this handle is done
3105 mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
3106 }
3107 }
3108
3109 mReleasePreviousBuffer = false;
3110 mCallbackHandleAcquireTimeOrFence = -1;
3111
3112 return willPresent;
3113}
3114
3115Rect Layer::getBufferSize(const State& /*s*/) const {
3116 // for buffer state layers we use the display frame size as the buffer size.
3117
3118 if (mBufferInfo.mBuffer == nullptr) {
3119 return Rect::INVALID_RECT;
3120 }
3121
3122 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3123 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3124
3125 // Undo any transformations on the buffer and return the result.
3126 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3127 std::swap(bufWidth, bufHeight);
3128 }
3129
3130 if (getTransformToDisplayInverse()) {
3131 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3132 if (invTransform & ui::Transform::ROT_90) {
3133 std::swap(bufWidth, bufHeight);
3134 }
3135 }
3136
3137 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3138}
3139
3140FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3141 if (mBufferInfo.mBuffer == nullptr) {
3142 return parentBounds;
3143 }
3144
3145 return getBufferSize(getDrawingState()).toFloatRect();
3146}
3147
3148bool Layer::fenceHasSignaled() const {
3149 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3150 return true;
3151 }
3152
3153 const bool fenceSignaled =
3154 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3155 if (!fenceSignaled) {
3156 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3157 TimeStats::LatchSkipReason::LateAcquire);
3158 }
3159
3160 return fenceSignaled;
3161}
3162
Vishnu Naire14c6b32022-08-06 04:20:15 +00003163bool Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003164 for (const auto& handle : mDrawingState.callbackHandles) {
3165 handle->refreshStartTime = refreshStartTime;
3166 }
3167 return hasReadyFrame();
3168}
3169
3170void Layer::setAutoRefresh(bool autoRefresh) {
3171 mDrawingState.autoRefresh = autoRefresh;
3172}
3173
3174bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3175 // 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 +00003176 auto* snapshot = editLayerSnapshot();
3177 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003178
3179 if (mSidebandStreamChanged.exchange(false)) {
3180 const State& s(getDrawingState());
3181 // mSidebandStreamChanged was true
3182 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003183 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003184 if (mSidebandStream != nullptr) {
3185 setTransactionFlags(eTransactionNeeded);
3186 mFlinger->setTransactionFlags(eTraversalNeeded);
3187 }
3188 recomputeVisibleRegions = true;
3189
3190 return true;
3191 }
3192 return false;
3193}
3194
3195bool Layer::hasFrameUpdate() const {
3196 const State& c(getDrawingState());
3197 return (mDrawingStateModified || mDrawingState.modified) &&
3198 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3199}
3200
3201void Layer::updateTexImage(nsecs_t latchTime) {
3202 const State& s(getDrawingState());
3203
3204 if (!s.buffer) {
3205 if (s.bgColorLayer) {
3206 for (auto& handle : mDrawingState.callbackHandles) {
3207 handle->latchTime = latchTime;
3208 }
3209 }
3210 return;
3211 }
3212
3213 for (auto& handle : mDrawingState.callbackHandles) {
3214 if (handle->frameNumber == mDrawingState.frameNumber) {
3215 handle->latchTime = latchTime;
3216 }
3217 }
3218
3219 const int32_t layerId = getSequence();
3220 const uint64_t bufferId = mDrawingState.buffer->getId();
3221 const uint64_t frameNumber = mDrawingState.frameNumber;
3222 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3223 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3224 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3225
3226 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3227 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3228 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3229 FrameTracer::FrameEvent::LATCH);
3230
3231 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3232 if (bufferSurfaceFrame != nullptr &&
3233 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3234 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3235 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3236 // are processing the next state.
3237 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3238 mDrawingState.acquireFenceTime->getSignalTime(),
3239 latchTime);
3240 mDrawingState.bufferSurfaceFrameTX.reset();
3241 }
3242
3243 std::deque<sp<CallbackHandle>> remainingHandles;
3244 mFlinger->getTransactionCallbackInvoker()
3245 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3246 mDrawingState.callbackHandles = remainingHandles;
3247
3248 mDrawingStateModified = false;
3249}
3250
3251void Layer::gatherBufferInfo() {
3252 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3253 decrementPendingBufferCount();
3254 }
3255
3256 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3257 mBufferInfo.mBuffer = mDrawingState.buffer;
3258 mBufferInfo.mFence = mDrawingState.acquireFence;
3259 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3260 mBufferInfo.mPixelFormat =
3261 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3262 mBufferInfo.mFrameLatencyNeeded = true;
3263 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3264 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3265 mBufferInfo.mFence = mDrawingState.acquireFence;
3266 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3267 auto lastDataspace = mBufferInfo.mDataspace;
3268 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3269 if (lastDataspace != mBufferInfo.mDataspace) {
3270 mFlinger->mSomeDataspaceChanged = true;
3271 }
3272 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3273 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3274 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3275 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3276 mBufferInfo.mApi = mDrawingState.api;
3277 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003278}
3279
3280Rect Layer::computeBufferCrop(const State& s) {
3281 if (s.buffer && !s.bufferCrop.isEmpty()) {
3282 Rect bufferCrop;
3283 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3284 return bufferCrop;
3285 } else if (s.buffer) {
3286 return s.buffer->getBounds();
3287 } else {
3288 return s.bufferCrop;
3289 }
3290}
3291
3292sp<Layer> Layer::createClone() {
3293 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3294 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003295 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003296 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3297 return layer;
3298}
3299
3300bool Layer::bufferNeedsFiltering() const {
3301 const State& s(getDrawingState());
3302 if (!s.buffer) {
3303 return false;
3304 }
3305
3306 int32_t bufferWidth = static_cast<int32_t>(s.buffer->getWidth());
3307 int32_t bufferHeight = static_cast<int32_t>(s.buffer->getHeight());
3308
3309 // Undo any transformations on the buffer and return the result.
3310 if (s.bufferTransform & ui::Transform::ROT_90) {
3311 std::swap(bufferWidth, bufferHeight);
3312 }
3313
3314 if (s.transformToDisplayInverse) {
3315 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3316 if (invTransform & ui::Transform::ROT_90) {
3317 std::swap(bufferWidth, bufferHeight);
3318 }
3319 }
3320
3321 const Rect layerSize{getBounds()};
3322 int32_t layerWidth = layerSize.getWidth();
3323 int32_t layerHeight = layerSize.getHeight();
3324
3325 // Align the layer orientation with the buffer before comparism
3326 if (mTransformHint & ui::Transform::ROT_90) {
3327 std::swap(layerWidth, layerHeight);
3328 }
3329
3330 return layerWidth != bufferWidth || layerHeight != bufferHeight;
3331}
3332
3333void Layer::decrementPendingBufferCount() {
3334 int32_t pendingBuffers = --mPendingBufferTransactions;
3335 tracePendingBufferCount(pendingBuffers);
3336}
3337
3338void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3339 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3340}
3341
3342/*
3343 * We don't want to send the layer's transform to input, but rather the
3344 * parent's transform. This is because Layer's transform is
3345 * information about how the buffer is placed on screen. The parent's
3346 * transform makes more sense to send since it's information about how the
3347 * layer is placed on screen. This transform is used by input to determine
3348 * how to go from screen space back to window space.
3349 */
3350ui::Transform Layer::getInputTransform() const {
3351 if (!hasBufferOrSidebandStream()) {
3352 return getTransform();
3353 }
3354 sp<Layer> parent = mDrawingParent.promote();
3355 if (parent == nullptr) {
3356 return ui::Transform();
3357 }
3358
3359 return parent->getTransform();
3360}
3361
3362/**
3363 * Similar to getInputTransform, we need to update the bounds to include the transform.
3364 * This is because bounds don't include the buffer transform, where the input assumes
3365 * that's already included.
3366 */
3367Rect Layer::getInputBounds() const {
3368 if (!hasBufferOrSidebandStream()) {
3369 return getCroppedBufferSize(getDrawingState());
3370 }
3371
3372 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
3373 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
3374 return bufferBounds;
3375 }
3376 return mDrawingState.transform.transform(bufferBounds);
3377}
3378
3379bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3380 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3381
3382 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3383 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3384 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3385 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3386 layer_state_t::eReparent;
3387
3388 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3389 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3390 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3391 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3392 layer_state_t::eInputInfoChanged;
3393
3394 if ((s.what & requiredFlags) != requiredFlags) {
3395 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3396 (s.what | requiredFlags) & ~s.what);
3397 return false;
3398 }
3399
3400 if (s.what & deniedFlags) {
3401 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3402 return false;
3403 }
3404
3405 if (s.what & allowedFlags) {
3406 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3407 }
3408
3409 if (s.what & layer_state_t::ePositionChanged) {
3410 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3411 ALOGV("%s: false [ePositionChanged changed]", __func__);
3412 return false;
3413 }
3414 }
3415
3416 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003417 if (mDrawingState.color.a != s.color.a) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003418 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3419 return false;
3420 }
3421 }
3422
3423 if (s.what & layer_state_t::eColorTransformChanged) {
3424 if (mDrawingState.colorTransform != s.colorTransform) {
3425 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3426 return false;
3427 }
3428 }
3429
3430 if (s.what & layer_state_t::eBackgroundColorChanged) {
3431 if (mDrawingState.bgColorLayer || s.bgColorAlpha != 0) {
3432 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3433 return false;
3434 }
3435 }
3436
3437 if (s.what & layer_state_t::eMatrixChanged) {
3438 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3439 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3440 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3441 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3442 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3443 return false;
3444 }
3445 }
3446
3447 if (s.what & layer_state_t::eCornerRadiusChanged) {
3448 if (mDrawingState.cornerRadius != s.cornerRadius) {
3449 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3450 return false;
3451 }
3452 }
3453
3454 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3455 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3456 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3457 return false;
3458 }
3459 }
3460
Vishnu Nairbbceb462022-10-10 04:52:13 +00003461 if (s.what & layer_state_t::eBufferTransformChanged) {
3462 if (mDrawingState.bufferTransform != s.bufferTransform) {
3463 ALOGV("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003464 return false;
3465 }
3466 }
3467
3468 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3469 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3470 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3471 return false;
3472 }
3473 }
3474
3475 if (s.what & layer_state_t::eCropChanged) {
3476 if (mDrawingState.crop != s.crop) {
3477 ALOGV("%s: false [eCropChanged changed]", __func__);
3478 return false;
3479 }
3480 }
3481
3482 if (s.what & layer_state_t::eDataspaceChanged) {
3483 if (mDrawingState.dataspace != s.dataspace) {
3484 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3485 return false;
3486 }
3487 }
3488
3489 if (s.what & layer_state_t::eHdrMetadataChanged) {
3490 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3491 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3492 return false;
3493 }
3494 }
3495
3496 if (s.what & layer_state_t::eSidebandStreamChanged) {
3497 if (mDrawingState.sidebandStream != s.sidebandStream) {
3498 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3499 return false;
3500 }
3501 }
3502
3503 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3504 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3505 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3506 return false;
3507 }
3508 }
3509
3510 if (s.what & layer_state_t::eShadowRadiusChanged) {
3511 if (mDrawingState.shadowRadius != s.shadowRadius) {
3512 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3513 return false;
3514 }
3515 }
3516
3517 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3518 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3519 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3520 return false;
3521 }
3522 }
3523
3524 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3525 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3526 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3527 return false;
3528 }
3529 }
3530
3531 if (s.what & layer_state_t::eStretchChanged) {
3532 StretchEffect temp = s.stretchEffect;
3533 temp.sanitize();
3534 if (mDrawingState.stretchEffect != temp) {
3535 ALOGV("%s: false [eStretchChanged changed]", __func__);
3536 return false;
3537 }
3538 }
3539
3540 if (s.what & layer_state_t::eBufferCropChanged) {
3541 if (mDrawingState.bufferCrop != s.bufferCrop) {
3542 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3543 return false;
3544 }
3545 }
3546
3547 if (s.what & layer_state_t::eDestinationFrameChanged) {
3548 if (mDrawingState.destinationFrame != s.destinationFrame) {
3549 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3550 return false;
3551 }
3552 }
3553
3554 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3555 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3556 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3557 return false;
3558 }
3559 }
3560
3561 ALOGV("%s: true", __func__);
3562 return true;
3563}
3564
3565bool Layer::isHdrY410() const {
3566 // pixel format is HDR Y410 masquerading as RGBA_1010102
3567 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3568 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3569 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3570}
3571
Vishnu Naire14c6b32022-08-06 04:20:15 +00003572sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003573 // There's no need to get a CE Layer if the layer isn't going to draw anything.
Vishnu Naire14c6b32022-08-06 04:20:15 +00003574 return hasSomethingToDraw() ? mLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003575}
3576
Vishnu Naire14c6b32022-08-06 04:20:15 +00003577const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003578 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003579}
3580
Vishnu Naire14c6b32022-08-06 04:20:15 +00003581LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003582 return mSnapshot.get();
3583}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003584
Patrick Williamsbb25f802022-08-30 23:02:34 +00003585const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003586 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003587}
3588
Patrick Williams7584c6a2022-10-29 02:10:58 +00003589sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
3590 auto result = mFlinger->getFactory().createLayerFE(mLayerFE->getDebugName());
3591 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3592 return result;
3593}
3594
Patrick Williamsbb25f802022-08-30 23:02:34 +00003595void Layer::useSurfaceDamage() {
3596 if (mFlinger->mForceFullDamage) {
3597 surfaceDamageRegion = Region::INVALID_REGION;
3598 } else {
3599 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3600 }
3601}
3602
3603void Layer::useEmptyDamage() {
3604 surfaceDamageRegion.clear();
3605}
3606
3607bool Layer::isOpaque(const Layer::State& s) const {
3608 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3609 // layer's opaque flag.
3610 if (!hasSomethingToDraw()) {
3611 return false;
3612 }
3613
3614 // if the layer has the opaque flag, then we're always opaque
3615 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3616 return true;
3617 }
3618
3619 // If the buffer has no alpha channel, then we are opaque
3620 if (hasBufferOrSidebandStream() && isOpaqueFormat(getPixelFormat())) {
3621 return true;
3622 }
3623
3624 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3625 return fillsColor() && getAlpha() == 1.0_hf;
3626}
3627
3628bool Layer::canReceiveInput() const {
3629 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3630}
3631
3632bool Layer::isVisible() const {
3633 if (!hasSomethingToDraw()) {
3634 return false;
3635 }
3636
3637 if (isHiddenByPolicy()) {
3638 return false;
3639 }
3640
3641 return getAlpha() > 0.0f || hasBlur();
3642}
3643
3644void Layer::onPostComposition(const DisplayDevice* display,
3645 const std::shared_ptr<FenceTime>& glDoneFence,
3646 const std::shared_ptr<FenceTime>& presentFence,
3647 const CompositorTiming& compositorTiming) {
3648 // mFrameLatencyNeeded is true when a new frame was latched for the
3649 // composition.
3650 if (!mBufferInfo.mFrameLatencyNeeded) return;
3651
3652 for (const auto& handle : mDrawingState.callbackHandles) {
3653 handle->gpuCompositionDoneFence = glDoneFence;
3654 handle->compositorTiming = compositorTiming;
3655 }
3656
3657 // Update mFrameTracker.
3658 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3659 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3660
3661 const int32_t layerId = getSequence();
3662 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3663
3664 const auto outputLayer = findOutputLayerForDisplay(display);
3665 if (outputLayer && outputLayer->requiresClientComposition()) {
3666 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3667 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3668 clientCompositionTimestamp,
3669 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3670 // Update the SurfaceFrames in the drawing state
3671 if (mDrawingState.bufferSurfaceFrameTX) {
3672 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3673 }
3674 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3675 surfaceFrame->setGpuComposition();
3676 }
3677 }
3678
3679 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3680 if (frameReadyFence->isValid()) {
3681 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3682 } else {
3683 // There was no fence for this frame, so assume that it was ready
3684 // to be presented at the desired present time.
3685 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3686 }
3687
3688 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08003689 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003690 const std::optional<Fps> renderRate =
3691 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3692
3693 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3694 const auto gameMode = getGameMode();
3695
3696 if (presentFence->isValid()) {
3697 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3698 refreshRate, renderRate, vote, gameMode);
3699 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3700 presentFence,
3701 FrameTracer::FrameEvent::PRESENT_FENCE);
3702 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3703 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3704 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003705 // The HWC doesn't support present fences, so use the present timestamp instead.
3706 const nsecs_t presentTimestamp =
3707 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3708
3709 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3710 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3711 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3712
Patrick Williamsbb25f802022-08-30 23:02:34 +00003713 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3714 refreshRate, renderRate, vote, gameMode);
3715 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3716 mCurrentFrameNumber, actualPresentTime,
3717 FrameTracer::FrameEvent::PRESENT_FENCE);
3718 mFrameTracker.setActualPresentTime(actualPresentTime);
3719 }
3720 }
3721
3722 mFrameTracker.advanceFrame();
3723 mBufferInfo.mFrameLatencyNeeded = false;
3724}
3725
3726bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
3727 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3728 getDrawingState().frameNumber);
3729
3730 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3731
3732 if (refreshRequired) {
3733 return refreshRequired;
3734 }
3735
3736 // If the head buffer's acquire fence hasn't signaled yet, return and
3737 // try again later
3738 if (!fenceHasSignaled()) {
3739 ATRACE_NAME("!fenceHasSignaled()");
3740 mFlinger->onLayerUpdate();
3741 return false;
3742 }
3743
3744 updateTexImage(latchTime);
3745 if (mDrawingState.buffer == nullptr) {
3746 return false;
3747 }
3748
3749 // Capture the old state of the layer for comparisons later
3750 BufferInfo oldBufferInfo = mBufferInfo;
3751 const bool oldOpacity = isOpaque(mDrawingState);
3752 mPreviousFrameNumber = mCurrentFrameNumber;
3753 mCurrentFrameNumber = mDrawingState.frameNumber;
3754 gatherBufferInfo();
3755
3756 if (oldBufferInfo.mBuffer == nullptr) {
3757 // the first time we receive a buffer, we need to trigger a
3758 // geometry invalidation.
3759 recomputeVisibleRegions = true;
3760 }
3761
3762 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3763 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3764 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3765 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3766 recomputeVisibleRegions = true;
3767 }
3768
3769 if (oldBufferInfo.mBuffer != nullptr) {
3770 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3771 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3772 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3773 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3774 recomputeVisibleRegions = true;
3775 }
3776 }
3777
3778 if (oldOpacity != isOpaque(mDrawingState)) {
3779 recomputeVisibleRegions = true;
3780 }
3781
3782 return true;
3783}
3784
3785bool Layer::hasReadyFrame() const {
3786 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
3787}
3788
3789bool Layer::isProtected() const {
3790 return (mBufferInfo.mBuffer != nullptr) &&
3791 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
3792}
3793
3794// As documented in libhardware header, formats in the range
3795// 0x100 - 0x1FF are specific to the HAL implementation, and
3796// are known to have no alpha channel
3797// TODO: move definition for device-specific range into
3798// hardware.h, instead of using hard-coded values here.
3799#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
3800
3801bool Layer::isOpaqueFormat(PixelFormat format) {
3802 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
3803 return true;
3804 }
3805 switch (format) {
3806 case PIXEL_FORMAT_RGBA_8888:
3807 case PIXEL_FORMAT_BGRA_8888:
3808 case PIXEL_FORMAT_RGBA_FP16:
3809 case PIXEL_FORMAT_RGBA_1010102:
3810 case PIXEL_FORMAT_R_8:
3811 return false;
3812 }
3813 // in all other case, we have no blending (also for unknown formats)
3814 return true;
3815}
3816
3817bool Layer::needsFiltering(const DisplayDevice* display) const {
3818 if (!hasBufferOrSidebandStream()) {
3819 return false;
3820 }
3821 const auto outputLayer = findOutputLayerForDisplay(display);
3822 if (outputLayer == nullptr) {
3823 return false;
3824 }
3825
3826 // We need filtering if the sourceCrop rectangle size does not match the
3827 // displayframe rectangle size (not a 1:1 render)
3828 const auto& compositionState = outputLayer->getState();
3829 const auto displayFrame = compositionState.displayFrame;
3830 const auto sourceCrop = compositionState.sourceCrop;
3831 return sourceCrop.getHeight() != displayFrame.getHeight() ||
3832 sourceCrop.getWidth() != displayFrame.getWidth();
3833}
3834
3835bool Layer::needsFilteringForScreenshots(const DisplayDevice* display,
3836 const ui::Transform& inverseParentTransform) const {
3837 if (!hasBufferOrSidebandStream()) {
3838 return false;
3839 }
3840 const auto outputLayer = findOutputLayerForDisplay(display);
3841 if (outputLayer == nullptr) {
3842 return false;
3843 }
3844
3845 // We need filtering if the sourceCrop rectangle size does not match the
3846 // viewport rectangle size (not a 1:1 render)
3847 const auto& compositionState = outputLayer->getState();
3848 const ui::Transform& displayTransform = display->getTransform();
3849 const ui::Transform inverseTransform = inverseParentTransform * displayTransform.inverse();
3850 // Undo the transformation of the displayFrame so that we're back into
3851 // layer-stack space.
3852 const Rect frame = inverseTransform.transform(compositionState.displayFrame);
3853 const FloatRect sourceCrop = compositionState.sourceCrop;
3854
3855 int32_t frameHeight = frame.getHeight();
3856 int32_t frameWidth = frame.getWidth();
3857 // If the display transform had a rotational component then undo the
3858 // rotation so that the orientation matches the source crop.
3859 if (displayTransform.getOrientation() & ui::Transform::ROT_90) {
3860 std::swap(frameHeight, frameWidth);
3861 }
3862 return sourceCrop.getHeight() != frameHeight || sourceCrop.getWidth() != frameWidth;
3863}
3864
3865void Layer::latchAndReleaseBuffer() {
3866 if (hasReadyFrame()) {
3867 bool ignored = false;
3868 latchBuffer(ignored, systemTime());
3869 }
3870 releasePendingBuffer(systemTime());
3871}
3872
3873PixelFormat Layer::getPixelFormat() const {
3874 return mBufferInfo.mPixelFormat;
3875}
3876
3877bool Layer::getTransformToDisplayInverse() const {
3878 return mBufferInfo.mTransformToDisplayInverse;
3879}
3880
3881Rect Layer::getBufferCrop() const {
3882 // this is the crop rectangle that applies to the buffer
3883 // itself (as opposed to the window)
3884 if (!mBufferInfo.mCrop.isEmpty()) {
3885 // if the buffer crop is defined, we use that
3886 return mBufferInfo.mCrop;
3887 } else if (mBufferInfo.mBuffer != nullptr) {
3888 // otherwise we use the whole buffer
3889 return mBufferInfo.mBuffer->getBounds();
3890 } else {
3891 // if we don't have a buffer yet, we use an empty/invalid crop
3892 return Rect();
3893 }
3894}
3895
3896uint32_t Layer::getBufferTransform() const {
3897 return mBufferInfo.mTransform;
3898}
3899
3900ui::Dataspace Layer::getDataSpace() const {
3901 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
3902}
3903
3904ui::Dataspace Layer::getRequestedDataSpace() const {
3905 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
3906}
3907
3908ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
3909 ui::Dataspace updatedDataspace = dataspace;
3910 // translate legacy dataspaces to modern dataspaces
3911 switch (dataspace) {
3912 case ui::Dataspace::SRGB:
3913 updatedDataspace = ui::Dataspace::V0_SRGB;
3914 break;
3915 case ui::Dataspace::SRGB_LINEAR:
3916 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
3917 break;
3918 case ui::Dataspace::JFIF:
3919 updatedDataspace = ui::Dataspace::V0_JFIF;
3920 break;
3921 case ui::Dataspace::BT601_625:
3922 updatedDataspace = ui::Dataspace::V0_BT601_625;
3923 break;
3924 case ui::Dataspace::BT601_525:
3925 updatedDataspace = ui::Dataspace::V0_BT601_525;
3926 break;
3927 case ui::Dataspace::BT709:
3928 updatedDataspace = ui::Dataspace::V0_BT709;
3929 break;
3930 default:
3931 break;
3932 }
3933
3934 return updatedDataspace;
3935}
3936
3937sp<GraphicBuffer> Layer::getBuffer() const {
3938 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
3939}
3940
Patrick Williamsbb25f802022-08-30 23:02:34 +00003941void Layer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
3942 mTransformHint = getFixedTransformHint();
3943 if (mTransformHint == ui::Transform::ROT_INVALID) {
3944 mTransformHint = displayTransformHint;
3945 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07003946 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003947}
3948
3949const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
3950 return mBufferInfo.mBuffer;
3951}
3952
3953bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003954 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003955 return false;
3956 }
3957
3958 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00003959 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003960 mDrawingState.modified = true;
3961 setTransactionFlags(eTransactionNeeded);
3962 return true;
3963}
3964
3965bool Layer::fillsColor() const {
3966 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
3967 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
3968}
3969
3970bool Layer::hasBlur() const {
3971 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
3972}
3973
Vishnu Nairba354102022-08-01 00:14:18 +00003974void Layer::updateSnapshot(bool updateGeometry) {
3975 if (!getCompositionEngineLayerFE()) {
3976 return;
3977 }
3978
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003979 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00003980 if (updateGeometry) {
3981 prepareBasicGeometryCompositionState();
3982 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003983 snapshot->roundedCorner = getRoundedCornerState();
3984 snapshot->stretchEffect = getStretchEffect();
3985 snapshot->transformedBounds = mScreenBounds;
3986 if (mEffectiveShadowRadius > 0.f) {
3987 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
3988
3989 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
3990 // it if transparent regions are present. This may not be necessary since shadows are
3991 // typically cast by layers without transparent regions.
3992 snapshot->shadowSettings.boundaries = mBounds;
3993
3994 const float casterAlpha = snapshot->alpha;
3995 const bool casterIsOpaque =
3996 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
3997
3998 // If the casting layer is translucent, we need to fill in the shadow underneath the
3999 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4000 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4001 snapshot->shadowSettings.ambientColor *= casterAlpha;
4002 snapshot->shadowSettings.spotColor *= casterAlpha;
4003 }
4004 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004005 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004006 snapshot->contentOpaque = isOpaque(mDrawingState);
4007 snapshot->isHdrY410 = isHdrY410();
4008 snapshot->bufferNeedsFiltering = bufferNeedsFiltering();
4009 sp<Layer> p = mDrawingParent.promote();
4010 if (p != nullptr) {
4011 snapshot->transform = p->getTransform();
4012 } else {
4013 snapshot->transform.reset();
4014 }
4015 snapshot->bufferSize = getBufferSize(mDrawingState);
4016 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004017 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004018 preparePerFrameCompositionState();
4019}
4020
Vishnu Naire14c6b32022-08-06 04:20:15 +00004021void Layer::updateChildrenSnapshots(bool updateGeometry) {
4022 for (const sp<Layer>& child : mDrawingChildren) {
4023 child->updateSnapshot(updateGeometry);
4024 child->updateChildrenSnapshots(updateGeometry);
4025 }
4026}
4027
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004028void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4029 mSnapshot->layerMetadata = parentMetadata;
4030 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4031 for (const sp<Layer>& child : mDrawingChildren) {
4032 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4033 }
4034}
4035
4036void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4037 std::unordered_set<Layer*>& visited) {
4038 if (visited.find(this) != visited.end()) {
4039 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4040 return;
4041 }
4042 visited.insert(this);
4043
4044 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4045
4046 if (mDrawingState.zOrderRelatives.empty()) {
4047 return;
4048 }
4049 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4050 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4051 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4052 sp<Layer> relative = weakRelative.promote();
4053 if (!relative) {
4054 continue;
4055 }
4056 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4057 }
4058}
4059
Patrick Williams377c0142022-10-13 17:33:38 +00004060LayerSnapshotGuard::LayerSnapshotGuard(Layer* layer) : mLayer(layer) {
Patrick Williams4da60852022-11-17 17:19:38 +00004061 if (mLayer) {
4062 mLayer->mLayerFE->mSnapshot = std::move(mLayer->mSnapshot);
4063 }
Patrick Williams377c0142022-10-13 17:33:38 +00004064}
4065
4066LayerSnapshotGuard::~LayerSnapshotGuard() {
4067 if (mLayer) {
4068 mLayer->mSnapshot = std::move(mLayer->mLayerFE->mSnapshot);
4069 }
4070}
4071
4072LayerSnapshotGuard::LayerSnapshotGuard(LayerSnapshotGuard&& other) : mLayer(other.mLayer) {
4073 other.mLayer = nullptr;
4074}
4075
4076LayerSnapshotGuard& LayerSnapshotGuard::operator=(LayerSnapshotGuard&& other) {
4077 mLayer = other.mLayer;
4078 other.mLayer = nullptr;
4079 return *this;
4080}
4081
Chavi Weingarten076acac2023-01-19 17:20:43 +00004082void Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
4083 TrustedPresentationListener const& listener) {
4084 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4085 mTrustedPresentationListener = listener;
4086 mTrustedPresentationThresholds = thresholds;
4087 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4088 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4089 mFlinger->mNumTrustedPresentationListeners++;
4090 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4091 mFlinger->mNumTrustedPresentationListeners--;
4092 }
4093}
4094
Mathias Agopian13127d82013-03-05 17:47:11 -08004095// ---------------------------------------------------------------------------
4096
Marin Shalamanov46084422020-10-13 12:33:42 +02004097std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004098 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4099 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004100}
4101
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004102} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004103
4104#if defined(__gl_h_)
4105#error "don't include gl/gl.h in this file"
4106#endif
4107
4108#if defined(__gl2_h_)
4109#error "don't include gl2/gl2.h in this file"
4110#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004111
4112// TODO(b/129481165): remove the #pragma below and fix conversion issues
4113#pragma clang diagnostic pop // ignored "-Wconversion"