blob: 89ec296da600650f98030d1c9f9ada08adf6de13 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Dan Stoza9e56aa02015-11-02 13:00:03 -080021//#define LOG_NDEBUG 0
22#undef LOG_TAG
23#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080024#define ATRACE_TAG ATRACE_TAG_GRAPHICS
25
Alec Mourie60041e2019-06-14 18:59:51 -070026#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080027
[1;3C2b9fc252021-02-04 16:16:50 -080028#include <android-base/properties.h>
Yiwei Zhang5434a782018-12-05 18:06:32 -080029#include <android-base/stringprintf.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080030#include <android/native_window.h>
Vishnu Nair0f085c62019-08-30 08:49:12 -070031#include <binder/IPCThreadState.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000032#include <compositionengine/CompositionEngine.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080033#include <compositionengine/Display.h>
Lloyd Piquea83776c2019-01-29 18:42:32 -080034#include <compositionengine/LayerFECompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080035#include <compositionengine/OutputLayer.h>
36#include <compositionengine/impl/OutputLayerCompositionState.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070037#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070038#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070039#include <cutils/properties.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070040#include <ftl/enum.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080041#include <ftl/fake_guard.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080042#include <gui/BufferItem.h>
43#include <gui/LayerDebugInfo.h>
44#include <gui/Surface.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000045#include <gui/TraceUtils.h>
Alec Mourie60041e2019-06-14 18:59:51 -070046#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070047#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070049#include <stdint.h>
50#include <stdlib.h>
51#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000052#include <system/graphics-base-v1.0.h>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070053#include <ui/DataspaceUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080054#include <ui/DebugUtils.h>
55#include <ui/GraphicBuffer.h>
56#include <ui/PixelFormat.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#include <utils/Errors.h>
58#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080059#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080061#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Alec Mourie60041e2019-06-14 18:59:51 -070063#include <algorithm>
64#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070065#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070066#include <sstream>
67
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070068#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080069#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070070#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070071#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +000072#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000073#include "FrontEnd/LayerHandle.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080074#include "LayerProtoHelper.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080076#include "TimeStats/TimeStats.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070077#include "TunnelModeEnabledReporter.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070078
David Sodman41fdfc92017-11-06 16:09:56 -080079#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000080#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082namespace android {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010083namespace {
84constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000085
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000086const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000087
Patrick Williamsbb25f802022-08-30 23:02:34 +000088bool assignTransform(ui::Transform* dst, ui::Transform& from) {
89 if (*dst == from) {
90 return false;
91 }
92 *dst = from;
93 return true;
94}
95
96TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
97 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
98 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
99 const auto frameRateCompatibility = [frameRate] {
100 switch (frameRate.type) {
101 case Layer::FrameRateCompatibility::Default:
102 return FrameRateCompatibility::Default;
103 case Layer::FrameRateCompatibility::ExactOrMultiple:
104 return FrameRateCompatibility::ExactOrMultiple;
105 default:
106 return FrameRateCompatibility::Undefined;
107 }
108 }();
109
110 const auto seamlessness = [frameRate] {
111 switch (frameRate.seamlessness) {
112 case scheduler::Seamlessness::OnlySeamless:
113 return Seamlessness::ShouldBeSeamless;
114 case scheduler::Seamlessness::SeamedAndSeamless:
115 return Seamlessness::NotRequired;
116 default:
117 return Seamlessness::Undefined;
118 }
119 }();
120
121 return TimeStats::SetFrameRateVote{.frameRate = frameRate.rate.getValue(),
122 .frameRateCompatibility = frameRateCompatibility,
123 .seamlessness = seamlessness};
124}
125
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100126} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700128using namespace ftl::flag_operators;
129
Yiwei Zhang5434a782018-12-05 18:06:32 -0800130using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000131using frontend::LayerSnapshot;
132using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800133using gui::GameMode;
134using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500135using gui::WindowInfo;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800136
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700137using PresentState = frametimeline::SurfaceFrame::PresentState;
138
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700139Layer::Layer(const LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000140 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700141 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000142 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700143 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800144 mWindowType(static_cast<WindowInfo::Type>(
145 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000146 mLayerCreationFlags(args.flags),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000147 mBorderEnabled(false),
148 mTextureName(args.textureName),
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000149 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000150 ALOGV("Creating Layer %s", getDebugName());
151
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700152 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700153 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
154 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
155 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700156 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
157 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700158 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700159 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700160 mDrawingState.z = 0;
161 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700162 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700163 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700164 mDrawingState.transform.set(0, 0);
165 mDrawingState.frameNumber = 0;
166 mDrawingState.bufferTransform = 0;
167 mDrawingState.transformToDisplayInverse = false;
168 mDrawingState.crop.makeInvalid();
169 mDrawingState.acquireFence = sp<Fence>::make(-1);
170 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
171 mDrawingState.dataspace = ui::Dataspace::UNKNOWN;
Vishnu Nairbc4ee5c2022-08-16 03:19:37 +0000172 mDrawingState.dataspaceRequested = false;
Robert Carr6a160312021-05-17 12:08:20 -0700173 mDrawingState.hdrMetadata.validTypes = 0;
174 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
175 mDrawingState.cornerRadius = 0.0f;
176 mDrawingState.backgroundBlurRadius = 0;
177 mDrawingState.api = -1;
178 mDrawingState.hasColorTransform = false;
179 mDrawingState.colorSpaceAgnostic = false;
180 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
181 mDrawingState.metadata = args.metadata;
182 mDrawingState.shadowRadius = 0.f;
183 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
184 mDrawingState.frameTimelineInfo = {};
185 mDrawingState.postTime = -1;
186 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000187 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700188 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700189 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000190 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700191
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700192 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
193 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700194 mDrawingState.color.r = -1.0_hf;
195 mDrawingState.color.g = -1.0_hf;
196 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700197 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700198
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500199 mFrameTracker.setDisplayRefreshPeriod(
200 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700201
Vishnu Naircb8be502022-10-12 19:03:23 +0000202 mOwnerUid = args.ownerUid;
203 mOwnerPid = args.ownerPid;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000204
205 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
206 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
207 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
208 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000209
210 mSnapshot->sequence = sequence;
211 mSnapshot->name = getDebugName();
212 mSnapshot->textureName = mTextureName;
213 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000214 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800215}
216
217void Layer::onFirstRef() {
218 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700219}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700220
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700221Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000222 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
223 "Layer destructor called off the main thread.");
224
Patrick Williamsbb25f802022-08-30 23:02:34 +0000225 // The original layer and the clone layer share the same texture and buffer. Therefore, only
226 // one of the layers, in this case the original layer, needs to handle the deletion. The
227 // original layer and the clone should be removed at the same time so there shouldn't be any
228 // issue with the clone layer trying to use the texture.
229 if (mBufferInfo.mBuffer != nullptr) {
230 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
231 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800232 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000233 }
234 if (!isClone()) {
235 // The original layer and the clone layer share the same texture. Therefore, only one of
236 // the layers, in this case the original layer, needs to handle the deletion. The original
237 // layer and the clone should be removed at the same time so there shouldn't be any issue
238 // with the clone layer trying to use the deleted texture.
239 mFlinger->deleteTextureAsync(mTextureName);
240 }
241 const int32_t layerId = getSequence();
242 mFlinger->mTimeStats->onDestroy(layerId);
243 mFlinger->mFrameTracer->onDestroy(layerId);
244
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000245 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700246 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700247
248 if (mDrawingState.sidebandStream != nullptr) {
249 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
250 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700251 if (mHadClonedChild) {
252 mFlinger->mNumClones--;
253 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000254 if (hasTrustedPresentationListener()) {
255 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000256 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000257 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700258}
259
Mathias Agopian13127d82013-03-05 17:47:11 -0800260// ---------------------------------------------------------------------------
261// callbacks
262// ---------------------------------------------------------------------------
263
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700264void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700265 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700266 return;
267 }
Robert Carr2e102c92018-10-23 12:11:15 -0700268
Robert Carr6a160312021-05-17 12:08:20 -0700269 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700270 if (strongRelative == nullptr) {
271 setZOrderRelativeOf(nullptr);
272 return;
273 }
274
275 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700276 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700277 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800278 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700279 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700280}
281
282void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700283 if (!mRemovedFromDrawingState) {
284 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700285 mFlinger->mScheduler->deregisterLayer(this);
286 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000287 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000288
Ady Abrahamd11bade2022-08-01 16:18:03 -0700289 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700290}
Chia-I Wu38512252017-05-17 14:36:16 -0700291
chaviw68d4dab2020-06-08 15:07:32 -0700292sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000293 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700294 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700295 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700296 }
297 return parent->getRootLayer();
298}
299
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700300void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700301 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
302 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700303 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700304
305 traverse(LayerVector::StateSet::Current, [&](Layer* layer) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700306 layer->removeFromCurrentState();
307 layer->removeRelativeZ(layersInTree);
chaviw68d4dab2020-06-08 15:07:32 -0700308 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700309}
310
chaviw61626f22018-11-15 16:26:27 -0800311void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700312 if (mRemovedFromDrawingState) {
313 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700314 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700315 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700316 }
chaviw61626f22018-11-15 16:26:27 -0800317
318 for (const auto& child : mCurrentChildren) {
319 child->addToCurrentState();
320 }
321}
322
Mathias Agopian13127d82013-03-05 17:47:11 -0800323// ---------------------------------------------------------------------------
324// set-up
325// ---------------------------------------------------------------------------
326
chaviw13fdc492017-06-27 12:40:18 -0700327bool Layer::getPremultipledAlpha() const {
328 return mPremultipliedAlpha;
329}
330
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700331sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800332 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700333 if (mGetHandleCalled) {
334 ALOGE("Get handle called twice" );
335 return nullptr;
336 }
337 mGetHandleCalled = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000338 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800339}
340
341// ---------------------------------------------------------------------------
342// h/w composer set-up
343// ---------------------------------------------------------------------------
344
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700345static Rect reduce(const Rect& win, const Region& exclude) {
346 if (CC_LIKELY(exclude.isEmpty())) {
347 return win;
348 }
349 if (exclude.isRect()) {
350 return win.reduce(exclude.getBounds());
351 }
352 return Region(win).subtract(exclude).getBounds();
353}
354
Dan Stoza80d61162017-12-20 15:57:52 -0800355static FloatRect reduce(const FloatRect& win, const Region& exclude) {
356 if (CC_LIKELY(exclude.isEmpty())) {
357 return win;
358 }
359 // Convert through Rect (by rounding) for lack of FloatRegion
360 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
361}
362
Vishnu Nair4351ad52019-02-11 14:13:02 -0800363Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800364 if (!reduceTransparentRegion) {
365 return Rect{mScreenBounds};
366 }
367
368 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800369 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800370 // Transform to screen space.
371 bounds = t.transform(bounds);
372 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700373}
374
Vishnu Nair4351ad52019-02-11 14:13:02 -0800375FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000376 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800377 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700378}
379
Vishnu Nairf0c28512019-02-08 12:40:28 -0800380FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
381 // Subtract the transparent region and snap to the bounds.
382 return reduce(mBounds, activeTransparentRegion);
383}
384
Chavi Weingarten076acac2023-01-19 17:20:43 +0000385// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000386void Layer::updateTrustedPresentationState(const DisplayDevice* display,
387 const frontend::LayerSnapshot* snapshot,
388 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000389 if (!hasTrustedPresentationListener()) {
390 return;
391 }
392 const bool lastState = mLastComputedTrustedPresentationState;
393 mLastComputedTrustedPresentationState = false;
394
395 if (!leaveState) {
396 const auto outputLayer = findOutputLayerForDisplay(display);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000397 if (outputLayer != nullptr) {
398 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
399 Region coveredRegion =
400 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
401 mLastComputedTrustedPresentationState =
402 computeTrustedPresentationState(snapshot->geomLayerBounds,
403 snapshot->sourceBounds(), coveredRegion,
404 snapshot->transformedBounds,
405 snapshot->alpha,
406 snapshot->geomLayerTransform,
407 mTrustedPresentationThresholds);
408 } else {
409 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
410 "TrustedPresentationState",
411 getDebugName());
412 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000413 }
414 }
415 const bool newState = mLastComputedTrustedPresentationState;
416 if (lastState && !newState) {
417 // We were in the trusted presentation state, but now we left it,
418 // emit the callback if needed
419 if (mLastReportedTrustedPresentationState) {
420 mLastReportedTrustedPresentationState = false;
421 mTrustedPresentationListener.invoke(false);
422 }
423 // Reset the timer
424 mEnteredTrustedPresentationStateTime = -1;
425 } else if (!lastState && newState) {
426 // We were not in the trusted presentation state, but we entered it, begin the timer
427 // and make sure this gets called at least once more!
428 mEnteredTrustedPresentationStateTime = time_in_ms;
429 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
430 }
431
432 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
433 if (!mLastReportedTrustedPresentationState && newState &&
434 (time_in_ms - mEnteredTrustedPresentationStateTime >
435 mTrustedPresentationThresholds.stabilityRequirementMs)) {
436 mLastReportedTrustedPresentationState = true;
437 mTrustedPresentationListener.invoke(true);
438 }
439}
440
441/**
442 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
443 * of how the parameters and thresholds are interpreted. The general spirit is
444 * to produce an upper bound on the amount of the buffer which was presented.
445 */
446bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
447 const Region& coveredRegion,
448 const FloatRect& screenBounds, float alpha,
449 const ui::Transform& effectiveTransform,
450 const TrustedPresentationThresholds& thresholds) {
451 if (alpha < thresholds.minAlpha) {
452 return false;
453 }
454 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
455 return false;
456 }
457 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
458 return false;
459 }
460
461 const float sx = effectiveTransform.dsdx();
462 const float sy = effectiveTransform.dsdy();
463 float fractionRendered = std::min(sx * sy, 1.0f);
464
465 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
466 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
467 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
468
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000469 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
470 // Compute the size of all the rects since they may be disconnected.
471 float coveredSize = 0;
472 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
473 float size = rect->width() * rect->height();
474 coveredSize += size;
475 }
476
477 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000478
479 if (fractionRendered < thresholds.minFractionRendered) {
480 return false;
481 }
482
483 return true;
484}
485
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700486void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
487 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800488 const State& s(getDrawingState());
489
490 // Calculate effective layer transform
491 mEffectiveTransform = parentTransform * getActiveTransform(s);
492
Garfield Tan2c1782c2022-02-16 15:25:05 -0800493 if (CC_UNLIKELY(!isTransformValid())) {
494 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
495 getDebugName());
496 return;
497 }
498
Vishnu Nair4351ad52019-02-11 14:13:02 -0800499 // Transform parent bounds to layer space
500 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
501
Vishnu Nairc652ff82019-03-15 12:48:54 -0700502 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800503 mSourceBounds = computeSourceBounds(parentBounds);
504
505 // Calculate bounds by croping diplay frame with layer crop and parent bounds
506 FloatRect bounds = mSourceBounds;
507 const Rect layerCrop = getCrop(s);
508 if (!layerCrop.isEmpty()) {
509 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
510 }
511 bounds = bounds.intersect(parentBounds);
512
513 mBounds = bounds;
514 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700515
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700516 // Use the layer's own shadow radius if set. Otherwise get the radius from
517 // parent.
518 if (s.shadowRadius > 0.f) {
519 mEffectiveShadowRadius = s.shadowRadius;
520 } else {
521 mEffectiveShadowRadius = parentShadowRadius;
522 }
523
524 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
525 // don't pass it to its children.
526 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
527
Vishnu Nair4351ad52019-02-11 14:13:02 -0800528 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700529 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800530 }
Vishnu Nairba354102022-08-01 00:14:18 +0000531
532 if (mPotentialCursor) {
533 prepareCursorCompositionState();
534 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800535}
536
Vishnu Nair60356342018-11-13 13:00:45 -0800537Rect Layer::getCroppedBufferSize(const State& s) const {
538 Rect size = getBufferSize(s);
539 Rect crop = getCrop(s);
540 if (!crop.isEmpty() && size.isValid()) {
541 size.intersect(crop, &size);
542 } else if (!crop.isEmpty()) {
543 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700544 }
Vishnu Nair60356342018-11-13 13:00:45 -0800545 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800546}
547
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700548void Layer::setupRoundedCornersCropCoordinates(Rect win,
549 const FloatRect& roundedCornersCrop) const {
550 // Translate win by the rounded corners rect coordinates, to have all values in
551 // layer coordinate space.
552 win.left -= roundedCornersCrop.left;
553 win.right -= roundedCornersCrop.left;
554 win.top -= roundedCornersCrop.top;
555 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700556}
557
Lloyd Piquede196652020-01-22 17:29:58 -0800558void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800559 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800560 const auto alpha = static_cast<float>(getAlpha());
561 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700562 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800563
564 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
565 if (!opaque || alpha != 1.0f) {
566 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
567 : Hwc2::IComposerClient::BlendMode::COVERAGE;
568 }
569
Alec Mourif4af03e2023-02-11 00:25:24 +0000570 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000571 auto* snapshot = editLayerSnapshot();
572 snapshot->outputFilter = getOutputFilter();
573 snapshot->isVisible = isVisible();
574 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
575 snapshot->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800576
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000577 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800578 contentDirty = false;
579
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000580 snapshot->geomLayerBounds = mBounds;
581 snapshot->geomLayerTransform = getTransform();
582 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
583 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000584 snapshot->localTransform = getActiveTransform(drawingState);
585 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000586 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
587 snapshot->alpha = alpha;
588 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
589 snapshot->blurRegions = drawingState.blurRegions;
590 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800591}
592
Lloyd Piquede196652020-01-22 17:29:58 -0800593void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800594 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000595 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700596
Alec Mourif4af03e2023-02-11 00:25:24 +0000597 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000598 snapshot->geomBufferSize = getBufferSize(drawingState);
599 snapshot->geomContentCrop = getBufferCrop();
600 snapshot->geomCrop = getCrop(drawingState);
601 snapshot->geomBufferTransform = getBufferTransform();
602 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
603 snapshot->geomUsesSourceCrop = usesSourceCrop();
604 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800605
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000606 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800607 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
608 for (const auto& [key, mandatory] : supportedMetadata) {
609 const auto& genericLayerMetadataCompatibilityMap =
610 mFlinger->getGenericLayerMetadataKeyMap();
611 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
612 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
613 continue;
614 }
615 const uint32_t id = compatIter->second;
616
617 auto it = drawingState.metadata.mMap.find(id);
618 if (it == std::end(drawingState.metadata.mMap)) {
619 continue;
620 }
621
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000622 snapshot->metadata.emplace(key,
623 compositionengine::GenericLayerMetadataEntry{mandatory,
624 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800625 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800626}
David Sodmanba340492018-08-05 21:51:33 -0700627
Lloyd Piquede196652020-01-22 17:29:58 -0800628void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800629 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000630 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000631 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800632
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000633 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800634
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000635 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
636 snapshot->dataspace = getDataSpace();
637 snapshot->colorTransform = getColorTransform();
638 snapshot->colorTransformIsIdentity = !hasColorTransform();
639 snapshot->surfaceDamage = surfaceDamageRegion;
640 snapshot->hasProtectedContent = isProtected();
641 snapshot->dimmingEnabled = isDimmingEnabled();
John Reck68796592023-01-25 13:47:12 -0500642 snapshot->currentSdrHdrRatio = getCurrentSdrHdrRatio();
643 snapshot->desiredSdrHdrRatio = getDesiredSdrHdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000644 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800645
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700646 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700647
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000648 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800649
650 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400651 // Rounded corners no longer force client composition, since we may use a
652 // hole punch so that the layer will appear to have rounded corners.
653 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000654 snapshot->stretchEffect.hasEffect()) {
655 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800656 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700657 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000658 snapshot->blurRegions = drawingState.blurRegions;
659 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400660
661 // Layer framerate is used in caching decisions.
662 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
663 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000664 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000665
666 if (hasBufferOrSidebandStream()) {
667 preparePerFrameBufferCompositionState();
668 } else {
669 preparePerFrameEffectsCompositionState();
670 }
671}
672
673void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000674 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000675 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000676 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000677 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
678 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000679 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
680 return;
681 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000682 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000683 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
684 } else {
685 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000686 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
687 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000688 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
689 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
690 }
691
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000692 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000693 snapshot->acquireFence = mBufferInfo.mFence;
694 snapshot->frameNumber = mBufferInfo.mFrameNumber;
695 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000696}
697
698void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000699 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000700 auto* snapshot = editLayerSnapshot();
701 snapshot->color = getColor();
702 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000703 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800704}
705
Lloyd Piquede196652020-01-22 17:29:58 -0800706void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800707 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000708 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000709 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800710
711 // Apply the layer's transform, followed by the display's global transform
712 // Here we're guaranteed that the layer's transform preserves rects
713 Rect win = getCroppedBufferSize(drawingState);
714 // Subtract the transparent region and snap to the bounds
715 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
716 Rect frame(getTransform().transform(bounds));
717
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000718 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800719}
720
Lloyd Piquea83776c2019-01-29 18:42:32 -0800721const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700722 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800723}
724
Mathias Agopian13127d82013-03-05 17:47:11 -0800725// ---------------------------------------------------------------------------
726// drawing...
727// ---------------------------------------------------------------------------
728
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500729aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
730 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700731 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800732 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500733 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800734 }
735 if (outputLayer->getState().hwc) {
736 return (*outputLayer->getState().hwc).hwcCompositionType;
737 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500738 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800739 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800740}
741
Mathias Agopian13127d82013-03-05 17:47:11 -0800742// ----------------------------------------------------------------------------
743// local state
744// ----------------------------------------------------------------------------
745
David Sodman41fdfc92017-11-06 16:09:56 -0800746bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800747 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700748 if (s.flags & layer_state_t::eLayerSecure) {
749 return true;
750 }
751
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000752 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700753 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700754}
755
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100756void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
757 std::vector<JankData>& jankData) {
758 if (mPendingJankClassifications.empty() ||
759 !mPendingJankClassifications.front()->getJankType()) {
760 return;
761 }
762
763 bool includeJankData = false;
764 for (const auto& handle : handles) {
765 for (const auto& cb : handle->callbackIds) {
766 if (cb.includeJankData) {
767 includeJankData = true;
768 break;
769 }
770 }
771
772 if (includeJankData) {
773 jankData.reserve(mPendingJankClassifications.size());
774 break;
775 }
776 }
777
778 while (!mPendingJankClassifications.empty() &&
779 mPendingJankClassifications.front()->getJankType()) {
780 if (includeJankData) {
781 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
782 mPendingJankClassifications.front();
783 jankData.emplace_back(
784 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
785 }
786 mPendingJankClassifications.pop_front();
787 }
788}
789
Mathias Agopian13127d82013-03-05 17:47:11 -0800790// ----------------------------------------------------------------------------
791// transaction
792// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800793
Vishnu Naira156f482023-02-22 00:23:38 +0000794uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700795 ATRACE_CALL();
796
Robert Carr0758e5d2021-03-11 22:15:04 -0800797 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700798 mDrawingStateModified = mDrawingState.modified;
799 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700800
Alec Mourib416efd2018-09-06 21:01:59 +0000801 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700802
Robert Carr6a160312021-05-17 12:08:20 -0700803 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800804 // invalidate and recompute the visible regions if needed
805 flags |= Layer::eVisibleRegion;
806 }
807
Robert Carr6a160312021-05-17 12:08:20 -0700808 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800809 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000810 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800811 flags |= eVisibleRegion;
812 this->contentDirty = true;
813
814 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700815 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800816 }
817
Arthur Hung9ed43392022-05-27 06:31:57 +0000818 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
819 mFlinger->mUpdateInputInfo = true;
820 }
821
Vishnu Naira156f482023-02-22 00:23:38 +0000822 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800823
Mathias Agopian13127d82013-03-05 17:47:11 -0800824 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800825}
826
Vishnu Naira156f482023-02-22 00:23:38 +0000827void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000828 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
829 // bufferSurfaceFrameTX will be presented in latchBuffer.
830 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
831 if (surfaceFrame->getPresentState() != PresentState::Presented) {
832 // With applyPendingStates, we could end up having presented surfaceframes from previous
833 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800834 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000835 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
836 }
837 }
Robert Carr6a160312021-05-17 12:08:20 -0700838 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700839}
840
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700841uint32_t Layer::clearTransactionFlags(uint32_t mask) {
842 const auto flags = mTransactionFlags & mask;
843 mTransactionFlags &= ~mask;
844 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800845}
846
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700847void Layer::setTransactionFlags(uint32_t mask) {
848 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800849}
850
Robert Carr1f0a16a2016-10-24 16:27:39 -0700851bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
852 ssize_t idx = mCurrentChildren.indexOf(childLayer);
853 if (idx < 0) {
854 return false;
855 }
856 if (childLayer->setLayer(z)) {
857 mCurrentChildren.removeAt(idx);
858 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800859 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700860 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800861 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700862}
863
Robert Carr503c7042017-09-27 15:06:08 -0700864bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
865 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
866 ssize_t idx = mCurrentChildren.indexOf(childLayer);
867 if (idx < 0) {
868 return false;
869 }
870 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
871 mCurrentChildren.removeAt(idx);
872 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800873 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700874 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800875 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700876}
877
Robert Carrae060832016-11-28 10:51:00 -0800878bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700879 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
880 mDrawingState.sequence++;
881 mDrawingState.z = z;
882 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700883
Robert Carra70e91c2021-06-11 13:59:52 -0700884 mFlinger->mSomeChildrenChanged = true;
885
Robert Carrdb66e622017-04-10 16:55:57 -0700886 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700887 if (mDrawingState.zOrderRelativeOf != nullptr) {
888 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700889 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700890 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700891 }
chaviw606e5cf2019-03-01 10:12:10 -0800892 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700893 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800894 setTransactionFlags(eTransactionNeeded);
895 return true;
896}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700897
Robert Carrdb66e622017-04-10 16:55:57 -0700898void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700899 mDrawingState.zOrderRelatives.remove(relative);
900 mDrawingState.sequence++;
901 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700902 setTransactionFlags(eTransactionNeeded);
903}
904
905void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700906 mDrawingState.zOrderRelatives.add(relative);
907 mDrawingState.modified = true;
908 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700909 setTransactionFlags(eTransactionNeeded);
910}
911
chaviw606e5cf2019-03-01 10:12:10 -0800912void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700913 mDrawingState.zOrderRelativeOf = relativeOf;
914 mDrawingState.sequence++;
915 mDrawingState.modified = true;
916 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700917
chaviw606e5cf2019-03-01 10:12:10 -0800918 setTransactionFlags(eTransactionNeeded);
919}
920
Robert Carr503d2bd2017-12-04 15:49:47 -0800921bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000922 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700923 if (relative == nullptr) {
924 return false;
925 }
926
Robert Carr6a160312021-05-17 12:08:20 -0700927 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
928 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800929 return false;
930 }
931
Robert Carr88b85e12022-03-21 15:47:35 -0700932 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
933 (relative->mDrawingState.zOrderRelativeOf == this)) {
934 ALOGE("Detected relative layer loop between %s and %s",
935 mName.c_str(), relative->mName.c_str());
936 ALOGE("Ignoring new call to set relative layer");
937 return false;
938 }
939
Robert Carra70e91c2021-06-11 13:59:52 -0700940 mFlinger->mSomeChildrenChanged = true;
941
Robert Carr6a160312021-05-17 12:08:20 -0700942 mDrawingState.sequence++;
943 mDrawingState.modified = true;
944 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700945
Robert Carr6a160312021-05-17 12:08:20 -0700946 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700947 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700948 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700949 }
chaviw606e5cf2019-03-01 10:12:10 -0800950 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700951 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700952
953 setTransactionFlags(eTransactionNeeded);
954
955 return true;
956}
957
Winson Chunga30f7c92021-06-29 15:42:56 -0700958bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
959 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
960 mDrawingState.isTrustedOverlay = isTrustedOverlay;
961 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000962 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700963 setTransactionFlags(eTransactionNeeded);
964 return true;
965}
966
967bool Layer::isTrustedOverlay() const {
968 if (getDrawingState().isTrustedOverlay) {
969 return true;
970 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000971 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700972 return (p != nullptr) && p->isTrustedOverlay();
973}
974
Dan Stoza9e56aa02015-11-02 13:00:03 -0800975bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700976 if (mDrawingState.color.a == alpha) return false;
977 mDrawingState.sequence++;
978 mDrawingState.color.a = alpha;
979 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800980 setTransactionFlags(eTransactionNeeded);
981 return true;
982}
chaviw13fdc492017-06-27 12:40:18 -0700983
Valerie Haudd0b7572019-01-29 14:59:27 -0800984bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700985 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700986 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800987 }
Robert Carr6a160312021-05-17 12:08:20 -0700988 mDrawingState.sequence++;
989 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800990 setTransactionFlags(eTransactionNeeded);
991
Robert Carr6a160312021-05-17 12:08:20 -0700992 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -0800993 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -0800994 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700995 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -0700996 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800997 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700998 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -0700999
Valerie Haudd0b7572019-01-29 14:59:27 -08001000 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001001 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001002 mFlinger->mLayersAdded = true;
1003 // set up SF to handle added color layer
1004 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -07001005 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001006 }
1007 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001008 } else if (mDrawingState.bgColorLayer && alpha == 0) {
1009 mDrawingState.bgColorLayer->reparent(nullptr);
1010 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001011 return true;
1012 }
1013
Robert Carr6a160312021-05-17 12:08:20 -07001014 mDrawingState.bgColorLayer->setColor(color);
1015 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1016 mDrawingState.bgColorLayer->setAlpha(alpha);
1017 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001018
chaviw13fdc492017-06-27 12:40:18 -07001019 return true;
1020}
1021
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001022bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001023 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001024
Robert Carr6a160312021-05-17 12:08:20 -07001025 mDrawingState.sequence++;
1026 mDrawingState.cornerRadius = cornerRadius;
1027 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001028 setTransactionFlags(eTransactionNeeded);
1029 return true;
1030}
1031
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001032bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001033 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001034 // If we start or stop drawing blur then the layer's visibility state may change so increment
1035 // the magic sequence number.
1036 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1037 mDrawingState.sequence++;
1038 }
Robert Carr6a160312021-05-17 12:08:20 -07001039 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1040 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001041 setTransactionFlags(eTransactionNeeded);
1042 return true;
1043}
Marissa Wall61c58622018-07-18 10:12:20 -07001044
Mathias Agopian13127d82013-03-05 17:47:11 -08001045bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001046 mDrawingState.sequence++;
1047 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001048 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001049 setTransactionFlags(eTransactionNeeded);
1050 return true;
1051}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001052
Lucas Dupinc3800b82020-10-02 16:24:48 -07001053bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001054 // If we start or stop drawing blur then the layer's visibility state may change so increment
1055 // the magic sequence number.
1056 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1057 mDrawingState.sequence++;
1058 }
Robert Carr6a160312021-05-17 12:08:20 -07001059 mDrawingState.blurRegions = blurRegions;
1060 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001061 setTransactionFlags(eTransactionNeeded);
1062 return true;
1063}
1064
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001065bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001066 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1067 if (mDrawingState.flags == newFlags) return false;
1068 mDrawingState.sequence++;
1069 mDrawingState.flags = newFlags;
1070 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001071 setTransactionFlags(eTransactionNeeded);
1072 return true;
1073}
Robert Carr99e27f02016-06-16 15:18:02 -07001074
chaviw25714502021-02-11 10:01:08 -08001075bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001076 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001077 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001078 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001079
Robert Carr6a160312021-05-17 12:08:20 -07001080 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001081 setTransactionFlags(eTransactionNeeded);
1082 return true;
1083}
Robert Carr8d5227b2017-03-16 15:41:03 -07001084
Evan Roskyef876c92019-01-25 17:46:06 -08001085bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001086 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1087 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001088 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001089 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001090}
1091
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001092bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001093 if (mDrawingState.layerStack == layerStack) return false;
1094 mDrawingState.sequence++;
1095 mDrawingState.layerStack = layerStack;
1096 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001097 setTransactionFlags(eTransactionNeeded);
1098 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001099}
1100
Peiyong Linc502cb72019-03-01 15:00:23 -08001101bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001102 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001103 return false;
1104 }
Robert Carr6a160312021-05-17 12:08:20 -07001105 mDrawingState.sequence++;
1106 mDrawingState.colorSpaceAgnostic = agnostic;
1107 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001108 setTransactionFlags(eTransactionNeeded);
1109 return true;
1110}
1111
Sally Qi81d95e62022-03-21 19:41:33 -07001112bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1113 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1114
1115 mDrawingState.sequence++;
1116 mDrawingState.dimmingEnabled = dimmingEnabled;
1117 mDrawingState.modified = true;
1118 setTransactionFlags(eTransactionNeeded);
1119 return true;
1120}
1121
Ana Krulecc84d09b2019-11-02 23:10:29 +01001122bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001123 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1124 mDrawingState.frameRateSelectionPriority = priority;
1125 mDrawingState.sequence++;
1126 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001127 setTransactionFlags(eTransactionNeeded);
1128 return true;
1129}
1130
1131int32_t Layer::getFrameRateSelectionPriority() const {
1132 // Check if layer has priority set.
1133 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1134 return mDrawingState.frameRateSelectionPriority;
1135 }
1136 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001137 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001138 if (parent != nullptr) {
1139 return parent->getFrameRateSelectionPriority();
1140 }
1141
1142 return Layer::PRIORITY_UNSET;
1143}
1144
Andy Labrada096227e2022-06-15 16:58:11 +00001145bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1146 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1147 mDrawingState.defaultFrameRateCompatibility = compatibility;
1148 mDrawingState.modified = true;
1149 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1150 setTransactionFlags(eTransactionNeeded);
1151 return true;
1152}
1153
1154scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1155 return mDrawingState.defaultFrameRateCompatibility;
1156}
1157
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001158bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1159 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1160};
1161
Vishnu Nair73908d12022-10-24 21:46:42 -07001162ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1163 bool useDrawing = state == LayerVector::StateSet::Drawing;
1164 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1165 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001166 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001167 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001168 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001169}
1170
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001171bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001172 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001173 return false;
1174 }
1175
Robert Carr6a160312021-05-17 12:08:20 -07001176 mDrawingState.sequence++;
1177 mDrawingState.shadowRadius = shadowRadius;
1178 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001179 setTransactionFlags(eTransactionNeeded);
1180 return true;
1181}
1182
Vishnu Nair6213bd92020-05-08 17:42:25 -07001183bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001184 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001185 return false;
1186 }
1187
Robert Carr6a160312021-05-17 12:08:20 -07001188 mDrawingState.sequence++;
1189 mDrawingState.fixedTransformHint = fixedTransformHint;
1190 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001191 setTransactionFlags(eTransactionNeeded);
1192 return true;
1193}
1194
John Reckcdb4ed72021-02-04 13:39:33 -05001195bool Layer::setStretchEffect(const StretchEffect& effect) {
1196 StretchEffect temp = effect;
1197 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001198 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001199 return false;
1200 }
Robert Carr6a160312021-05-17 12:08:20 -07001201 mDrawingState.sequence++;
1202 mDrawingState.stretchEffect = temp;
1203 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001204 setTransactionFlags(eTransactionNeeded);
1205 return true;
1206}
1207
John Reckc00c6692021-02-16 11:37:33 -05001208StretchEffect Layer::getStretchEffect() const {
1209 if (mDrawingState.stretchEffect.hasEffect()) {
1210 return mDrawingState.stretchEffect;
1211 }
1212
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001213 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001214 if (parent != nullptr) {
1215 auto effect = parent->getStretchEffect();
1216 if (effect.hasEffect()) {
1217 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1218 return effect;
1219 }
1220 }
1221 return StretchEffect{};
1222}
1223
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001224bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1225 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001226 return false;
1227 }
1228 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001229 mBorderWidth = width;
1230 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001231 return true;
1232}
1233
1234bool Layer::isBorderEnabled() {
1235 return mBorderEnabled;
1236}
1237
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001238float Layer::getBorderWidth() {
1239 return mBorderWidth;
1240}
1241
1242const half4& Layer::getBorderColor() {
1243 return mBorderColor;
1244}
1245
Ady Abrahama850c182021-08-04 13:04:37 -07001246bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1247 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1248 const auto frameRate = [&] {
1249 if (mDrawingState.frameRate.rate.isValid() ||
1250 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1251 return mDrawingState.frameRate;
1252 }
1253
1254 return parentFrameRate;
1255 }();
1256
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001257 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001258
1259 // The frame rate is propagated to the children
1260 bool childrenHaveFrameRate = false;
1261 for (const sp<Layer>& child : mCurrentChildren) {
1262 childrenHaveFrameRate |=
1263 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1264 }
1265
1266 // If we don't have a valid frame rate, but the children do, we set this
1267 // layer as NoVote to allow the children to control the refresh rate
1268 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1269 childrenHaveFrameRate) {
1270 *transactionNeeded |=
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001271 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001272 }
1273
1274 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1275 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001276 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001277 const auto layerVotedWithDefaultCompatibility =
1278 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1279 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1280 const auto layerVotedWithExactCompatibility =
1281 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1282 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1283 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1284}
1285
Ady Abraham60e42ea2020-03-09 19:17:31 -07001286void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001287 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001288 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001289 while (auto parent = layer->getParent()) {
1290 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001291 }
Ady Abrahama850c182021-08-04 13:04:37 -07001292 return layer;
1293 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001294
Ady Abraham60e42ea2020-03-09 19:17:31 -07001295 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001296 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001297
Ady Abrahama850c182021-08-04 13:04:37 -07001298 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001299 if (transactionNeeded) {
1300 mFlinger->setTransactionFlags(eTraversalNeeded);
1301 }
1302}
1303
Ady Abraham71c437d2020-01-31 15:56:57 -08001304bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001305 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001306 return false;
1307 }
1308
Robert Carr6a160312021-05-17 12:08:20 -07001309 mDrawingState.sequence++;
1310 mDrawingState.frameRate = frameRate;
1311 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001312
1313 updateTreeHasFrameRateVote();
1314
Steven Thomas3172e202020-01-06 19:25:30 -08001315 setTransactionFlags(eTransactionNeeded);
1316 return true;
1317}
1318
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001319void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1320 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001321 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001322
1323 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1324 // there are two transactions with the same token, the first one without a buffer and the
1325 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1326 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001327 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1328 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001329 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001330 mDrawingState.bufferSurfaceFrameTX = it->second;
1331 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1332 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1333 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001334 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001335 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001336 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1337 }
1338}
1339
1340void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1341 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001342 mDrawingState.frameTimelineInfo = info;
1343 mDrawingState.postTime = postTime;
1344 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001345 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001346
Robert Carr6a160312021-05-17 12:08:20 -07001347 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001348 bufferSurfaceFrameTX != nullptr) {
1349 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1350 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1351 // being used for BufferSurfaceFrame, don't create a new one.
1352 return;
1353 }
1354 }
1355 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1356 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1357 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001358 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1359 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001360 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001361 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001362 } else {
1363 if (it->second->getPresentState() == PresentState::Presented) {
1364 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1365 // have been from previous vsync.
1366 it->second = createSurfaceFrameForTransaction(info, postTime);
1367 }
1368 }
1369}
1370
1371void Layer::addSurfaceFrameDroppedForBuffer(
1372 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001373 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001374 surfaceFrame->setPresentState(PresentState::Dropped);
1375 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1376}
1377
1378void Layer::addSurfaceFramePresentedForBuffer(
1379 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1380 nsecs_t currentLatchTime) {
1381 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1382 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1383 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001384 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001385}
1386
1387std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1388 const FrameTimelineInfo& info, nsecs_t postTime) {
1389 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001390 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1391 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001392 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001393 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001394 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001395 // For Transactions, the post time is considered to be both queue and acquire fence time.
1396 surfaceFrame->setActualQueueTime(postTime);
1397 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001398 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1399 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001400 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001401 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001402 onSurfaceFrameCreated(surfaceFrame);
1403 return surfaceFrame;
1404}
1405
1406std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1407 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1408 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001409 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001410 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001411 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001412 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001413 // For buffers, acquire fence time will set during latch.
1414 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001415 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1416 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001417 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001418 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001419 onSurfaceFrameCreated(surfaceFrame);
1420 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001421}
1422
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001423bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001424 if (mDrawingState.frameRateForLayerTree == frameRate) {
1425 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001426 }
1427
Ady Abrahama850c182021-08-04 13:04:37 -07001428 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001429
Ady Abrahama850c182021-08-04 13:04:37 -07001430 // TODO(b/195668952): we probably don't need to dirty visible regions here
1431 // or even store frameRateForLayerTree in mDrawingState
1432 mDrawingState.sequence++;
1433 mDrawingState.modified = true;
1434 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001435
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001436 mFlinger->mScheduler
1437 ->recordLayerHistory(sequence, getLayerProps(), systemTime(),
1438 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1439 return true;
1440}
Ady Abrahama850c182021-08-04 13:04:37 -07001441
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001442bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps) {
1443 if (mDrawingState.frameRateForLayerTree == frameRate) {
1444 return false;
1445 }
1446
1447 mDrawingState.frameRateForLayerTree = frameRate;
1448 mFlinger->mScheduler
1449 ->recordLayerHistory(sequence, layerProps, systemTime(),
1450 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001451 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001452}
1453
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001454Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1455 return getDrawingState().frameRateForLayerTree;
1456}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001457
Robert Carr1f0a16a2016-10-24 16:27:39 -07001458bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001459 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001460 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001461 if (parent != nullptr && parent->isHiddenByPolicy()) {
1462 return true;
1463 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001464 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1465 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1466 if (zOrderRelativeOf != nullptr) {
1467 if (zOrderRelativeOf->isHiddenByPolicy()) {
1468 return true;
1469 }
1470 }
1471 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001472 if (CC_UNLIKELY(!isTransformValid())) {
1473 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1474 return true;
1475 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001476 return s.flags & layer_state_t::eLayerHidden;
1477}
1478
David Sodman41fdfc92017-11-06 16:09:56 -08001479uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001480 // TODO: should we do something special if mSecure is set?
1481 if (mProtectedByApp) {
1482 // need a hardware-protected path to external video sink
1483 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001484 }
Riley Andrews03414a12014-07-01 14:22:59 -07001485 if (mPotentialCursor) {
1486 usage |= GraphicBuffer::USAGE_CURSOR;
1487 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001488 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001489 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001490}
1491
Vishnu Nair71fcf912022-10-18 09:14:20 -07001492void Layer::skipReportingTransformHint() {
1493 mSkipReportingTransformHint = true;
1494}
1495
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001496void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1497 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1498 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001499 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001500
Vishnu Nair6213bd92020-05-08 17:42:25 -07001501 setTransformHint(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001502}
1503
Mathias Agopian13127d82013-03-05 17:47:11 -08001504// ----------------------------------------------------------------------------
1505// debugging
1506// ----------------------------------------------------------------------------
1507
Marissa Wall61c58622018-07-18 10:12:20 -07001508// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001509gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001510 using namespace std::string_literals;
1511
Huihong Luo05539a12022-02-23 10:29:40 -08001512 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001513 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001514 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001515 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001516 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001517 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001518
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001519 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001520 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001521 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001522 info.mX = ds.transform.tx();
1523 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001524 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001525 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001526 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001527 info.mFlags = ds.flags;
1528 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001529 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001530 info.mMatrix[0][0] = ds.transform[0][0];
1531 info.mMatrix[0][1] = ds.transform[0][1];
1532 info.mMatrix[1][0] = ds.transform[1][0];
1533 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001534 {
chaviwd62d3062019-09-04 14:48:02 -07001535 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001536 if (buffer != 0) {
1537 info.mActiveBufferWidth = buffer->getWidth();
1538 info.mActiveBufferHeight = buffer->getHeight();
1539 info.mActiveBufferStride = buffer->getStride();
1540 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001541 } else {
1542 info.mActiveBufferWidth = 0;
1543 info.mActiveBufferHeight = 0;
1544 info.mActiveBufferStride = 0;
1545 info.mActiveBufferFormat = 0;
1546 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001547 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001548 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001549 info.mIsOpaque = isOpaque(ds);
1550 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001551 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001552 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001553}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001554
Yiwei Zhang5434a782018-12-05 18:06:32 -08001555void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001556 result.append(kDumpTableRowLength, '-');
1557 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001558 result.append(" Layer name\n");
1559 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001560 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001561 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001562 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001563 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001564 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001565 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1566 result.append(kDumpTableRowLength, '-');
1567 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001568}
1569
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001570void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1571 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001572 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001573 return;
1574 }
1575
Yiwei Zhang5434a782018-12-05 18:06:32 -08001576 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001577 if (mName.length() > 77) {
1578 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001579 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001580 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001581 shortened.append(mName, mName.length() - 36);
1582 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001583 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001584 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001585 }
1586
Yiwei Zhang5434a782018-12-05 18:06:32 -08001587 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001588
Alec Mourib416efd2018-09-06 21:01:59 +00001589 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001590 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001591
Chia-I Wu1e043612018-03-01 09:45:09 -08001592 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001593 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001594 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001595 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001596 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001597 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001598 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001599 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1600 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001601 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001602 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001603 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001604 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001605 const auto frameRate = getFrameRateForLayerTree();
1606 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1607 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001608 ftl::enum_string(frameRate.type).c_str(),
1609 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001610 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001611 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001612 }
Dan Stozae22aec72016-08-01 13:20:59 -07001613
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001614 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1615 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1616
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001617 result.append(kDumpTableRowLength, '-');
1618 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001619}
Dan Stozae22aec72016-08-01 13:20:59 -07001620
Yiwei Zhang5434a782018-12-05 18:06:32 -08001621void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001622 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001623}
1624
Svetoslavd85084b2014-03-20 10:28:31 -07001625void Layer::clearFrameStats() {
1626 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001627}
1628
Jamie Gennis6547ff42013-07-16 20:12:42 -07001629void Layer::logFrameStats() {
1630 mFrameTracker.logAndResetStats(mName);
1631}
1632
Svetoslavd85084b2014-03-20 10:28:31 -07001633void Layer::getFrameStats(FrameStats* outStats) const {
1634 mFrameTracker.getStats(outStats);
1635}
1636
Vishnu Nair76554eb2022-12-09 03:38:36 +00001637void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1638 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
1639 StringAppendF(&result, "Layer %s%s pid:%d uid:%d\n", getName().c_str(), hasBuffer.c_str(),
Vishnu Naircb8be502022-10-12 19:03:23 +00001640 mOwnerPid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001641}
1642
Brian Anderson5ea5e592016-12-01 16:54:33 -08001643void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001644 const int32_t layerId = getSequence();
1645 mFlinger->mTimeStats->onDestroy(layerId);
1646 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001647}
1648
Chia-I Wu98f1c102017-05-30 14:54:08 -07001649size_t Layer::getChildrenCount() const {
1650 size_t count = 0;
1651 for (const sp<Layer>& child : mCurrentChildren) {
1652 count += 1 + child->getChildrenCount();
1653 }
1654 return count;
1655}
1656
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001657void Layer::setGameModeForTree(GameMode gameMode) {
1658 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001659 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1660 gameMode =
1661 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001662 }
1663 setGameMode(gameMode);
1664 for (const sp<Layer>& child : mCurrentChildren) {
1665 child->setGameModeForTree(gameMode);
1666 }
1667}
1668
Robert Carr1f0a16a2016-10-24 16:27:39 -07001669void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001670 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001671 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001672
Robert Carr1f0a16a2016-10-24 16:27:39 -07001673 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001674 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001675 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001676 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001677}
1678
1679ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001680 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001681 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001682
Robert Carr1323c952019-01-28 18:13:27 -08001683 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001684 const auto removeResult = mCurrentChildren.remove(layer);
1685
1686 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001687 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001688 layer->updateTreeHasFrameRateVote();
1689
1690 return removeResult;
1691}
1692
Robert Carr15eae092018-03-23 13:43:53 -07001693void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001694 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001695 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001696 const float parentShadowRadius =
1697 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001698 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001699 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001700 }
1701}
1702
chaviwf1961f72017-09-18 16:41:07 -07001703bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001704 sp<Layer> newParent;
1705 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001706 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001707 if (newParent == nullptr) {
1708 ALOGE("Unable to promote Layer handle");
1709 return false;
1710 }
1711 if (newParent == this) {
1712 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1713 return false;
1714 }
1715 }
1716
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001717 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001718 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001719 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001720 }
1721
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001722 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001723 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001724 if (!newParent->isRemovedFromCurrentState()) {
1725 addToCurrentState();
1726 } else {
1727 onRemovedFromCurrentState();
1728 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001729 } else {
1730 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001731 }
1732
chaviw06178942017-07-27 10:25:59 -07001733 return true;
1734}
1735
Peiyong Lind3788632018-09-18 16:01:31 -07001736bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001737 static const mat4 identityMatrix = mat4();
1738
Robert Carr6a160312021-05-17 12:08:20 -07001739 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001740 return false;
1741 }
Robert Carr6a160312021-05-17 12:08:20 -07001742 ++mDrawingState.sequence;
1743 mDrawingState.colorTransform = matrix;
1744 mDrawingState.hasColorTransform = matrix != identityMatrix;
1745 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001746 setTransactionFlags(eTransactionNeeded);
1747 return true;
1748}
1749
chaviwf66724d2018-11-28 16:35:21 -08001750mat4 Layer::getColorTransform() const {
1751 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001752 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001753 colorTransform = parent->getColorTransform() * colorTransform;
1754 }
1755 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001756}
1757
1758bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001759 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001760 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001761 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1762 }
1763 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001764}
1765
Chia-I Wu11481472018-05-04 10:43:19 -07001766bool Layer::isLegacyDataSpace() const {
1767 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001768 return !(getDataSpace() &
1769 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1770 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001771}
1772
Robert Carr1f0a16a2016-10-24 16:27:39 -07001773void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001774 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001775}
1776
Robert Carr6a160312021-05-17 12:08:20 -07001777int32_t Layer::getZ(LayerVector::StateSet) const {
1778 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001779}
1780
Robert Carr1c5481e2019-07-01 14:42:27 -07001781bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001782 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001783 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001784 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001785}
1786
David Sodman41fdfc92017-11-06 16:09:56 -08001787__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001788 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001789 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1790 "makeTraversalList received invalid stateSet");
1791 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1792 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001793 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001794
Robert Carr29abff82017-12-04 13:51:20 -08001795 if (state.zOrderRelatives.size() == 0) {
1796 *outSkipRelativeZUsers = true;
1797 return children;
1798 }
1799
chaviwfd462612018-05-31 16:11:27 -07001800 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001801 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001802 sp<Layer> strongRelative = weakRelative.promote();
1803 if (strongRelative != nullptr) {
1804 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001805 }
1806 }
1807
Dan Stoza412903f2017-04-27 13:42:17 -07001808 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001809 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001810 continue;
1811 }
Robert Carrdb66e622017-04-10 16:55:57 -07001812 traverse.add(child);
1813 }
1814
1815 return traverse;
1816}
1817
Robert Carr1f0a16a2016-10-24 16:27:39 -07001818/**
Robert Carrdb66e622017-04-10 16:55:57 -07001819 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001820 */
Dan Stoza412903f2017-04-27 13:42:17 -07001821void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001822 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1823 // produce a new list for traversing, including our relatives, and not including our children
1824 // who are relatives of another surface. In the case that there are no relative Z,
1825 // makeTraversalList returns our children directly to avoid significant overhead.
1826 // However in this case we need to take the responsibility for filtering children which
1827 // are relatives of another surface here.
1828 bool skipRelativeZUsers = false;
1829 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001830
Robert Carr1f0a16a2016-10-24 16:27:39 -07001831 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001832 for (; i < list.size(); i++) {
1833 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001834 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1835 continue;
1836 }
1837
chaviw301b1d82019-11-06 13:15:09 -08001838 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001839 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001840 }
Dan Stoza412903f2017-04-27 13:42:17 -07001841 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001842 }
Robert Carr29abff82017-12-04 13:51:20 -08001843
Dan Stoza412903f2017-04-27 13:42:17 -07001844 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001845 for (; i < list.size(); i++) {
1846 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001847
Robert Carr29abff82017-12-04 13:51:20 -08001848 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1849 continue;
1850 }
Dan Stoza412903f2017-04-27 13:42:17 -07001851 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001852 }
1853}
1854
1855/**
Robert Carrdb66e622017-04-10 16:55:57 -07001856 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001857 */
Dan Stoza412903f2017-04-27 13:42:17 -07001858void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1859 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001860 // See traverseInZOrder for documentation.
1861 bool skipRelativeZUsers = false;
1862 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001863
Robert Carr1f0a16a2016-10-24 16:27:39 -07001864 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001865 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001866 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001867
1868 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1869 continue;
1870 }
1871
chaviw301b1d82019-11-06 13:15:09 -08001872 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001873 break;
1874 }
Dan Stoza412903f2017-04-27 13:42:17 -07001875 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001876 }
Dan Stoza412903f2017-04-27 13:42:17 -07001877 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001878 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001879 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001880
1881 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1882 continue;
1883 }
1884
Dan Stoza412903f2017-04-27 13:42:17 -07001885 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001886 }
1887}
1888
Edgar Arriaga844fa672020-01-16 14:21:42 -08001889void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1890 visitor(this);
1891 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001892 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001893 for (const sp<Layer>& child : children) {
1894 child->traverse(state, visitor);
1895 }
1896}
1897
chaviw4b129c22018-04-09 16:19:43 -07001898LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1899 const std::vector<Layer*>& layersInTree) {
1900 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1901 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001902 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1903 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001904 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001905
chaviwfd462612018-05-31 16:11:27 -07001906 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001907 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1908 sp<Layer> strongRelative = weakRelative.promote();
1909 // Only add relative layers that are also descendents of the top most parent of the tree.
1910 // If a relative layer is not a descendent, then it should be ignored.
1911 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1912 traverse.add(strongRelative);
1913 }
1914 }
1915
1916 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001917 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001918 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1919 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1920 // the child here since it won't be added later as a relative.
1921 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1922 childState.zOrderRelativeOf.promote().get())) {
1923 continue;
1924 }
1925 traverse.add(child);
1926 }
1927
1928 return traverse;
1929}
1930
1931void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1932 LayerVector::StateSet stateSet,
1933 const LayerVector::Visitor& visitor) {
1934 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001935
1936 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001937 for (; i < list.size(); i++) {
1938 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001939 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001940 break;
1941 }
chaviw4b129c22018-04-09 16:19:43 -07001942 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001943 }
chaviw4b129c22018-04-09 16:19:43 -07001944
chaviwa76b2712017-09-20 12:02:26 -07001945 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001946 for (; i < list.size(); i++) {
1947 const auto& relative = list[i];
1948 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001949 }
1950}
1951
chaviw4b129c22018-04-09 16:19:43 -07001952std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1953 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1954 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1955
1956 std::vector<Layer*> layersInTree = {this};
1957 for (size_t i = 0; i < children.size(); i++) {
1958 const auto& child = children[i];
1959 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1960 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1961 }
1962
1963 return layersInTree;
1964}
1965
1966void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1967 const LayerVector::Visitor& visitor) {
1968 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1969 std::sort(layersInTree.begin(), layersInTree.end());
1970 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1971}
1972
Peiyong Linefefaac2018-08-17 12:27:51 -07001973ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001974 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001975}
1976
Garfield Tan2c1782c2022-02-16 15:25:05 -08001977bool Layer::isTransformValid() const {
1978 float transformDet = getTransform().det();
1979 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1980}
1981
chaviw13fdc492017-06-27 12:40:18 -07001982half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001983 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001984
chaviw13fdc492017-06-27 12:40:18 -07001985 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1986 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07001987}
Robert Carr6452f122017-03-21 10:41:29 -07001988
Vishnu Nair6213bd92020-05-08 17:42:25 -07001989ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07001990 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001991 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
1992 return fixedTransformHint;
1993 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001994 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07001995 if (!p) return fixedTransformHint;
1996 return p->getFixedTransformHint();
1997}
1998
chaviw13fdc492017-06-27 12:40:18 -07001999half4 Layer::getColor() const {
2000 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002001 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002002}
Robert Carr6452f122017-03-21 10:41:29 -07002003
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002004int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002005 if (getDrawingState().backgroundBlurRadius == 0) {
2006 return 0;
2007 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002008
Vishnu Nair29810f72022-07-01 16:38:41 +00002009 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002010 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2011 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002012}
2013
Galia Peychevae0acf382021-04-12 21:22:34 +02002014const std::vector<BlurRegion> Layer::getBlurRegions() const {
2015 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002016 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002017 for (auto& region : regionsCopy) {
2018 region.alpha = region.alpha * layerAlpha;
2019 }
2020 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002021}
2022
Vishnu Naire14c6b32022-08-06 04:20:15 +00002023RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002024 // Get parent settings
2025 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002026 const auto& parent = mDrawingParent.promote();
2027 if (parent != nullptr) {
2028 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002029 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002030 ui::Transform t = getActiveTransform(getDrawingState());
2031 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002032 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002033 parentSettings.radius.x *= t.getScaleX();
2034 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002035 }
2036 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002037
2038 // Get layer settings
2039 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002040 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002041 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002042 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002043
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002044 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002045 // If the parent and the layer have rounded corner settings, use the parent settings if the
2046 // parent crop is entirely inside the layer crop.
2047 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2048 if (parentSettings.cropRect.left > layerCropRect.left &&
2049 parentSettings.cropRect.top > layerCropRect.top &&
2050 parentSettings.cropRect.right < layerCropRect.right &&
2051 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2052 return parentSettings;
2053 } else {
2054 return layerSettings;
2055 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002056 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002057 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002058 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002059 return parentSettings;
2060 }
2061 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002062}
2063
Robert Carr88b85e12022-03-21 15:47:35 -07002064bool Layer::findInHierarchy(const sp<Layer>& l) {
2065 if (l == this) {
2066 return true;
2067 }
2068 for (auto& child : mDrawingChildren) {
2069 if (child->findInHierarchy(l)) {
2070 return true;
2071 }
2072 }
2073 return false;
2074}
2075
Robert Carr1f0a16a2016-10-24 16:27:39 -07002076void Layer::commitChildList() {
2077 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2078 const auto& child = mCurrentChildren[i];
2079 child->commitChildList();
2080 }
2081 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002082 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002083 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2084 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2085 if (zOrderRelativeOf == nullptr) return;
2086 if (findInHierarchy(zOrderRelativeOf)) {
2087 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2088 zOrderRelativeOf->mName.c_str());
2089 ALOGE("Severing rel Z loop, potentially dangerous");
2090 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002091 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002092 }
2093 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002094}
2095
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002096
chaviw3277faf2021-05-19 16:45:23 -05002097void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002098 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002099 mDrawingState.touchableRegionCrop =
2100 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002101 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002102 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002103 setTransactionFlags(eTransactionNeeded);
2104}
2105
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002106LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002107 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002108 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002109 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2110
Vishnu Nair00b90132021-11-05 14:03:40 -07002111 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002112 writeCompositionStateToProto(layerProto);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002113 }
2114
chaviw08f3cb22020-01-13 13:17:21 -08002115 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002116 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002117 }
chaviw6d89e2d2020-01-14 14:42:01 -08002118
2119 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002120}
2121
Vishnu Nairea6ff812023-02-27 17:41:39 +00002122void Layer::writeCompositionStateToProto(LayerProto* layerProto) {
2123 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2124
2125 // Only populate for the primary display.
2126 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
2127 const auto compositionType = getCompositionType(*display);
2128 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
2129 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2130 [&]() { return layerProto->mutable_visible_region(); });
2131 }
2132}
2133
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002134void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002135 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002136 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002137 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002138 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002139 [&]() { return layerInfo->mutable_active_buffer(); });
2140 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2141 layerInfo->mutable_buffer_transform());
2142 }
2143 layerInfo->set_invalidate(contentDirty);
2144 layerInfo->set_is_protected(isProtected());
2145 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2146 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002147 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002148 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002149 layerInfo->set_corner_radius(
2150 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002151 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2152 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2153 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2154 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2155 [&]() { return layerInfo->mutable_position(); });
2156 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002157 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2158 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002159
Vishnu Nair00b90132021-11-05 14:03:40 -07002160 if (hasColorTransform()) {
2161 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002162 }
2163
Vishnu Nair60db8c02020-04-02 11:55:16 -07002164 LayerProtoHelper::writeToProto(mSourceBounds,
2165 [&]() { return layerInfo->mutable_source_bounds(); });
2166 LayerProtoHelper::writeToProto(mScreenBounds,
2167 [&]() { return layerInfo->mutable_screen_bounds(); });
2168 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2169 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2170 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002171}
2172
2173void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002174 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002175 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2176 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002177 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002178
chaviw766c9c52021-02-10 17:36:47 -08002179 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002180
Vishnu Nair00b90132021-11-05 14:03:40 -07002181 layerInfo->set_id(sequence);
2182 layerInfo->set_name(getName().c_str());
2183 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002184
Vishnu Nair00b90132021-11-05 14:03:40 -07002185 for (const auto& child : children) {
2186 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002187 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002188
Vishnu Nair00b90132021-11-05 14:03:40 -07002189 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2190 sp<Layer> strongRelative = weakRelative.promote();
2191 if (strongRelative != nullptr) {
2192 layerInfo->add_relatives(strongRelative->sequence);
2193 }
2194 }
2195
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002196 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002197 [&]() { return layerInfo->mutable_transparent_region(); });
2198
2199 layerInfo->set_layer_stack(getLayerStack().id);
2200 layerInfo->set_z(state.z);
2201
2202 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2203 return layerInfo->mutable_requested_position();
2204 });
2205
Vishnu Nair00b90132021-11-05 14:03:40 -07002206 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2207
2208 layerInfo->set_is_opaque(isOpaque(state));
2209
2210 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2211 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2212 LayerProtoHelper::writeToProto(state.color,
2213 [&]() { return layerInfo->mutable_requested_color(); });
2214 layerInfo->set_flags(state.flags);
2215
2216 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2217 layerInfo->mutable_requested_transform());
2218
2219 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2220 if (parent != nullptr) {
2221 layerInfo->set_parent(parent->sequence);
2222 } else {
2223 layerInfo->set_parent(-1);
2224 }
2225
2226 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2227 if (zOrderRelativeOf != nullptr) {
2228 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2229 } else {
2230 layerInfo->set_z_order_relative_of(-1);
2231 }
2232
2233 layerInfo->set_is_relative_of(state.isRelativeOf);
2234
2235 layerInfo->set_owner_uid(mOwnerUid);
2236
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002237 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002238 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002239 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002240 info = fillInputInfo(
2241 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002242 } else {
2243 info = state.inputInfo;
2244 }
2245
2246 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002247 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002248 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002249
Vishnu Nair00b90132021-11-05 14:03:40 -07002250 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002251 auto protoMap = layerInfo->mutable_metadata();
2252 for (const auto& entry : state.metadata.mMap) {
2253 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2254 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002255 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002256
2257 LayerProtoHelper::writeToProto(state.destinationFrame,
2258 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002259}
2260
Robert Carr2e102c92018-10-23 12:11:15 -07002261bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002262 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002263}
2264
Prabir Pradhan33da9462022-06-14 14:55:57 +00002265// Applies the given transform to the region, while protecting against overflows caused by any
2266// offsets. If applying the offset in the transform to any of the Rects in the region would result
2267// in an overflow, they are not added to the output Region.
2268static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2269 const std::string& debugWindowName) {
2270 // Round the translation using the same rounding strategy used by ui::Transform.
2271 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2272 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2273
2274 ui::Transform transformWithoutOffset = t;
2275 transformWithoutOffset.set(0.f, 0.f);
2276
2277 const Region transformed = transformWithoutOffset.transform(r);
2278
2279 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2280 Region ret;
2281 for (const auto& rect : transformed) {
2282 Rect newRect;
2283 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2284 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2285 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2286 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2287 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2288 debugWindowName.c_str());
2289 continue;
2290 }
2291 ret.orSelf(newRect);
2292 }
2293 return ret;
2294}
2295
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002296void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
2297 Rect tmpBounds = getInputBounds();
2298 if (!tmpBounds.isValid()) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002299 info.touchableRegion.clear();
2300 // A layer could have invalid input bounds and still expect to receive touch input if it has
2301 // replaceTouchableRegionWithCrop. For that case, the input transform needs to be calculated
2302 // correctly to determine the coordinate space for input events. Use an empty rect so that
2303 // the layer will receive input in its own layer space.
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002304 tmpBounds = Rect::EMPTY_RECT;
chaviw7e72caf2020-12-02 16:50:43 -08002305 }
2306
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002307 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2308 // frame and transform used for the layer, which determines the bounds and the coordinate space
2309 // within which the layer will receive input.
2310 //
2311 // The coordinate space within which each of the bounds are specified is explicitly documented
2312 // in the variable name. For example "inputBoundsInLayer" is specified in layer space. A
2313 // Transform converts one coordinate space to another, which is apparent in its naming. For
2314 // example, "layerToDisplay" transforms layer space to display space.
2315 //
2316 // Coordinate space definitions:
2317 // - display: The display device's coordinate space. Correlates to pixels on the display.
2318 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2319 // - layer: The coordinate space of this layer.
2320 // - input: The coordinate space in which this layer will receive input events. This could be
2321 // different than layer space if a surfaceInset is used, which changes the origin
2322 // of the input space.
2323 const FloatRect inputBoundsInLayer = tmpBounds.toFloatRect();
chaviw7e72caf2020-12-02 16:50:43 -08002324
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002325 // Clamp surface inset to the input bounds.
2326 const auto surfaceInset = static_cast<float>(info.surfaceInset);
2327 const float xSurfaceInset =
2328 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getWidth() / 2.f));
2329 const float ySurfaceInset =
2330 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getHeight() / 2.f));
chaviw1ff3d1e2020-07-01 15:53:47 -07002331
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002332 // Apply the insets to the input bounds.
2333 const FloatRect insetBoundsInLayer(inputBoundsInLayer.left + xSurfaceInset,
2334 inputBoundsInLayer.top + ySurfaceInset,
2335 inputBoundsInLayer.right - xSurfaceInset,
2336 inputBoundsInLayer.bottom - ySurfaceInset);
Ady Abraham282f1d72019-07-24 18:05:56 -07002337
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002338 // Crop the input bounds to ensure it is within the parent's bounds.
2339 const FloatRect croppedInsetBoundsInLayer = mBounds.intersect(insetBoundsInLayer);
Ady Abraham282f1d72019-07-24 18:05:56 -07002340
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002341 const ui::Transform layerToScreen = getInputTransform();
2342 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
Vishnu Nair8033a492018-12-05 07:27:23 -08002343
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002344 const Rect roundedFrameInDisplay{layerToDisplay.transform(croppedInsetBoundsInLayer)};
2345 info.frameLeft = roundedFrameInDisplay.left;
2346 info.frameTop = roundedFrameInDisplay.top;
2347 info.frameRight = roundedFrameInDisplay.right;
2348 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002349
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002350 ui::Transform inputToLayer;
2351 inputToLayer.set(insetBoundsInLayer.left, insetBoundsInLayer.top);
2352 const ui::Transform inputToDisplay = layerToDisplay * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002353
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002354 // InputDispatcher expects a display-to-input transform.
2355 info.transform = inputToDisplay.inverse();
2356
2357 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002358 info.touchableRegion =
2359 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002360}
2361
chaviw3277faf2021-05-19 16:45:23 -05002362void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002363 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002364 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002365 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002366 }
2367 if (p != nullptr) {
2368 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2369 }
2370}
2371
Vishnu Naira066d902021-09-13 18:40:17 -07002372gui::DropInputMode Layer::getDropInputMode() const {
2373 gui::DropInputMode mode = mDrawingState.dropInputMode;
2374 if (mode == gui::DropInputMode::ALL) {
2375 return mode;
2376 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002377 sp<Layer> parent = mDrawingParent.promote();
2378 if (parent) {
2379 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002380 if (parentMode != gui::DropInputMode::NONE) {
2381 return parentMode;
2382 }
2383 }
2384 return mode;
2385}
2386
2387void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002388 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002389 return;
2390 }
2391
2392 // Check if we need to drop input unconditionally
2393 gui::DropInputMode dropInputMode = getDropInputMode();
2394 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002395 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002396 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2397 return;
2398 }
2399
2400 // Check if we need to check if the window is obscured by parent
2401 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2402 return;
2403 }
2404
2405 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002406 sp<Layer> parent = mDrawingParent.promote();
2407 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002408 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002409 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2410 static_cast<float>(getAlpha()));
2411 }
2412
2413 // Check if the parent has cropped the buffer
2414 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2415 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002416 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002417 return;
2418 }
2419
2420 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2421 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2422 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2423 // match then the layer has not been cropped by its parents.
2424 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2425 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2426
2427 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002428 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002429 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2430 getDebugName());
2431 } else {
2432 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2433 // input if the window is obscured. This check should be done in surfaceflinger but the
2434 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2435 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002436 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002437 }
2438}
2439
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002440WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002441 if (!hasInputInfo()) {
2442 mDrawingState.inputInfo.name = getName();
2443 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2444 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002445 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002446 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002447 }
2448
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002449 const ui::Transform& displayTransform =
2450 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2451
chaviw3277faf2021-05-19 16:45:23 -05002452 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002453 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002454 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002455
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002456 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002457
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002458 if (displayArgs.transform == nullptr) {
2459 // Do not let the window receive touches if it is not associated with a valid display
2460 // transform. We still allow the window to receive keys and prevent ANRs.
2461 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2462 }
2463
Robert Carr5dc426e2020-06-10 14:29:14 -07002464 // For compatibility reasons we let layers which can receive input
2465 // receive input before they have actually submitted a buffer. Because
2466 // of this we use canReceiveInput instead of isVisible to check the
2467 // policy-visibility, ignoring the buffer state. However for layers with
2468 // hasInputInfo()==false we can use the real visibility state.
2469 // We are just using these layers for occlusion detection in
2470 // InputDispatcher, and obviously if they aren't visible they can't occlude
2471 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002472 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2473 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2474
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002475 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002476 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002477 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002478
Vishnu Nair16a938f2021-09-24 07:14:54 -07002479 // If the window will be blacked out on a display because the display does not have the secure
2480 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002481 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002482 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002483 }
2484
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002485 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2486 if (info.replaceTouchableRegionWithCrop) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002487 const Rect bounds(cropLayer ? cropLayer->mScreenBounds : mScreenBounds);
2488 info.touchableRegion = Region(displayTransform.transform(bounds));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002489 } else if (cropLayer != nullptr) {
[1;3C2b9fc252021-02-04 16:16:50 -08002490 info.touchableRegion = info.touchableRegion.intersect(
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002491 displayTransform.transform(Rect{cropLayer->mScreenBounds}));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002492 }
2493
Winson Chunga30f7c92021-06-29 15:42:56 -07002494 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2495 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002496 if (isTrustedOverlay()) {
2497 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2498 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002499
chaviwaf87b3e2019-10-01 16:59:28 -07002500 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2501 // touches from going outside the cloned area.
2502 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002503 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002504 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2505 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002506 info.touchableRegion = info.touchableRegion.intersect(rect);
2507 }
2508 }
2509
Robert Carr720e5062018-07-30 17:45:14 -07002510 return info;
2511}
2512
chaviwaf87b3e2019-10-01 16:59:28 -07002513sp<Layer> Layer::getClonedRoot() {
2514 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002515 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002516 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002517 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002518 return nullptr;
2519 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002520 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002521}
2522
Robert Carredd13602020-04-13 17:24:34 -07002523bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002524 return mDrawingState.inputInfo.token != nullptr ||
2525 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002526}
2527
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002528compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002529 const DisplayDevice* display) const {
2530 if (!display) return nullptr;
Vishnu Naird47bcee2023-02-24 18:08:51 +00002531 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2532 return display->getCompositionDisplay()->getOutputLayerForLayer(
2533 getCompositionEngineLayerFE());
2534 }
2535 sp<LayerFE> layerFE;
2536 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2537 for (auto& [p, layer] : mLayerFEs) {
2538 if (p == path) {
2539 layerFE = layer;
2540 }
2541 }
2542
2543 if (!layerFE) return nullptr;
2544 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002545}
2546
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002547Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2548 const auto outputLayer = findOutputLayerForDisplay(display);
2549 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002550}
2551
chaviwb4c6e582019-08-16 14:35:07 -07002552void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002553 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002554 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002555 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2556 mPotentialCursor = clonedFrom->mPotentialCursor;
2557 mProtectedByApp = clonedFrom->mProtectedByApp;
2558 updateCloneBufferInfo();
2559}
2560
2561void Layer::updateCloneBufferInfo() {
2562 if (!isClone() || !isClonedFromAlive()) {
2563 return;
2564 }
2565
2566 sp<Layer> clonedFrom = getClonedFrom();
2567 mBufferInfo = clonedFrom->mBufferInfo;
2568 mSidebandStream = clonedFrom->mSidebandStream;
2569 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2570 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2571 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2572
2573 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2574 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2575 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2576 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2577 // the cloned drawingState again.
2578 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2579 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2580 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2581 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2582
2583 cloneDrawingState(clonedFrom.get());
2584
2585 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2586 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2587 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2588 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002589}
chaviw74b03172019-08-19 11:09:03 -07002590
2591void Layer::updateMirrorInfo() {
2592 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2593 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2594 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2595 // that case, we want to delete the reference to the clone since we want it to get
2596 // destroyed. The root, this layer, will still be around since the client can continue
2597 // to hold a reference, but no cloned layers will be displayed.
2598 mClonedChild = nullptr;
2599 return;
2600 }
2601
2602 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2603 // If the real layer exists and is in current state, add the clone as a child of the root.
2604 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2605 // copied to drawingState for the root layer. So the clonedChild is always removed from
2606 // drawingState and then needs to be added back each traversal.
2607 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2608 addChildToDrawing(mClonedChild);
2609 }
2610
2611 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002612 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002613 mClonedChild->updateClonedRelatives(clonedLayersMap);
2614}
2615
2616void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2617 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2618 // to the clone. If the real layer is no longer alive, continue traversing the children
2619 // since we may be able to pull out other children that are still alive.
2620 if (isClonedFromAlive()) {
2621 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002622 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002623 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002624 }
2625
2626 // The clone layer may have children in drawingState since they may have been created and
2627 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2628 // that already exist, since we can just re-use them.
2629 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2630 // not updated in the regular traversal. They are skipped since the root will lose the
2631 // reference to them when it copies its currentChildren to drawing.
2632 for (sp<Layer>& child : mDrawingChildren) {
2633 child->updateClonedDrawingState(clonedLayersMap);
2634 }
2635}
2636
2637void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2638 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2639 mDrawingChildren.clear();
2640
2641 if (!isClonedFromAlive()) {
2642 return;
2643 }
2644
2645 sp<Layer> clonedFrom = getClonedFrom();
2646 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2647 if (child == mirrorRoot) {
2648 // This is to avoid cyclical mirroring.
2649 continue;
2650 }
2651 sp<Layer> clonedChild = clonedLayersMap[child];
2652 if (clonedChild == nullptr) {
2653 clonedChild = child->createClone();
2654 clonedLayersMap[child] = clonedChild;
2655 }
2656 addChildToDrawing(clonedChild);
2657 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2658 }
2659}
2660
chaviwaf87b3e2019-10-01 16:59:28 -07002661void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2662 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2663 if (cropLayer != nullptr) {
2664 if (clonedLayersMap.count(cropLayer) == 0) {
2665 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2666 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002667 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002668 } else {
2669 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2670 mDrawingState.touchableRegionCrop = clonedCropLayer;
2671 }
2672 }
2673 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2674 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002675 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002676}
2677
2678void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002679 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002680 mDrawingState.zOrderRelatives.clear();
2681
2682 if (!isClonedFromAlive()) {
2683 return;
2684 }
2685
chaviwaf87b3e2019-10-01 16:59:28 -07002686 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002687 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002688 const sp<Layer>& relative = relativeWeak.promote();
2689 if (clonedLayersMap.count(relative) > 0) {
2690 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002691 mDrawingState.zOrderRelatives.add(clonedRelative);
2692 }
2693 }
2694
2695 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2696 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2697 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2698 // still traverse the children, but the layer with the missing relativeOf will not be shown
2699 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002700 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2701 if (clonedLayersMap.count(relativeOf) > 0) {
2702 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002703 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2704 }
2705
chaviwaf87b3e2019-10-01 16:59:28 -07002706 updateClonedInputInfo(clonedLayersMap);
2707
chaviw74b03172019-08-19 11:09:03 -07002708 for (sp<Layer>& child : mDrawingChildren) {
2709 child->updateClonedRelatives(clonedLayersMap);
2710 }
2711}
2712
2713void Layer::addChildToDrawing(const sp<Layer>& layer) {
2714 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002715 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002716}
2717
Steven Thomas62a4cf82020-01-31 12:04:03 -08002718Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2719 switch (compatibility) {
2720 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2721 return FrameRateCompatibility::Default;
2722 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2723 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002724 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2725 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002726 case ANATIVEWINDOW_FRAME_RATE_MIN:
2727 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002728 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2729 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002730 default:
2731 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2732 return FrameRateCompatibility::Default;
2733 }
2734}
2735
Marin Shalamanovc5986772021-03-16 16:09:49 +01002736scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2737 switch (strategy) {
2738 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2739 return Seamlessness::OnlySeamless;
2740 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2741 return Seamlessness::SeamedAndSeamless;
2742 default:
2743 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2744 return Seamlessness::Default;
2745 }
2746}
2747
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002748bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002749 const State& s(mDrawingState);
2750 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2751 return true;
2752 }
2753
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002754 sp<Layer> parent = mDrawingParent.promote();
2755 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002756}
2757
Robert Carr6a0382d2021-07-01 15:57:17 -07002758void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2759 mClonedChild = clonedChild;
2760 mHadClonedChild = true;
2761 mFlinger->mNumClones++;
2762}
2763
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002764bool Layer::setDropInputMode(gui::DropInputMode mode) {
2765 if (mDrawingState.dropInputMode == mode) {
2766 return false;
2767 }
2768 mDrawingState.dropInputMode = mode;
2769 return true;
2770}
2771
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002772void Layer::cloneDrawingState(const Layer* from) {
2773 mDrawingState = from->mDrawingState;
2774 // Skip callback info since they are not applicable for cloned layers.
2775 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002776 // TODO (b/238781169) currently broken for mirror layers because we do not
2777 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002778 mDrawingState.callbackHandles = {};
2779}
2780
Patrick Williamsbb25f802022-08-30 23:02:34 +00002781void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2782 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002783 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002784 if (!listener) {
2785 return;
2786 }
2787 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002788 uint32_t currentMaxAcquiredBufferCount =
2789 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002790 listener->onReleaseBuffer({buffer->getId(), framenumber},
2791 releaseFence ? releaseFence : Fence::NO_FENCE,
2792 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002793}
2794
2795void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2796 // If we are displayed on multiple displays in a single composition cycle then we would
2797 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2798 // For example we can only use it if all the displays are client comp, and we need
2799 // to merge all the client comp fences. We could do this, but for now we just
2800 // disable the optimization when a layer is composed on multiple displays.
2801 if (mClearClientCompositionFenceOnLayerDisplayed) {
2802 mLastClientCompositionFence = nullptr;
2803 } else {
2804 mClearClientCompositionFenceOnLayerDisplayed = true;
2805 }
2806
2807 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2808 // buffer that was presented on this layer. The first transaction that came in this frame that
2809 // replaced the previous buffer on this layer needs this release fence, because the fence will
2810 // let the client know when that previous buffer is removed from the screen.
2811 //
2812 // Every other transaction on this layer does not need a release fence because no other
2813 // Transactions that were set on this layer this frame are going to have their preceding buffer
2814 // removed from the display this frame.
2815 //
2816 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2817 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2818 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2819 // the previous buffer will be released this frame. The third transaction also contains a
2820 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2821 // transaction will now no longer be presented so it is released immediately and the third
2822 // transaction doesn't need a previous release fence.
2823 sp<CallbackHandle> ch;
2824 for (auto& handle : mDrawingState.callbackHandles) {
2825 if (handle->releasePreviousBuffer &&
2826 mDrawingState.releaseBufferEndpoint == handle->listener) {
2827 ch = handle;
2828 break;
2829 }
2830 }
2831
2832 // Prevent tracing the same release multiple times.
2833 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2834 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2835 }
2836
2837 if (ch != nullptr) {
2838 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2839 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2840 ch->name = mName;
2841 }
2842}
2843
2844void Layer::onSurfaceFrameCreated(
2845 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2846 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2847 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2848 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2849 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002850 if (hasBufferOrSidebandStreamInDrawing()) {
2851 // Only log for layers with a buffer, since we expect the jank data to be drained for
2852 // these, while there may be no jank listeners for bufferless layers.
2853 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2854 mName.c_str());
2855 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2856 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2857 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002858 mPendingJankClassifications.pop_front();
2859 }
2860 mPendingJankClassifications.emplace_back(surfaceFrame);
2861}
2862
2863void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2864 for (const auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair71fcf912022-10-18 09:14:20 -07002865 handle->transformHint = mSkipReportingTransformHint
2866 ? std::nullopt
2867 : std::make_optional<uint32_t>(mTransformHint);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002868 handle->dequeueReadyTime = dequeueReadyTime;
2869 handle->currentMaxAcquiredBufferCount =
2870 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2871 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2872 handle->previousReleaseCallbackId.framenumber);
2873 }
2874
2875 for (auto& handle : mDrawingState.callbackHandles) {
2876 if (handle->releasePreviousBuffer &&
2877 mDrawingState.releaseBufferEndpoint == handle->listener) {
2878 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2879 break;
2880 }
2881 }
2882
2883 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002884 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002885 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2886 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002887 mDrawingState.callbackHandles = {};
2888}
2889
2890bool Layer::willPresentCurrentTransaction() const {
2891 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2892 return (getSidebandStreamChanged() || getAutoRefresh() ||
2893 (mDrawingState.modified &&
2894 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2895}
2896
2897bool Layer::setTransform(uint32_t transform) {
2898 if (mDrawingState.bufferTransform == transform) return false;
2899 mDrawingState.bufferTransform = transform;
2900 mDrawingState.modified = true;
2901 setTransactionFlags(eTransactionNeeded);
2902 return true;
2903}
2904
2905bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2906 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2907 mDrawingState.sequence++;
2908 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2909 mDrawingState.modified = true;
2910 setTransactionFlags(eTransactionNeeded);
2911 return true;
2912}
2913
2914bool Layer::setBufferCrop(const Rect& bufferCrop) {
2915 if (mDrawingState.bufferCrop == bufferCrop) return false;
2916
2917 mDrawingState.sequence++;
2918 mDrawingState.bufferCrop = bufferCrop;
2919
2920 mDrawingState.modified = true;
2921 setTransactionFlags(eTransactionNeeded);
2922 return true;
2923}
2924
2925bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2926 if (mDrawingState.destinationFrame == destinationFrame) return false;
2927
2928 mDrawingState.sequence++;
2929 mDrawingState.destinationFrame = destinationFrame;
2930
2931 mDrawingState.modified = true;
2932 setTransactionFlags(eTransactionNeeded);
2933 return true;
2934}
2935
2936// Translate destination frame into scale and position. If a destination frame is not set, use the
2937// provided scale and position
2938bool Layer::updateGeometry() {
2939 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2940 mDrawingState.destinationFrame.isEmpty()) {
2941 // If destination frame is not set, use the requested transform set via
2942 // Layer::setPosition and Layer::setMatrix.
2943 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2944 }
2945
2946 Rect destRect = mDrawingState.destinationFrame;
2947 int32_t destW = destRect.width();
2948 int32_t destH = destRect.height();
2949 if (destRect.left < 0) {
2950 destRect.left = 0;
2951 destRect.right = destW;
2952 }
2953 if (destRect.top < 0) {
2954 destRect.top = 0;
2955 destRect.bottom = destH;
2956 }
2957
2958 if (!mDrawingState.buffer) {
2959 ui::Transform t;
2960 t.set(destRect.left, destRect.top);
2961 return assignTransform(&mDrawingState.transform, t);
2962 }
2963
2964 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2965 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2966 // Undo any transformations on the buffer.
2967 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2968 std::swap(bufferWidth, bufferHeight);
2969 }
2970 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
2971 if (mDrawingState.transformToDisplayInverse) {
2972 if (invTransform & ui::Transform::ROT_90) {
2973 std::swap(bufferWidth, bufferHeight);
2974 }
2975 }
2976
2977 float sx = destW / static_cast<float>(bufferWidth);
2978 float sy = destH / static_cast<float>(bufferHeight);
2979 ui::Transform t;
2980 t.set(sx, 0, 0, sy);
2981 t.set(destRect.left, destRect.top);
2982 return assignTransform(&mDrawingState.transform, t);
2983}
2984
2985bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
2986 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
2987 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
2988 return false;
2989 }
2990
2991 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
2992
2993 mDrawingState.sequence++;
2994 mDrawingState.modified = true;
2995 setTransactionFlags(eTransactionNeeded);
2996
2997 return true;
2998}
2999
3000bool Layer::setPosition(float x, float y) {
3001 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3002 return false;
3003 }
3004
3005 mRequestedTransform.set(x, y);
3006
3007 mDrawingState.sequence++;
3008 mDrawingState.modified = true;
3009 setTransactionFlags(eTransactionNeeded);
3010
3011 return true;
3012}
3013
3014bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3015 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3016 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003017 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003018 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003019 if (!buffer) {
3020 return false;
3021 }
3022
3023 const bool frameNumberChanged =
3024 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3025 const uint64_t frameNumber =
3026 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003027 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003028
3029 if (mDrawingState.buffer) {
3030 mReleasePreviousBuffer = true;
3031 if (!mBufferInfo.mBuffer ||
3032 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3033 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3034 // If mDrawingState has a buffer, and we are about to update again
3035 // before swapping to drawing state, then the first buffer will be
3036 // dropped and we should decrement the pending buffer count and
3037 // call any release buffer callbacks if set.
3038 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3039 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003040 mDrawingState.acquireFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003041 decrementPendingBufferCount();
3042 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3043 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3044 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
3045 mDrawingState.bufferSurfaceFrameTX.reset();
3046 }
3047 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3048 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3049 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003050 mLastClientCompositionFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003051 mLastClientCompositionFence = nullptr;
3052 }
Vishnu Nairc09c0232023-03-02 03:22:35 +00003053 } else {
3054 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3055 // we don't want to incorrectly classify a frame if we miss the desired present time.
3056 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003057 }
3058
liulijuneb489f62022-10-17 22:02:14 +08003059 mDrawingState.producerId = bufferData.producerId;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003060 mDrawingState.frameNumber = frameNumber;
3061 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3062 mDrawingState.buffer = std::move(buffer);
3063 mDrawingState.clientCacheId = bufferData.cachedBuffer;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003064 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3065 ? bufferData.acquireFence
3066 : Fence::NO_FENCE;
3067 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3068 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3069 // We latched this buffer unsiganled, so we need to pass the acquire fence
3070 // on the callback instead of just the acquire time, since it's unknown at
3071 // this point.
3072 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3073 } else {
3074 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3075 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003076 mDrawingState.latchedVsyncId = info.vsyncId;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003077 mDrawingState.modified = true;
3078 setTransactionFlags(eTransactionNeeded);
3079
3080 const int32_t layerId = getSequence();
3081 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3082 mOwnerUid, postTime, getGameMode());
3083 mDrawingState.desiredPresentTime = desiredPresentTime;
3084 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3085
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003086 if (mFlinger->mLegacyFrontEndEnabled) {
3087 recordLayerHistoryBufferUpdate(getLayerProps());
3088 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003089
3090 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3091
3092 if (dequeueTime && *dequeueTime != 0) {
3093 const uint64_t bufferId = mDrawingState.buffer->getId();
3094 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3095 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3096 FrameTracer::FrameEvent::DEQUEUE);
3097 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3098 FrameTracer::FrameEvent::QUEUE);
3099 }
3100
3101 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3102 return true;
3103}
3104
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003105void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3106 mDrawingState.desiredPresentTime = desiredPresentTime;
3107 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3108}
3109
3110void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps) {
3111 const nsecs_t presentTime = [&] {
3112 if (!mDrawingState.isAutoTimestamp) return mDrawingState.desiredPresentTime;
3113
3114 const auto prediction = mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3115 mDrawingState.latchedVsyncId);
3116 if (prediction.has_value()) return prediction->presentTime;
3117
3118 return static_cast<nsecs_t>(0);
3119 }();
3120 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3121 scheduler::LayerHistory::LayerUpdateType::Buffer);
3122}
3123
3124void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps) {
3125 const nsecs_t presentTime =
3126 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
3127 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3128 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3129}
3130
Patrick Williamsbb25f802022-08-30 23:02:34 +00003131bool Layer::setDataspace(ui::Dataspace dataspace) {
3132 mDrawingState.dataspaceRequested = true;
3133 if (mDrawingState.dataspace == dataspace) return false;
3134 mDrawingState.dataspace = dataspace;
3135 mDrawingState.modified = true;
3136 setTransactionFlags(eTransactionNeeded);
3137 return true;
3138}
3139
John Reck68796592023-01-25 13:47:12 -05003140bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
3141 if (mDrawingState.currentSdrHdrRatio == currentBufferRatio &&
3142 mDrawingState.desiredSdrHdrRatio == desiredRatio)
3143 return false;
3144 mDrawingState.currentSdrHdrRatio = currentBufferRatio;
3145 mDrawingState.desiredSdrHdrRatio = desiredRatio;
3146 mDrawingState.modified = true;
3147 setTransactionFlags(eTransactionNeeded);
3148 return true;
3149}
3150
Alec Mourif4af03e2023-02-11 00:25:24 +00003151bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3152 if (mDrawingState.cachingHint == cachingHint) return false;
3153 mDrawingState.cachingHint = cachingHint;
3154 mDrawingState.modified = true;
3155 setTransactionFlags(eTransactionNeeded);
3156 return true;
3157}
3158
Patrick Williamsbb25f802022-08-30 23:02:34 +00003159bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3160 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3161 mDrawingState.hdrMetadata = hdrMetadata;
3162 mDrawingState.modified = true;
3163 setTransactionFlags(eTransactionNeeded);
3164 return true;
3165}
3166
3167bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
3168 mDrawingState.surfaceDamageRegion = surfaceDamage;
3169 mDrawingState.modified = true;
3170 setTransactionFlags(eTransactionNeeded);
3171 return true;
3172}
3173
3174bool Layer::setApi(int32_t api) {
3175 if (mDrawingState.api == api) return false;
3176 mDrawingState.api = api;
3177 mDrawingState.modified = true;
3178 setTransactionFlags(eTransactionNeeded);
3179 return true;
3180}
3181
3182bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3183 if (mDrawingState.sidebandStream == sidebandStream) return false;
3184
3185 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3186 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3187 } else if (sidebandStream != nullptr) {
3188 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3189 }
3190
3191 mDrawingState.sidebandStream = sidebandStream;
3192 mDrawingState.modified = true;
3193 setTransactionFlags(eTransactionNeeded);
3194 if (!mSidebandStreamChanged.exchange(true)) {
3195 // mSidebandStreamChanged was false
3196 mFlinger->onLayerUpdate();
3197 }
3198 return true;
3199}
3200
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003201bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3202 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003203 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3204 if (handles.empty()) {
3205 mReleasePreviousBuffer = false;
3206 return false;
3207 }
3208
Pascal Muetschard81cef292023-02-06 12:18:52 +01003209 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003210 for (const auto& handle : handles) {
3211 // If this transaction set a buffer on this layer, release its previous buffer
3212 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3213
3214 // If this layer will be presented in this frame
3215 if (willPresent) {
3216 // If this transaction set an acquire fence on this layer, set its acquire time
3217 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3218 handle->frameNumber = mDrawingState.frameNumber;
3219
3220 // Store so latched time and release fence can be set
3221 mDrawingState.callbackHandles.push_back(handle);
3222
3223 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003224 // Queue this handle to be notified below.
3225 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003226 }
3227 }
3228
Pascal Muetschard81cef292023-02-06 12:18:52 +01003229 if (!remainingHandles.empty()) {
3230 // Notify the transaction completed threads these handles are done. These are only the
3231 // handles that were not added to the mDrawingState, which will be notified later.
3232 std::vector<JankData> jankData;
3233 transferAvailableJankData(remainingHandles, jankData);
3234 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3235 }
3236
Patrick Williamsbb25f802022-08-30 23:02:34 +00003237 mReleasePreviousBuffer = false;
3238 mCallbackHandleAcquireTimeOrFence = -1;
3239
3240 return willPresent;
3241}
3242
3243Rect Layer::getBufferSize(const State& /*s*/) const {
3244 // for buffer state layers we use the display frame size as the buffer size.
3245
3246 if (mBufferInfo.mBuffer == nullptr) {
3247 return Rect::INVALID_RECT;
3248 }
3249
3250 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3251 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3252
3253 // Undo any transformations on the buffer and return the result.
3254 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3255 std::swap(bufWidth, bufHeight);
3256 }
3257
3258 if (getTransformToDisplayInverse()) {
3259 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3260 if (invTransform & ui::Transform::ROT_90) {
3261 std::swap(bufWidth, bufHeight);
3262 }
3263 }
3264
3265 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3266}
3267
3268FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3269 if (mBufferInfo.mBuffer == nullptr) {
3270 return parentBounds;
3271 }
3272
3273 return getBufferSize(getDrawingState()).toFloatRect();
3274}
3275
3276bool Layer::fenceHasSignaled() const {
3277 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3278 return true;
3279 }
3280
3281 const bool fenceSignaled =
3282 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3283 if (!fenceSignaled) {
3284 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3285 TimeStats::LatchSkipReason::LateAcquire);
3286 }
3287
3288 return fenceSignaled;
3289}
3290
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003291void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003292 for (const auto& handle : mDrawingState.callbackHandles) {
3293 handle->refreshStartTime = refreshStartTime;
3294 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003295}
3296
3297void Layer::setAutoRefresh(bool autoRefresh) {
3298 mDrawingState.autoRefresh = autoRefresh;
3299}
3300
3301bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3302 // 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 +00003303 auto* snapshot = editLayerSnapshot();
3304 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003305
3306 if (mSidebandStreamChanged.exchange(false)) {
3307 const State& s(getDrawingState());
3308 // mSidebandStreamChanged was true
3309 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003310 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003311 if (mSidebandStream != nullptr) {
3312 setTransactionFlags(eTransactionNeeded);
3313 mFlinger->setTransactionFlags(eTraversalNeeded);
3314 }
3315 recomputeVisibleRegions = true;
3316
3317 return true;
3318 }
3319 return false;
3320}
3321
3322bool Layer::hasFrameUpdate() const {
3323 const State& c(getDrawingState());
3324 return (mDrawingStateModified || mDrawingState.modified) &&
3325 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3326}
3327
Vishnu Naird47bcee2023-02-24 18:08:51 +00003328void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003329 const State& s(getDrawingState());
3330
3331 if (!s.buffer) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003332 if (bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003333 for (auto& handle : mDrawingState.callbackHandles) {
3334 handle->latchTime = latchTime;
3335 }
3336 }
3337 return;
3338 }
3339
3340 for (auto& handle : mDrawingState.callbackHandles) {
3341 if (handle->frameNumber == mDrawingState.frameNumber) {
3342 handle->latchTime = latchTime;
3343 }
3344 }
3345
3346 const int32_t layerId = getSequence();
3347 const uint64_t bufferId = mDrawingState.buffer->getId();
3348 const uint64_t frameNumber = mDrawingState.frameNumber;
3349 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3350 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3351 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3352
3353 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3354 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3355 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3356 FrameTracer::FrameEvent::LATCH);
3357
3358 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3359 if (bufferSurfaceFrame != nullptr &&
3360 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3361 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3362 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3363 // are processing the next state.
3364 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3365 mDrawingState.acquireFenceTime->getSignalTime(),
3366 latchTime);
3367 mDrawingState.bufferSurfaceFrameTX.reset();
3368 }
3369
3370 std::deque<sp<CallbackHandle>> remainingHandles;
3371 mFlinger->getTransactionCallbackInvoker()
3372 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3373 mDrawingState.callbackHandles = remainingHandles;
3374
3375 mDrawingStateModified = false;
3376}
3377
3378void Layer::gatherBufferInfo() {
3379 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3380 decrementPendingBufferCount();
3381 }
3382
3383 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3384 mBufferInfo.mBuffer = mDrawingState.buffer;
3385 mBufferInfo.mFence = mDrawingState.acquireFence;
3386 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3387 mBufferInfo.mPixelFormat =
3388 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3389 mBufferInfo.mFrameLatencyNeeded = true;
3390 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3391 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3392 mBufferInfo.mFence = mDrawingState.acquireFence;
3393 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3394 auto lastDataspace = mBufferInfo.mDataspace;
3395 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3396 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003397 mFlinger->mHdrLayerInfoChanged = true;
3398 }
3399 if (mBufferInfo.mDesiredSdrHdrRatio != mDrawingState.desiredSdrHdrRatio) {
3400 mBufferInfo.mDesiredSdrHdrRatio = mDrawingState.desiredSdrHdrRatio;
3401 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003402 }
3403 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3404 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3405 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3406 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3407 mBufferInfo.mApi = mDrawingState.api;
3408 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003409}
3410
3411Rect Layer::computeBufferCrop(const State& s) {
3412 if (s.buffer && !s.bufferCrop.isEmpty()) {
3413 Rect bufferCrop;
3414 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3415 return bufferCrop;
3416 } else if (s.buffer) {
3417 return s.buffer->getBounds();
3418 } else {
3419 return s.bufferCrop;
3420 }
3421}
3422
3423sp<Layer> Layer::createClone() {
3424 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3425 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003426 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003427 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3428 return layer;
3429}
3430
Patrick Williamsbb25f802022-08-30 23:02:34 +00003431void Layer::decrementPendingBufferCount() {
3432 int32_t pendingBuffers = --mPendingBufferTransactions;
3433 tracePendingBufferCount(pendingBuffers);
3434}
3435
3436void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3437 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3438}
3439
3440/*
3441 * We don't want to send the layer's transform to input, but rather the
3442 * parent's transform. This is because Layer's transform is
3443 * information about how the buffer is placed on screen. The parent's
3444 * transform makes more sense to send since it's information about how the
3445 * layer is placed on screen. This transform is used by input to determine
3446 * how to go from screen space back to window space.
3447 */
3448ui::Transform Layer::getInputTransform() const {
3449 if (!hasBufferOrSidebandStream()) {
3450 return getTransform();
3451 }
3452 sp<Layer> parent = mDrawingParent.promote();
3453 if (parent == nullptr) {
3454 return ui::Transform();
3455 }
3456
3457 return parent->getTransform();
3458}
3459
3460/**
3461 * Similar to getInputTransform, we need to update the bounds to include the transform.
3462 * This is because bounds don't include the buffer transform, where the input assumes
3463 * that's already included.
3464 */
3465Rect Layer::getInputBounds() const {
3466 if (!hasBufferOrSidebandStream()) {
3467 return getCroppedBufferSize(getDrawingState());
3468 }
3469
3470 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
3471 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
3472 return bufferBounds;
3473 }
3474 return mDrawingState.transform.transform(bufferBounds);
3475}
3476
3477bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3478 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3479
3480 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3481 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3482 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3483 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3484 layer_state_t::eReparent;
3485
3486 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3487 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3488 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3489 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3490 layer_state_t::eInputInfoChanged;
3491
3492 if ((s.what & requiredFlags) != requiredFlags) {
3493 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3494 (s.what | requiredFlags) & ~s.what);
3495 return false;
3496 }
3497
3498 if (s.what & deniedFlags) {
3499 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3500 return false;
3501 }
3502
3503 if (s.what & allowedFlags) {
3504 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3505 }
3506
3507 if (s.what & layer_state_t::ePositionChanged) {
3508 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3509 ALOGV("%s: false [ePositionChanged changed]", __func__);
3510 return false;
3511 }
3512 }
3513
3514 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003515 if (mDrawingState.color.a != s.color.a) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003516 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3517 return false;
3518 }
3519 }
3520
3521 if (s.what & layer_state_t::eColorTransformChanged) {
3522 if (mDrawingState.colorTransform != s.colorTransform) {
3523 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3524 return false;
3525 }
3526 }
3527
3528 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003529 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003530 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3531 return false;
3532 }
3533 }
3534
3535 if (s.what & layer_state_t::eMatrixChanged) {
3536 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3537 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3538 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3539 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3540 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3541 return false;
3542 }
3543 }
3544
3545 if (s.what & layer_state_t::eCornerRadiusChanged) {
3546 if (mDrawingState.cornerRadius != s.cornerRadius) {
3547 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3548 return false;
3549 }
3550 }
3551
3552 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3553 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3554 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3555 return false;
3556 }
3557 }
3558
Vishnu Nairbbceb462022-10-10 04:52:13 +00003559 if (s.what & layer_state_t::eBufferTransformChanged) {
3560 if (mDrawingState.bufferTransform != s.bufferTransform) {
3561 ALOGV("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003562 return false;
3563 }
3564 }
3565
3566 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3567 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3568 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3569 return false;
3570 }
3571 }
3572
3573 if (s.what & layer_state_t::eCropChanged) {
3574 if (mDrawingState.crop != s.crop) {
3575 ALOGV("%s: false [eCropChanged changed]", __func__);
3576 return false;
3577 }
3578 }
3579
3580 if (s.what & layer_state_t::eDataspaceChanged) {
3581 if (mDrawingState.dataspace != s.dataspace) {
3582 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3583 return false;
3584 }
3585 }
3586
3587 if (s.what & layer_state_t::eHdrMetadataChanged) {
3588 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3589 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3590 return false;
3591 }
3592 }
3593
3594 if (s.what & layer_state_t::eSidebandStreamChanged) {
3595 if (mDrawingState.sidebandStream != s.sidebandStream) {
3596 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3597 return false;
3598 }
3599 }
3600
3601 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3602 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3603 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3604 return false;
3605 }
3606 }
3607
3608 if (s.what & layer_state_t::eShadowRadiusChanged) {
3609 if (mDrawingState.shadowRadius != s.shadowRadius) {
3610 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3611 return false;
3612 }
3613 }
3614
3615 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3616 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3617 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3618 return false;
3619 }
3620 }
3621
3622 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3623 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3624 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3625 return false;
3626 }
3627 }
3628
3629 if (s.what & layer_state_t::eStretchChanged) {
3630 StretchEffect temp = s.stretchEffect;
3631 temp.sanitize();
3632 if (mDrawingState.stretchEffect != temp) {
3633 ALOGV("%s: false [eStretchChanged changed]", __func__);
3634 return false;
3635 }
3636 }
3637
3638 if (s.what & layer_state_t::eBufferCropChanged) {
3639 if (mDrawingState.bufferCrop != s.bufferCrop) {
3640 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3641 return false;
3642 }
3643 }
3644
3645 if (s.what & layer_state_t::eDestinationFrameChanged) {
3646 if (mDrawingState.destinationFrame != s.destinationFrame) {
3647 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3648 return false;
3649 }
3650 }
3651
3652 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3653 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3654 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3655 return false;
3656 }
3657 }
3658
John Reck68796592023-01-25 13:47:12 -05003659 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
3660 if (mDrawingState.currentSdrHdrRatio != s.currentSdrHdrRatio ||
3661 mDrawingState.desiredSdrHdrRatio != s.desiredSdrHdrRatio) {
3662 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3663 return false;
3664 }
3665 }
3666
Patrick Williamsbb25f802022-08-30 23:02:34 +00003667 ALOGV("%s: true", __func__);
3668 return true;
3669}
3670
3671bool Layer::isHdrY410() const {
3672 // pixel format is HDR Y410 masquerading as RGBA_1010102
3673 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3674 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3675 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3676}
3677
Vishnu Naire14c6b32022-08-06 04:20:15 +00003678sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003679 // There's no need to get a CE Layer if the layer isn't going to draw anything.
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003680 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003681}
3682
Vishnu Naire14c6b32022-08-06 04:20:15 +00003683const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003684 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003685}
3686
Vishnu Naire14c6b32022-08-06 04:20:15 +00003687LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003688 return mSnapshot.get();
3689}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003690
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003691std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3692 return std::move(mSnapshot);
3693}
3694
3695void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3696 mSnapshot = std::move(snapshot);
3697}
3698
Patrick Williamsbb25f802022-08-30 23:02:34 +00003699const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003700 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003701}
3702
Patrick Williams7584c6a2022-10-29 02:10:58 +00003703sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003704 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003705 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3706 return result;
3707}
3708
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003709sp<LayerFE> Layer::getCompositionEngineLayerFE(
3710 const frontend::LayerHierarchy::TraversalPath& path) {
3711 for (auto& [p, layerFE] : mLayerFEs) {
3712 if (p == path) {
3713 return layerFE;
3714 }
3715 }
3716 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3717 mLayerFEs.emplace_back(path, layerFE);
3718 return layerFE;
3719}
3720
Patrick Williamsbb25f802022-08-30 23:02:34 +00003721void Layer::useSurfaceDamage() {
3722 if (mFlinger->mForceFullDamage) {
3723 surfaceDamageRegion = Region::INVALID_REGION;
3724 } else {
3725 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3726 }
3727}
3728
3729void Layer::useEmptyDamage() {
3730 surfaceDamageRegion.clear();
3731}
3732
3733bool Layer::isOpaque(const Layer::State& s) const {
3734 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3735 // layer's opaque flag.
3736 if (!hasSomethingToDraw()) {
3737 return false;
3738 }
3739
3740 // if the layer has the opaque flag, then we're always opaque
3741 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3742 return true;
3743 }
3744
3745 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003746 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003747 return true;
3748 }
3749
3750 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3751 return fillsColor() && getAlpha() == 1.0_hf;
3752}
3753
3754bool Layer::canReceiveInput() const {
3755 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3756}
3757
3758bool Layer::isVisible() const {
3759 if (!hasSomethingToDraw()) {
3760 return false;
3761 }
3762
3763 if (isHiddenByPolicy()) {
3764 return false;
3765 }
3766
3767 return getAlpha() > 0.0f || hasBlur();
3768}
3769
3770void Layer::onPostComposition(const DisplayDevice* display,
3771 const std::shared_ptr<FenceTime>& glDoneFence,
3772 const std::shared_ptr<FenceTime>& presentFence,
3773 const CompositorTiming& compositorTiming) {
3774 // mFrameLatencyNeeded is true when a new frame was latched for the
3775 // composition.
3776 if (!mBufferInfo.mFrameLatencyNeeded) return;
3777
3778 for (const auto& handle : mDrawingState.callbackHandles) {
3779 handle->gpuCompositionDoneFence = glDoneFence;
3780 handle->compositorTiming = compositorTiming;
3781 }
3782
3783 // Update mFrameTracker.
3784 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3785 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3786
3787 const int32_t layerId = getSequence();
3788 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3789
3790 const auto outputLayer = findOutputLayerForDisplay(display);
3791 if (outputLayer && outputLayer->requiresClientComposition()) {
3792 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3793 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3794 clientCompositionTimestamp,
3795 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3796 // Update the SurfaceFrames in the drawing state
3797 if (mDrawingState.bufferSurfaceFrameTX) {
3798 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3799 }
3800 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3801 surfaceFrame->setGpuComposition();
3802 }
3803 }
3804
3805 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3806 if (frameReadyFence->isValid()) {
3807 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3808 } else {
3809 // There was no fence for this frame, so assume that it was ready
3810 // to be presented at the desired present time.
3811 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3812 }
3813
3814 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08003815 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003816 const std::optional<Fps> renderRate =
3817 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3818
3819 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3820 const auto gameMode = getGameMode();
3821
3822 if (presentFence->isValid()) {
3823 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3824 refreshRate, renderRate, vote, gameMode);
3825 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3826 presentFence,
3827 FrameTracer::FrameEvent::PRESENT_FENCE);
3828 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3829 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3830 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003831 // The HWC doesn't support present fences, so use the present timestamp instead.
3832 const nsecs_t presentTimestamp =
3833 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3834
3835 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3836 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3837 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3838
Patrick Williamsbb25f802022-08-30 23:02:34 +00003839 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3840 refreshRate, renderRate, vote, gameMode);
3841 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3842 mCurrentFrameNumber, actualPresentTime,
3843 FrameTracer::FrameEvent::PRESENT_FENCE);
3844 mFrameTracker.setActualPresentTime(actualPresentTime);
3845 }
3846 }
3847
3848 mFrameTracker.advanceFrame();
3849 mBufferInfo.mFrameLatencyNeeded = false;
3850}
3851
3852bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003853 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
3854 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
3855}
3856
3857bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003858 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3859 getDrawingState().frameNumber);
3860
3861 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3862
3863 if (refreshRequired) {
3864 return refreshRequired;
3865 }
3866
3867 // If the head buffer's acquire fence hasn't signaled yet, return and
3868 // try again later
3869 if (!fenceHasSignaled()) {
3870 ATRACE_NAME("!fenceHasSignaled()");
3871 mFlinger->onLayerUpdate();
3872 return false;
3873 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00003874 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003875 if (mDrawingState.buffer == nullptr) {
3876 return false;
3877 }
3878
3879 // Capture the old state of the layer for comparisons later
3880 BufferInfo oldBufferInfo = mBufferInfo;
3881 const bool oldOpacity = isOpaque(mDrawingState);
3882 mPreviousFrameNumber = mCurrentFrameNumber;
3883 mCurrentFrameNumber = mDrawingState.frameNumber;
3884 gatherBufferInfo();
3885
3886 if (oldBufferInfo.mBuffer == nullptr) {
3887 // the first time we receive a buffer, we need to trigger a
3888 // geometry invalidation.
3889 recomputeVisibleRegions = true;
3890 }
3891
3892 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3893 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3894 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3895 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3896 recomputeVisibleRegions = true;
3897 }
3898
3899 if (oldBufferInfo.mBuffer != nullptr) {
3900 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3901 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3902 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3903 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3904 recomputeVisibleRegions = true;
3905 }
3906 }
3907
3908 if (oldOpacity != isOpaque(mDrawingState)) {
3909 recomputeVisibleRegions = true;
3910 }
3911
3912 return true;
3913}
3914
3915bool Layer::hasReadyFrame() const {
3916 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
3917}
3918
3919bool Layer::isProtected() const {
3920 return (mBufferInfo.mBuffer != nullptr) &&
3921 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
3922}
3923
Patrick Williamsbb25f802022-08-30 23:02:34 +00003924void Layer::latchAndReleaseBuffer() {
3925 if (hasReadyFrame()) {
3926 bool ignored = false;
3927 latchBuffer(ignored, systemTime());
3928 }
3929 releasePendingBuffer(systemTime());
3930}
3931
3932PixelFormat Layer::getPixelFormat() const {
3933 return mBufferInfo.mPixelFormat;
3934}
3935
3936bool Layer::getTransformToDisplayInverse() const {
3937 return mBufferInfo.mTransformToDisplayInverse;
3938}
3939
3940Rect Layer::getBufferCrop() const {
3941 // this is the crop rectangle that applies to the buffer
3942 // itself (as opposed to the window)
3943 if (!mBufferInfo.mCrop.isEmpty()) {
3944 // if the buffer crop is defined, we use that
3945 return mBufferInfo.mCrop;
3946 } else if (mBufferInfo.mBuffer != nullptr) {
3947 // otherwise we use the whole buffer
3948 return mBufferInfo.mBuffer->getBounds();
3949 } else {
3950 // if we don't have a buffer yet, we use an empty/invalid crop
3951 return Rect();
3952 }
3953}
3954
3955uint32_t Layer::getBufferTransform() const {
3956 return mBufferInfo.mTransform;
3957}
3958
3959ui::Dataspace Layer::getDataSpace() const {
3960 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
3961}
3962
3963ui::Dataspace Layer::getRequestedDataSpace() const {
3964 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
3965}
3966
3967ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
3968 ui::Dataspace updatedDataspace = dataspace;
3969 // translate legacy dataspaces to modern dataspaces
3970 switch (dataspace) {
3971 case ui::Dataspace::SRGB:
3972 updatedDataspace = ui::Dataspace::V0_SRGB;
3973 break;
3974 case ui::Dataspace::SRGB_LINEAR:
3975 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
3976 break;
3977 case ui::Dataspace::JFIF:
3978 updatedDataspace = ui::Dataspace::V0_JFIF;
3979 break;
3980 case ui::Dataspace::BT601_625:
3981 updatedDataspace = ui::Dataspace::V0_BT601_625;
3982 break;
3983 case ui::Dataspace::BT601_525:
3984 updatedDataspace = ui::Dataspace::V0_BT601_525;
3985 break;
3986 case ui::Dataspace::BT709:
3987 updatedDataspace = ui::Dataspace::V0_BT709;
3988 break;
3989 default:
3990 break;
3991 }
3992
3993 return updatedDataspace;
3994}
3995
3996sp<GraphicBuffer> Layer::getBuffer() const {
3997 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
3998}
3999
Patrick Williamsbb25f802022-08-30 23:02:34 +00004000void Layer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
4001 mTransformHint = getFixedTransformHint();
4002 if (mTransformHint == ui::Transform::ROT_INVALID) {
4003 mTransformHint = displayTransformHint;
4004 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004005 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004006}
4007
4008const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4009 return mBufferInfo.mBuffer;
4010}
4011
4012bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004013 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004014 return false;
4015 }
4016
4017 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004018 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004019 mDrawingState.modified = true;
4020 setTransactionFlags(eTransactionNeeded);
4021 return true;
4022}
4023
4024bool Layer::fillsColor() const {
4025 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4026 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4027}
4028
4029bool Layer::hasBlur() const {
4030 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4031}
4032
Vishnu Nairba354102022-08-01 00:14:18 +00004033void Layer::updateSnapshot(bool updateGeometry) {
4034 if (!getCompositionEngineLayerFE()) {
4035 return;
4036 }
4037
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004038 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004039 if (updateGeometry) {
4040 prepareBasicGeometryCompositionState();
4041 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004042 snapshot->roundedCorner = getRoundedCornerState();
4043 snapshot->stretchEffect = getStretchEffect();
4044 snapshot->transformedBounds = mScreenBounds;
4045 if (mEffectiveShadowRadius > 0.f) {
4046 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4047
4048 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4049 // it if transparent regions are present. This may not be necessary since shadows are
4050 // typically cast by layers without transparent regions.
4051 snapshot->shadowSettings.boundaries = mBounds;
4052
4053 const float casterAlpha = snapshot->alpha;
4054 const bool casterIsOpaque =
4055 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4056
4057 // If the casting layer is translucent, we need to fill in the shadow underneath the
4058 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4059 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4060 snapshot->shadowSettings.ambientColor *= casterAlpha;
4061 snapshot->shadowSettings.spotColor *= casterAlpha;
4062 }
4063 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004064 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004065 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004066 snapshot->layerOpaqueFlagSet =
4067 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004068 snapshot->isHdrY410 = isHdrY410();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004069 sp<Layer> p = mDrawingParent.promote();
4070 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004071 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004072 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004073 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004074 }
4075 snapshot->bufferSize = getBufferSize(mDrawingState);
4076 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004077 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004078 preparePerFrameCompositionState();
4079}
4080
Vishnu Naire14c6b32022-08-06 04:20:15 +00004081void Layer::updateChildrenSnapshots(bool updateGeometry) {
4082 for (const sp<Layer>& child : mDrawingChildren) {
4083 child->updateSnapshot(updateGeometry);
4084 child->updateChildrenSnapshots(updateGeometry);
4085 }
4086}
4087
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004088void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4089 mSnapshot->layerMetadata = parentMetadata;
4090 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4091 for (const sp<Layer>& child : mDrawingChildren) {
4092 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4093 }
4094}
4095
4096void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4097 std::unordered_set<Layer*>& visited) {
4098 if (visited.find(this) != visited.end()) {
4099 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4100 return;
4101 }
4102 visited.insert(this);
4103
4104 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4105
4106 if (mDrawingState.zOrderRelatives.empty()) {
4107 return;
4108 }
4109 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4110 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4111 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4112 sp<Layer> relative = weakRelative.promote();
4113 if (!relative) {
4114 continue;
4115 }
4116 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4117 }
4118}
4119
Chavi Weingarten328a8312023-01-26 21:17:52 +00004120bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004121 TrustedPresentationListener const& listener) {
4122 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4123 mTrustedPresentationListener = listener;
4124 mTrustedPresentationThresholds = thresholds;
4125 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4126 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4127 mFlinger->mNumTrustedPresentationListeners++;
4128 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4129 mFlinger->mNumTrustedPresentationListeners--;
4130 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004131
4132 // Reset trusted presentation states to ensure we start the time again.
4133 mEnteredTrustedPresentationStateTime = -1;
4134 mLastReportedTrustedPresentationState = false;
4135 mLastComputedTrustedPresentationState = false;
4136
4137 // If there's a new trusted presentation listener, the code needs to go through the composite
4138 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4139 // we're already in the requested state.
4140 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004141}
4142
Vishnu Naira156f482023-02-22 00:23:38 +00004143void Layer::updateLastLatchTime(nsecs_t latchTime) {
4144 mLastLatchTime = latchTime;
4145}
4146
Mathias Agopian13127d82013-03-05 17:47:11 -08004147// ---------------------------------------------------------------------------
4148
Marin Shalamanov46084422020-10-13 12:33:42 +02004149std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004150 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4151 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004152}
4153
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004154} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004155
4156#if defined(__gl_h_)
4157#error "don't include gl/gl.h in this file"
4158#endif
4159
4160#if defined(__gl2_h_)
4161#error "don't include gl2/gl2.h in this file"
4162#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004163
4164// TODO(b/129481165): remove the #pragma below and fix conversion issues
4165#pragma clang diagnostic pop // ignored "-Wconversion"