blob: be021510dfdc10d5cffbde5d9bd2688142e82de3 [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();
Sally Qi963049b2023-03-23 14:06:21 -0700642 snapshot->currentHdrSdrRatio = getCurrentHdrSdrRatio();
643 snapshot->desiredHdrSdrRatio = getDesiredHdrSdrRatio();
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;
ramindanib2158ee2023-02-13 20:29:59 -0800684 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
685 snapshot->compositionType =
686 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000687 } else {
688 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000689 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
690 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000691 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
692 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
693 }
694
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000695 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000696 snapshot->acquireFence = mBufferInfo.mFence;
697 snapshot->frameNumber = mBufferInfo.mFrameNumber;
698 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000699}
700
701void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000702 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000703 auto* snapshot = editLayerSnapshot();
704 snapshot->color = getColor();
705 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000706 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800707}
708
Lloyd Piquede196652020-01-22 17:29:58 -0800709void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800710 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000711 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000712 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800713
714 // Apply the layer's transform, followed by the display's global transform
715 // Here we're guaranteed that the layer's transform preserves rects
716 Rect win = getCroppedBufferSize(drawingState);
717 // Subtract the transparent region and snap to the bounds
718 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
719 Rect frame(getTransform().transform(bounds));
720
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000721 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800722}
723
Lloyd Piquea83776c2019-01-29 18:42:32 -0800724const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700725 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800726}
727
Mathias Agopian13127d82013-03-05 17:47:11 -0800728// ---------------------------------------------------------------------------
729// drawing...
730// ---------------------------------------------------------------------------
731
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500732aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
733 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700734 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800735 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500736 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800737 }
738 if (outputLayer->getState().hwc) {
739 return (*outputLayer->getState().hwc).hwcCompositionType;
740 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500741 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800742 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800743}
744
Mathias Agopian13127d82013-03-05 17:47:11 -0800745// ----------------------------------------------------------------------------
746// local state
747// ----------------------------------------------------------------------------
748
David Sodman41fdfc92017-11-06 16:09:56 -0800749bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800750 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700751 if (s.flags & layer_state_t::eLayerSecure) {
752 return true;
753 }
754
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000755 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700756 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700757}
758
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100759void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
760 std::vector<JankData>& jankData) {
761 if (mPendingJankClassifications.empty() ||
762 !mPendingJankClassifications.front()->getJankType()) {
763 return;
764 }
765
766 bool includeJankData = false;
767 for (const auto& handle : handles) {
768 for (const auto& cb : handle->callbackIds) {
769 if (cb.includeJankData) {
770 includeJankData = true;
771 break;
772 }
773 }
774
775 if (includeJankData) {
776 jankData.reserve(mPendingJankClassifications.size());
777 break;
778 }
779 }
780
781 while (!mPendingJankClassifications.empty() &&
782 mPendingJankClassifications.front()->getJankType()) {
783 if (includeJankData) {
784 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
785 mPendingJankClassifications.front();
786 jankData.emplace_back(
787 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
788 }
789 mPendingJankClassifications.pop_front();
790 }
791}
792
Mathias Agopian13127d82013-03-05 17:47:11 -0800793// ----------------------------------------------------------------------------
794// transaction
795// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800796
Vishnu Naira156f482023-02-22 00:23:38 +0000797uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700798 ATRACE_CALL();
799
Robert Carr0758e5d2021-03-11 22:15:04 -0800800 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700801 mDrawingStateModified = mDrawingState.modified;
802 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700803
Alec Mourib416efd2018-09-06 21:01:59 +0000804 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700805
Robert Carr6a160312021-05-17 12:08:20 -0700806 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800807 // invalidate and recompute the visible regions if needed
808 flags |= Layer::eVisibleRegion;
809 }
810
Robert Carr6a160312021-05-17 12:08:20 -0700811 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800812 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000813 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800814 flags |= eVisibleRegion;
815 this->contentDirty = true;
816
817 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700818 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800819 }
820
Arthur Hung9ed43392022-05-27 06:31:57 +0000821 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
822 mFlinger->mUpdateInputInfo = true;
823 }
824
Vishnu Naira156f482023-02-22 00:23:38 +0000825 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800826
Mathias Agopian13127d82013-03-05 17:47:11 -0800827 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800828}
829
Vishnu Naira156f482023-02-22 00:23:38 +0000830void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000831 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
832 // bufferSurfaceFrameTX will be presented in latchBuffer.
833 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
834 if (surfaceFrame->getPresentState() != PresentState::Presented) {
835 // With applyPendingStates, we could end up having presented surfaceframes from previous
836 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800837 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000838 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
839 }
840 }
Robert Carr6a160312021-05-17 12:08:20 -0700841 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700842}
843
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700844uint32_t Layer::clearTransactionFlags(uint32_t mask) {
845 const auto flags = mTransactionFlags & mask;
846 mTransactionFlags &= ~mask;
847 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800848}
849
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700850void Layer::setTransactionFlags(uint32_t mask) {
851 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800852}
853
Robert Carr1f0a16a2016-10-24 16:27:39 -0700854bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
855 ssize_t idx = mCurrentChildren.indexOf(childLayer);
856 if (idx < 0) {
857 return false;
858 }
859 if (childLayer->setLayer(z)) {
860 mCurrentChildren.removeAt(idx);
861 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800862 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700863 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800864 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700865}
866
Robert Carr503c7042017-09-27 15:06:08 -0700867bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
868 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
869 ssize_t idx = mCurrentChildren.indexOf(childLayer);
870 if (idx < 0) {
871 return false;
872 }
873 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
874 mCurrentChildren.removeAt(idx);
875 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800876 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700877 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800878 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700879}
880
Robert Carrae060832016-11-28 10:51:00 -0800881bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700882 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
883 mDrawingState.sequence++;
884 mDrawingState.z = z;
885 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700886
Robert Carra70e91c2021-06-11 13:59:52 -0700887 mFlinger->mSomeChildrenChanged = true;
888
Robert Carrdb66e622017-04-10 16:55:57 -0700889 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700890 if (mDrawingState.zOrderRelativeOf != nullptr) {
891 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700892 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700893 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700894 }
chaviw606e5cf2019-03-01 10:12:10 -0800895 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700896 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800897 setTransactionFlags(eTransactionNeeded);
898 return true;
899}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700900
Robert Carrdb66e622017-04-10 16:55:57 -0700901void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700902 mDrawingState.zOrderRelatives.remove(relative);
903 mDrawingState.sequence++;
904 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700905 setTransactionFlags(eTransactionNeeded);
906}
907
908void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700909 mDrawingState.zOrderRelatives.add(relative);
910 mDrawingState.modified = true;
911 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700912 setTransactionFlags(eTransactionNeeded);
913}
914
chaviw606e5cf2019-03-01 10:12:10 -0800915void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700916 mDrawingState.zOrderRelativeOf = relativeOf;
917 mDrawingState.sequence++;
918 mDrawingState.modified = true;
919 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700920
chaviw606e5cf2019-03-01 10:12:10 -0800921 setTransactionFlags(eTransactionNeeded);
922}
923
Robert Carr503d2bd2017-12-04 15:49:47 -0800924bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000925 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700926 if (relative == nullptr) {
927 return false;
928 }
929
Robert Carr6a160312021-05-17 12:08:20 -0700930 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
931 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800932 return false;
933 }
934
Robert Carr88b85e12022-03-21 15:47:35 -0700935 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
936 (relative->mDrawingState.zOrderRelativeOf == this)) {
937 ALOGE("Detected relative layer loop between %s and %s",
938 mName.c_str(), relative->mName.c_str());
939 ALOGE("Ignoring new call to set relative layer");
940 return false;
941 }
942
Robert Carra70e91c2021-06-11 13:59:52 -0700943 mFlinger->mSomeChildrenChanged = true;
944
Robert Carr6a160312021-05-17 12:08:20 -0700945 mDrawingState.sequence++;
946 mDrawingState.modified = true;
947 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700948
Robert Carr6a160312021-05-17 12:08:20 -0700949 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700950 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700951 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700952 }
chaviw606e5cf2019-03-01 10:12:10 -0800953 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700954 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700955
956 setTransactionFlags(eTransactionNeeded);
957
958 return true;
959}
960
Winson Chunga30f7c92021-06-29 15:42:56 -0700961bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
962 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
963 mDrawingState.isTrustedOverlay = isTrustedOverlay;
964 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000965 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700966 setTransactionFlags(eTransactionNeeded);
967 return true;
968}
969
970bool Layer::isTrustedOverlay() const {
971 if (getDrawingState().isTrustedOverlay) {
972 return true;
973 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000974 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700975 return (p != nullptr) && p->isTrustedOverlay();
976}
977
Dan Stoza9e56aa02015-11-02 13:00:03 -0800978bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700979 if (mDrawingState.color.a == alpha) return false;
980 mDrawingState.sequence++;
981 mDrawingState.color.a = alpha;
982 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800983 setTransactionFlags(eTransactionNeeded);
984 return true;
985}
chaviw13fdc492017-06-27 12:40:18 -0700986
Valerie Haudd0b7572019-01-29 14:59:27 -0800987bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700988 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700989 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800990 }
Robert Carr6a160312021-05-17 12:08:20 -0700991 mDrawingState.sequence++;
992 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800993 setTransactionFlags(eTransactionNeeded);
994
Robert Carr6a160312021-05-17 12:08:20 -0700995 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -0800996 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -0800997 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700998 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -0700999 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08001000 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001001 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001002
Valerie Haudd0b7572019-01-29 14:59:27 -08001003 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001004 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001005 mFlinger->mLayersAdded = true;
1006 // set up SF to handle added color layer
1007 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -07001008 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001009 }
1010 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001011 } else if (mDrawingState.bgColorLayer && alpha == 0) {
1012 mDrawingState.bgColorLayer->reparent(nullptr);
1013 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001014 return true;
1015 }
1016
Robert Carr6a160312021-05-17 12:08:20 -07001017 mDrawingState.bgColorLayer->setColor(color);
1018 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1019 mDrawingState.bgColorLayer->setAlpha(alpha);
1020 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001021
chaviw13fdc492017-06-27 12:40:18 -07001022 return true;
1023}
1024
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001025bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001026 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001027
Robert Carr6a160312021-05-17 12:08:20 -07001028 mDrawingState.sequence++;
1029 mDrawingState.cornerRadius = cornerRadius;
1030 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001031 setTransactionFlags(eTransactionNeeded);
1032 return true;
1033}
1034
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001035bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001036 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001037 // If we start or stop drawing blur then the layer's visibility state may change so increment
1038 // the magic sequence number.
1039 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1040 mDrawingState.sequence++;
1041 }
Robert Carr6a160312021-05-17 12:08:20 -07001042 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1043 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001044 setTransactionFlags(eTransactionNeeded);
1045 return true;
1046}
Marissa Wall61c58622018-07-18 10:12:20 -07001047
Mathias Agopian13127d82013-03-05 17:47:11 -08001048bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001049 mDrawingState.sequence++;
1050 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001051 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001052 setTransactionFlags(eTransactionNeeded);
1053 return true;
1054}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001055
Lucas Dupinc3800b82020-10-02 16:24:48 -07001056bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001057 // If we start or stop drawing blur then the layer's visibility state may change so increment
1058 // the magic sequence number.
1059 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1060 mDrawingState.sequence++;
1061 }
Robert Carr6a160312021-05-17 12:08:20 -07001062 mDrawingState.blurRegions = blurRegions;
1063 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001064 setTransactionFlags(eTransactionNeeded);
1065 return true;
1066}
1067
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001068bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001069 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1070 if (mDrawingState.flags == newFlags) return false;
1071 mDrawingState.sequence++;
1072 mDrawingState.flags = newFlags;
1073 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001074 setTransactionFlags(eTransactionNeeded);
1075 return true;
1076}
Robert Carr99e27f02016-06-16 15:18:02 -07001077
chaviw25714502021-02-11 10:01:08 -08001078bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001079 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001080 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001081 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001082
Robert Carr6a160312021-05-17 12:08:20 -07001083 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001084 setTransactionFlags(eTransactionNeeded);
1085 return true;
1086}
Robert Carr8d5227b2017-03-16 15:41:03 -07001087
Evan Roskyef876c92019-01-25 17:46:06 -08001088bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001089 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1090 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001091 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001092 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001093}
1094
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001095bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001096 if (mDrawingState.layerStack == layerStack) return false;
1097 mDrawingState.sequence++;
1098 mDrawingState.layerStack = layerStack;
1099 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001100 setTransactionFlags(eTransactionNeeded);
1101 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001102}
1103
Peiyong Linc502cb72019-03-01 15:00:23 -08001104bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001105 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001106 return false;
1107 }
Robert Carr6a160312021-05-17 12:08:20 -07001108 mDrawingState.sequence++;
1109 mDrawingState.colorSpaceAgnostic = agnostic;
1110 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001111 setTransactionFlags(eTransactionNeeded);
1112 return true;
1113}
1114
Sally Qi81d95e62022-03-21 19:41:33 -07001115bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1116 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1117
1118 mDrawingState.sequence++;
1119 mDrawingState.dimmingEnabled = dimmingEnabled;
1120 mDrawingState.modified = true;
1121 setTransactionFlags(eTransactionNeeded);
1122 return true;
1123}
1124
Ana Krulecc84d09b2019-11-02 23:10:29 +01001125bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001126 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1127 mDrawingState.frameRateSelectionPriority = priority;
1128 mDrawingState.sequence++;
1129 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001130 setTransactionFlags(eTransactionNeeded);
1131 return true;
1132}
1133
1134int32_t Layer::getFrameRateSelectionPriority() const {
1135 // Check if layer has priority set.
1136 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1137 return mDrawingState.frameRateSelectionPriority;
1138 }
1139 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001140 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001141 if (parent != nullptr) {
1142 return parent->getFrameRateSelectionPriority();
1143 }
1144
1145 return Layer::PRIORITY_UNSET;
1146}
1147
Andy Labrada096227e2022-06-15 16:58:11 +00001148bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1149 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1150 mDrawingState.defaultFrameRateCompatibility = compatibility;
1151 mDrawingState.modified = true;
1152 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1153 setTransactionFlags(eTransactionNeeded);
1154 return true;
1155}
1156
1157scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1158 return mDrawingState.defaultFrameRateCompatibility;
1159}
1160
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001161bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1162 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1163};
1164
Vishnu Nair73908d12022-10-24 21:46:42 -07001165ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1166 bool useDrawing = state == LayerVector::StateSet::Drawing;
1167 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1168 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001169 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001170 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001171 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001172}
1173
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001174bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001175 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001176 return false;
1177 }
1178
Robert Carr6a160312021-05-17 12:08:20 -07001179 mDrawingState.sequence++;
1180 mDrawingState.shadowRadius = shadowRadius;
1181 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001182 setTransactionFlags(eTransactionNeeded);
1183 return true;
1184}
1185
Vishnu Nair6213bd92020-05-08 17:42:25 -07001186bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001187 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001188 return false;
1189 }
1190
Robert Carr6a160312021-05-17 12:08:20 -07001191 mDrawingState.sequence++;
1192 mDrawingState.fixedTransformHint = fixedTransformHint;
1193 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001194 setTransactionFlags(eTransactionNeeded);
1195 return true;
1196}
1197
John Reckcdb4ed72021-02-04 13:39:33 -05001198bool Layer::setStretchEffect(const StretchEffect& effect) {
1199 StretchEffect temp = effect;
1200 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001201 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001202 return false;
1203 }
Robert Carr6a160312021-05-17 12:08:20 -07001204 mDrawingState.sequence++;
1205 mDrawingState.stretchEffect = temp;
1206 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001207 setTransactionFlags(eTransactionNeeded);
1208 return true;
1209}
1210
John Reckc00c6692021-02-16 11:37:33 -05001211StretchEffect Layer::getStretchEffect() const {
1212 if (mDrawingState.stretchEffect.hasEffect()) {
1213 return mDrawingState.stretchEffect;
1214 }
1215
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001216 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001217 if (parent != nullptr) {
1218 auto effect = parent->getStretchEffect();
1219 if (effect.hasEffect()) {
1220 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1221 return effect;
1222 }
1223 }
1224 return StretchEffect{};
1225}
1226
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001227bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1228 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001229 return false;
1230 }
1231 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001232 mBorderWidth = width;
1233 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001234 return true;
1235}
1236
1237bool Layer::isBorderEnabled() {
1238 return mBorderEnabled;
1239}
1240
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001241float Layer::getBorderWidth() {
1242 return mBorderWidth;
1243}
1244
1245const half4& Layer::getBorderColor() {
1246 return mBorderColor;
1247}
1248
Ady Abrahama850c182021-08-04 13:04:37 -07001249bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1250 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1251 const auto frameRate = [&] {
1252 if (mDrawingState.frameRate.rate.isValid() ||
1253 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1254 return mDrawingState.frameRate;
1255 }
1256
1257 return parentFrameRate;
1258 }();
1259
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001260 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001261
1262 // The frame rate is propagated to the children
1263 bool childrenHaveFrameRate = false;
1264 for (const sp<Layer>& child : mCurrentChildren) {
1265 childrenHaveFrameRate |=
1266 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1267 }
1268
1269 // If we don't have a valid frame rate, but the children do, we set this
1270 // layer as NoVote to allow the children to control the refresh rate
1271 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1272 childrenHaveFrameRate) {
1273 *transactionNeeded |=
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001274 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001275 }
1276
1277 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1278 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001279 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001280 const auto layerVotedWithDefaultCompatibility =
1281 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1282 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1283 const auto layerVotedWithExactCompatibility =
1284 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1285 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1286 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1287}
1288
Ady Abraham60e42ea2020-03-09 19:17:31 -07001289void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001290 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001291 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001292 while (auto parent = layer->getParent()) {
1293 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001294 }
Ady Abrahama850c182021-08-04 13:04:37 -07001295 return layer;
1296 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001297
Ady Abraham60e42ea2020-03-09 19:17:31 -07001298 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001299 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001300
Ady Abrahama850c182021-08-04 13:04:37 -07001301 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001302 if (transactionNeeded) {
1303 mFlinger->setTransactionFlags(eTraversalNeeded);
1304 }
1305}
1306
Ady Abraham71c437d2020-01-31 15:56:57 -08001307bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001308 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001309 return false;
1310 }
1311
Robert Carr6a160312021-05-17 12:08:20 -07001312 mDrawingState.sequence++;
1313 mDrawingState.frameRate = frameRate;
1314 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001315
1316 updateTreeHasFrameRateVote();
1317
Steven Thomas3172e202020-01-06 19:25:30 -08001318 setTransactionFlags(eTransactionNeeded);
1319 return true;
1320}
1321
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001322void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1323 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001324 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001325
1326 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1327 // there are two transactions with the same token, the first one without a buffer and the
1328 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1329 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001330 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1331 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001332 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001333 mDrawingState.bufferSurfaceFrameTX = it->second;
1334 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1335 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1336 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001337 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001338 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001339 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1340 }
1341}
1342
1343void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1344 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001345 mDrawingState.frameTimelineInfo = info;
1346 mDrawingState.postTime = postTime;
1347 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001348 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001349
Robert Carr6a160312021-05-17 12:08:20 -07001350 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001351 bufferSurfaceFrameTX != nullptr) {
1352 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1353 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1354 // being used for BufferSurfaceFrame, don't create a new one.
1355 return;
1356 }
1357 }
1358 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1359 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1360 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001361 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1362 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001363 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001364 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001365 } else {
1366 if (it->second->getPresentState() == PresentState::Presented) {
1367 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1368 // have been from previous vsync.
1369 it->second = createSurfaceFrameForTransaction(info, postTime);
1370 }
1371 }
1372}
1373
1374void Layer::addSurfaceFrameDroppedForBuffer(
1375 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001376 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001377 surfaceFrame->setPresentState(PresentState::Dropped);
1378 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1379}
1380
1381void Layer::addSurfaceFramePresentedForBuffer(
1382 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1383 nsecs_t currentLatchTime) {
1384 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1385 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1386 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001387 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001388}
1389
1390std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1391 const FrameTimelineInfo& info, nsecs_t postTime) {
1392 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001393 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1394 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001395 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001396 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001397 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001398 // For Transactions, the post time is considered to be both queue and acquire fence time.
1399 surfaceFrame->setActualQueueTime(postTime);
1400 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001401 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1402 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001403 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001404 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001405 onSurfaceFrameCreated(surfaceFrame);
1406 return surfaceFrame;
1407}
1408
1409std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1410 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1411 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001412 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001413 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001414 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001415 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001416 // For buffers, acquire fence time will set during latch.
1417 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001418 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1419 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001420 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001421 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001422 onSurfaceFrameCreated(surfaceFrame);
1423 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001424}
1425
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001426bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001427 if (mDrawingState.frameRateForLayerTree == frameRate) {
1428 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001429 }
1430
Ady Abrahama850c182021-08-04 13:04:37 -07001431 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001432
Ady Abrahama850c182021-08-04 13:04:37 -07001433 // TODO(b/195668952): we probably don't need to dirty visible regions here
1434 // or even store frameRateForLayerTree in mDrawingState
1435 mDrawingState.sequence++;
1436 mDrawingState.modified = true;
1437 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001438
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001439 mFlinger->mScheduler
1440 ->recordLayerHistory(sequence, getLayerProps(), systemTime(),
1441 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1442 return true;
1443}
Ady Abrahama850c182021-08-04 13:04:37 -07001444
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001445bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps) {
1446 if (mDrawingState.frameRateForLayerTree == frameRate) {
1447 return false;
1448 }
1449
1450 mDrawingState.frameRateForLayerTree = frameRate;
1451 mFlinger->mScheduler
1452 ->recordLayerHistory(sequence, layerProps, systemTime(),
1453 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001454 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001455}
1456
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001457Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1458 return getDrawingState().frameRateForLayerTree;
1459}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001460
Robert Carr1f0a16a2016-10-24 16:27:39 -07001461bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001462 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001463 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001464 if (parent != nullptr && parent->isHiddenByPolicy()) {
1465 return true;
1466 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001467 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1468 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1469 if (zOrderRelativeOf != nullptr) {
1470 if (zOrderRelativeOf->isHiddenByPolicy()) {
1471 return true;
1472 }
1473 }
1474 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001475 if (CC_UNLIKELY(!isTransformValid())) {
1476 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1477 return true;
1478 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001479 return s.flags & layer_state_t::eLayerHidden;
1480}
1481
David Sodman41fdfc92017-11-06 16:09:56 -08001482uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001483 // TODO: should we do something special if mSecure is set?
1484 if (mProtectedByApp) {
1485 // need a hardware-protected path to external video sink
1486 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001487 }
Riley Andrews03414a12014-07-01 14:22:59 -07001488 if (mPotentialCursor) {
1489 usage |= GraphicBuffer::USAGE_CURSOR;
1490 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001491 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001492 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001493}
1494
Vishnu Nair71fcf912022-10-18 09:14:20 -07001495void Layer::skipReportingTransformHint() {
1496 mSkipReportingTransformHint = true;
1497}
1498
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001499void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1500 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1501 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001502 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001503
Vishnu Nair6213bd92020-05-08 17:42:25 -07001504 setTransformHint(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001505}
1506
Mathias Agopian13127d82013-03-05 17:47:11 -08001507// ----------------------------------------------------------------------------
1508// debugging
1509// ----------------------------------------------------------------------------
1510
Marissa Wall61c58622018-07-18 10:12:20 -07001511// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001512gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001513 using namespace std::string_literals;
1514
Huihong Luo05539a12022-02-23 10:29:40 -08001515 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001516 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001517 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001518 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001519 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001520 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001521
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001522 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001523 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001524 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001525 info.mX = ds.transform.tx();
1526 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001527 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001528 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001529 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001530 info.mFlags = ds.flags;
1531 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001532 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001533 info.mMatrix[0][0] = ds.transform[0][0];
1534 info.mMatrix[0][1] = ds.transform[0][1];
1535 info.mMatrix[1][0] = ds.transform[1][0];
1536 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001537 {
chaviwd62d3062019-09-04 14:48:02 -07001538 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001539 if (buffer != 0) {
1540 info.mActiveBufferWidth = buffer->getWidth();
1541 info.mActiveBufferHeight = buffer->getHeight();
1542 info.mActiveBufferStride = buffer->getStride();
1543 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001544 } else {
1545 info.mActiveBufferWidth = 0;
1546 info.mActiveBufferHeight = 0;
1547 info.mActiveBufferStride = 0;
1548 info.mActiveBufferFormat = 0;
1549 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001550 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001551 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001552 info.mIsOpaque = isOpaque(ds);
1553 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001554 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001555 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001556}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001557
Yiwei Zhang5434a782018-12-05 18:06:32 -08001558void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001559 result.append(kDumpTableRowLength, '-');
1560 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001561 result.append(" Layer name\n");
1562 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001563 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001564 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001565 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001566 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001567 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001568 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1569 result.append(kDumpTableRowLength, '-');
1570 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001571}
1572
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001573void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1574 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001575 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001576 return;
1577 }
1578
Yiwei Zhang5434a782018-12-05 18:06:32 -08001579 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001580 if (mName.length() > 77) {
1581 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001582 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001583 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001584 shortened.append(mName, mName.length() - 36);
1585 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001586 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001587 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001588 }
1589
Yiwei Zhang5434a782018-12-05 18:06:32 -08001590 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001591
Alec Mourib416efd2018-09-06 21:01:59 +00001592 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001593 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001594
Chia-I Wu1e043612018-03-01 09:45:09 -08001595 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001596 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001597 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001598 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001599 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001600 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001601 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001602 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1603 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001604 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001605 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001606 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001607 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001608 const auto frameRate = getFrameRateForLayerTree();
1609 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1610 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001611 ftl::enum_string(frameRate.type).c_str(),
1612 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001613 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001614 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001615 }
Dan Stozae22aec72016-08-01 13:20:59 -07001616
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001617 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1618 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1619
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001620 result.append(kDumpTableRowLength, '-');
1621 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001622}
Dan Stozae22aec72016-08-01 13:20:59 -07001623
Yiwei Zhang5434a782018-12-05 18:06:32 -08001624void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001625 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001626}
1627
Svetoslavd85084b2014-03-20 10:28:31 -07001628void Layer::clearFrameStats() {
1629 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001630}
1631
Jamie Gennis6547ff42013-07-16 20:12:42 -07001632void Layer::logFrameStats() {
1633 mFrameTracker.logAndResetStats(mName);
1634}
1635
Svetoslavd85084b2014-03-20 10:28:31 -07001636void Layer::getFrameStats(FrameStats* outStats) const {
1637 mFrameTracker.getStats(outStats);
1638}
1639
Vishnu Nair76554eb2022-12-09 03:38:36 +00001640void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1641 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
1642 StringAppendF(&result, "Layer %s%s pid:%d uid:%d\n", getName().c_str(), hasBuffer.c_str(),
Vishnu Naircb8be502022-10-12 19:03:23 +00001643 mOwnerPid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001644}
1645
Brian Anderson5ea5e592016-12-01 16:54:33 -08001646void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001647 const int32_t layerId = getSequence();
1648 mFlinger->mTimeStats->onDestroy(layerId);
1649 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001650}
1651
Chia-I Wu98f1c102017-05-30 14:54:08 -07001652size_t Layer::getChildrenCount() const {
1653 size_t count = 0;
1654 for (const sp<Layer>& child : mCurrentChildren) {
1655 count += 1 + child->getChildrenCount();
1656 }
1657 return count;
1658}
1659
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001660void Layer::setGameModeForTree(GameMode gameMode) {
1661 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001662 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1663 gameMode =
1664 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001665 }
1666 setGameMode(gameMode);
1667 for (const sp<Layer>& child : mCurrentChildren) {
1668 child->setGameModeForTree(gameMode);
1669 }
1670}
1671
Robert Carr1f0a16a2016-10-24 16:27:39 -07001672void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001673 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001674 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001675
Robert Carr1f0a16a2016-10-24 16:27:39 -07001676 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001677 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001678 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001679 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001680}
1681
1682ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001683 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001684 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001685
Robert Carr1323c952019-01-28 18:13:27 -08001686 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001687 const auto removeResult = mCurrentChildren.remove(layer);
1688
1689 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001690 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001691 layer->updateTreeHasFrameRateVote();
1692
1693 return removeResult;
1694}
1695
Robert Carr15eae092018-03-23 13:43:53 -07001696void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001697 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001698 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001699 const float parentShadowRadius =
1700 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001701 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001702 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001703 }
1704}
1705
chaviwf1961f72017-09-18 16:41:07 -07001706bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001707 sp<Layer> newParent;
1708 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001709 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001710 if (newParent == nullptr) {
1711 ALOGE("Unable to promote Layer handle");
1712 return false;
1713 }
1714 if (newParent == this) {
1715 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1716 return false;
1717 }
1718 }
1719
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001720 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001721 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001722 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001723 }
1724
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001725 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001726 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001727 if (!newParent->isRemovedFromCurrentState()) {
1728 addToCurrentState();
1729 } else {
1730 onRemovedFromCurrentState();
1731 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001732 } else {
1733 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001734 }
1735
chaviw06178942017-07-27 10:25:59 -07001736 return true;
1737}
1738
Peiyong Lind3788632018-09-18 16:01:31 -07001739bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001740 static const mat4 identityMatrix = mat4();
1741
Robert Carr6a160312021-05-17 12:08:20 -07001742 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001743 return false;
1744 }
Robert Carr6a160312021-05-17 12:08:20 -07001745 ++mDrawingState.sequence;
1746 mDrawingState.colorTransform = matrix;
1747 mDrawingState.hasColorTransform = matrix != identityMatrix;
1748 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001749 setTransactionFlags(eTransactionNeeded);
1750 return true;
1751}
1752
chaviwf66724d2018-11-28 16:35:21 -08001753mat4 Layer::getColorTransform() const {
1754 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001755 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001756 colorTransform = parent->getColorTransform() * colorTransform;
1757 }
1758 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001759}
1760
1761bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001762 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001763 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001764 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1765 }
1766 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001767}
1768
Chia-I Wu11481472018-05-04 10:43:19 -07001769bool Layer::isLegacyDataSpace() const {
1770 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001771 return !(getDataSpace() &
1772 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1773 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001774}
1775
Robert Carr1f0a16a2016-10-24 16:27:39 -07001776void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001777 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001778}
1779
Robert Carr6a160312021-05-17 12:08:20 -07001780int32_t Layer::getZ(LayerVector::StateSet) const {
1781 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001782}
1783
Robert Carr1c5481e2019-07-01 14:42:27 -07001784bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001785 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001786 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001787 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001788}
1789
David Sodman41fdfc92017-11-06 16:09:56 -08001790__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001791 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001792 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1793 "makeTraversalList received invalid stateSet");
1794 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1795 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001796 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001797
Robert Carr29abff82017-12-04 13:51:20 -08001798 if (state.zOrderRelatives.size() == 0) {
1799 *outSkipRelativeZUsers = true;
1800 return children;
1801 }
1802
chaviwfd462612018-05-31 16:11:27 -07001803 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001804 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001805 sp<Layer> strongRelative = weakRelative.promote();
1806 if (strongRelative != nullptr) {
1807 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001808 }
1809 }
1810
Dan Stoza412903f2017-04-27 13:42:17 -07001811 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001812 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001813 continue;
1814 }
Robert Carrdb66e622017-04-10 16:55:57 -07001815 traverse.add(child);
1816 }
1817
1818 return traverse;
1819}
1820
Robert Carr1f0a16a2016-10-24 16:27:39 -07001821/**
Robert Carrdb66e622017-04-10 16:55:57 -07001822 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001823 */
Dan Stoza412903f2017-04-27 13:42:17 -07001824void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001825 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1826 // produce a new list for traversing, including our relatives, and not including our children
1827 // who are relatives of another surface. In the case that there are no relative Z,
1828 // makeTraversalList returns our children directly to avoid significant overhead.
1829 // However in this case we need to take the responsibility for filtering children which
1830 // are relatives of another surface here.
1831 bool skipRelativeZUsers = false;
1832 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001833
Robert Carr1f0a16a2016-10-24 16:27:39 -07001834 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001835 for (; i < list.size(); i++) {
1836 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001837 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1838 continue;
1839 }
1840
chaviw301b1d82019-11-06 13:15:09 -08001841 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001842 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001843 }
Dan Stoza412903f2017-04-27 13:42:17 -07001844 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001845 }
Robert Carr29abff82017-12-04 13:51:20 -08001846
Dan Stoza412903f2017-04-27 13:42:17 -07001847 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001848 for (; i < list.size(); i++) {
1849 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001850
Robert Carr29abff82017-12-04 13:51:20 -08001851 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1852 continue;
1853 }
Dan Stoza412903f2017-04-27 13:42:17 -07001854 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001855 }
1856}
1857
1858/**
Robert Carrdb66e622017-04-10 16:55:57 -07001859 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001860 */
Dan Stoza412903f2017-04-27 13:42:17 -07001861void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1862 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001863 // See traverseInZOrder for documentation.
1864 bool skipRelativeZUsers = false;
1865 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001866
Robert Carr1f0a16a2016-10-24 16:27:39 -07001867 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001868 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001869 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001870
1871 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1872 continue;
1873 }
1874
chaviw301b1d82019-11-06 13:15:09 -08001875 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001876 break;
1877 }
Dan Stoza412903f2017-04-27 13:42:17 -07001878 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001879 }
Dan Stoza412903f2017-04-27 13:42:17 -07001880 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001881 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001882 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001883
1884 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1885 continue;
1886 }
1887
Dan Stoza412903f2017-04-27 13:42:17 -07001888 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001889 }
1890}
1891
Edgar Arriaga844fa672020-01-16 14:21:42 -08001892void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1893 visitor(this);
1894 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001895 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001896 for (const sp<Layer>& child : children) {
1897 child->traverse(state, visitor);
1898 }
1899}
1900
chaviw4b129c22018-04-09 16:19:43 -07001901LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1902 const std::vector<Layer*>& layersInTree) {
1903 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1904 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001905 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1906 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001907 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001908
chaviwfd462612018-05-31 16:11:27 -07001909 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001910 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1911 sp<Layer> strongRelative = weakRelative.promote();
1912 // Only add relative layers that are also descendents of the top most parent of the tree.
1913 // If a relative layer is not a descendent, then it should be ignored.
1914 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1915 traverse.add(strongRelative);
1916 }
1917 }
1918
1919 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001920 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001921 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1922 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1923 // the child here since it won't be added later as a relative.
1924 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1925 childState.zOrderRelativeOf.promote().get())) {
1926 continue;
1927 }
1928 traverse.add(child);
1929 }
1930
1931 return traverse;
1932}
1933
1934void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1935 LayerVector::StateSet stateSet,
1936 const LayerVector::Visitor& visitor) {
1937 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001938
1939 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001940 for (; i < list.size(); i++) {
1941 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001942 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001943 break;
1944 }
chaviw4b129c22018-04-09 16:19:43 -07001945 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001946 }
chaviw4b129c22018-04-09 16:19:43 -07001947
chaviwa76b2712017-09-20 12:02:26 -07001948 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001949 for (; i < list.size(); i++) {
1950 const auto& relative = list[i];
1951 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001952 }
1953}
1954
chaviw4b129c22018-04-09 16:19:43 -07001955std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1956 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1957 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1958
1959 std::vector<Layer*> layersInTree = {this};
1960 for (size_t i = 0; i < children.size(); i++) {
1961 const auto& child = children[i];
1962 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1963 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1964 }
1965
1966 return layersInTree;
1967}
1968
1969void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1970 const LayerVector::Visitor& visitor) {
1971 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1972 std::sort(layersInTree.begin(), layersInTree.end());
1973 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1974}
1975
Peiyong Linefefaac2018-08-17 12:27:51 -07001976ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001977 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001978}
1979
Garfield Tan2c1782c2022-02-16 15:25:05 -08001980bool Layer::isTransformValid() const {
1981 float transformDet = getTransform().det();
1982 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1983}
1984
chaviw13fdc492017-06-27 12:40:18 -07001985half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001986 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001987
chaviw13fdc492017-06-27 12:40:18 -07001988 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1989 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07001990}
Robert Carr6452f122017-03-21 10:41:29 -07001991
Vishnu Nair6213bd92020-05-08 17:42:25 -07001992ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07001993 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001994 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
1995 return fixedTransformHint;
1996 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001997 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07001998 if (!p) return fixedTransformHint;
1999 return p->getFixedTransformHint();
2000}
2001
chaviw13fdc492017-06-27 12:40:18 -07002002half4 Layer::getColor() const {
2003 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002004 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002005}
Robert Carr6452f122017-03-21 10:41:29 -07002006
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002007int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002008 if (getDrawingState().backgroundBlurRadius == 0) {
2009 return 0;
2010 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002011
Vishnu Nair29810f72022-07-01 16:38:41 +00002012 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002013 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2014 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002015}
2016
Galia Peychevae0acf382021-04-12 21:22:34 +02002017const std::vector<BlurRegion> Layer::getBlurRegions() const {
2018 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002019 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002020 for (auto& region : regionsCopy) {
2021 region.alpha = region.alpha * layerAlpha;
2022 }
2023 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002024}
2025
Vishnu Naire14c6b32022-08-06 04:20:15 +00002026RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002027 // Get parent settings
2028 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002029 const auto& parent = mDrawingParent.promote();
2030 if (parent != nullptr) {
2031 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002032 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002033 ui::Transform t = getActiveTransform(getDrawingState());
2034 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002035 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002036 parentSettings.radius.x *= t.getScaleX();
2037 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002038 }
2039 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002040
2041 // Get layer settings
2042 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002043 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002044 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002045 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002046
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002047 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002048 // If the parent and the layer have rounded corner settings, use the parent settings if the
2049 // parent crop is entirely inside the layer crop.
2050 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2051 if (parentSettings.cropRect.left > layerCropRect.left &&
2052 parentSettings.cropRect.top > layerCropRect.top &&
2053 parentSettings.cropRect.right < layerCropRect.right &&
2054 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2055 return parentSettings;
2056 } else {
2057 return layerSettings;
2058 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002059 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002060 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002061 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002062 return parentSettings;
2063 }
2064 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002065}
2066
Robert Carr88b85e12022-03-21 15:47:35 -07002067bool Layer::findInHierarchy(const sp<Layer>& l) {
2068 if (l == this) {
2069 return true;
2070 }
2071 for (auto& child : mDrawingChildren) {
2072 if (child->findInHierarchy(l)) {
2073 return true;
2074 }
2075 }
2076 return false;
2077}
2078
Robert Carr1f0a16a2016-10-24 16:27:39 -07002079void Layer::commitChildList() {
2080 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2081 const auto& child = mCurrentChildren[i];
2082 child->commitChildList();
2083 }
2084 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002085 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002086 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2087 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2088 if (zOrderRelativeOf == nullptr) return;
2089 if (findInHierarchy(zOrderRelativeOf)) {
2090 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2091 zOrderRelativeOf->mName.c_str());
2092 ALOGE("Severing rel Z loop, potentially dangerous");
2093 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002094 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002095 }
2096 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002097}
2098
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002099
chaviw3277faf2021-05-19 16:45:23 -05002100void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002101 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002102 mDrawingState.touchableRegionCrop =
2103 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002104 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002105 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002106 setTransactionFlags(eTransactionNeeded);
2107}
2108
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002109LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002110 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002111 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002112 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2113
Vishnu Nair00b90132021-11-05 14:03:40 -07002114 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002115 writeCompositionStateToProto(layerProto);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002116 }
2117
chaviw08f3cb22020-01-13 13:17:21 -08002118 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002119 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002120 }
chaviw6d89e2d2020-01-14 14:42:01 -08002121
2122 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002123}
2124
Vishnu Nairea6ff812023-02-27 17:41:39 +00002125void Layer::writeCompositionStateToProto(LayerProto* layerProto) {
2126 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2127
2128 // Only populate for the primary display.
2129 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
2130 const auto compositionType = getCompositionType(*display);
2131 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
2132 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2133 [&]() { return layerProto->mutable_visible_region(); });
2134 }
2135}
2136
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002137void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002138 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002139 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002140 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002141 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002142 [&]() { return layerInfo->mutable_active_buffer(); });
2143 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2144 layerInfo->mutable_buffer_transform());
2145 }
2146 layerInfo->set_invalidate(contentDirty);
2147 layerInfo->set_is_protected(isProtected());
2148 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2149 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002150 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002151 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002152 layerInfo->set_corner_radius(
2153 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002154 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2155 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2156 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2157 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2158 [&]() { return layerInfo->mutable_position(); });
2159 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002160 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2161 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002162
Vishnu Nair00b90132021-11-05 14:03:40 -07002163 if (hasColorTransform()) {
2164 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002165 }
2166
Vishnu Nair60db8c02020-04-02 11:55:16 -07002167 LayerProtoHelper::writeToProto(mSourceBounds,
2168 [&]() { return layerInfo->mutable_source_bounds(); });
2169 LayerProtoHelper::writeToProto(mScreenBounds,
2170 [&]() { return layerInfo->mutable_screen_bounds(); });
2171 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2172 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2173 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002174}
2175
2176void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002177 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002178 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2179 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002180 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002181
chaviw766c9c52021-02-10 17:36:47 -08002182 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002183
Vishnu Nair00b90132021-11-05 14:03:40 -07002184 layerInfo->set_id(sequence);
2185 layerInfo->set_name(getName().c_str());
2186 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002187
Vishnu Nair00b90132021-11-05 14:03:40 -07002188 for (const auto& child : children) {
2189 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002190 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002191
Vishnu Nair00b90132021-11-05 14:03:40 -07002192 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2193 sp<Layer> strongRelative = weakRelative.promote();
2194 if (strongRelative != nullptr) {
2195 layerInfo->add_relatives(strongRelative->sequence);
2196 }
2197 }
2198
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002199 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002200 [&]() { return layerInfo->mutable_transparent_region(); });
2201
2202 layerInfo->set_layer_stack(getLayerStack().id);
2203 layerInfo->set_z(state.z);
2204
2205 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2206 return layerInfo->mutable_requested_position();
2207 });
2208
Vishnu Nair00b90132021-11-05 14:03:40 -07002209 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2210
2211 layerInfo->set_is_opaque(isOpaque(state));
2212
2213 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2214 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2215 LayerProtoHelper::writeToProto(state.color,
2216 [&]() { return layerInfo->mutable_requested_color(); });
2217 layerInfo->set_flags(state.flags);
2218
2219 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2220 layerInfo->mutable_requested_transform());
2221
2222 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2223 if (parent != nullptr) {
2224 layerInfo->set_parent(parent->sequence);
2225 } else {
2226 layerInfo->set_parent(-1);
2227 }
2228
2229 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2230 if (zOrderRelativeOf != nullptr) {
2231 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2232 } else {
2233 layerInfo->set_z_order_relative_of(-1);
2234 }
2235
2236 layerInfo->set_is_relative_of(state.isRelativeOf);
2237
2238 layerInfo->set_owner_uid(mOwnerUid);
2239
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002240 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002241 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002242 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002243 info = fillInputInfo(
2244 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002245 } else {
2246 info = state.inputInfo;
2247 }
2248
2249 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002250 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002251 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002252
Vishnu Nair00b90132021-11-05 14:03:40 -07002253 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002254 auto protoMap = layerInfo->mutable_metadata();
2255 for (const auto& entry : state.metadata.mMap) {
2256 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2257 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002258 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002259
2260 LayerProtoHelper::writeToProto(state.destinationFrame,
2261 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002262}
2263
Robert Carr2e102c92018-10-23 12:11:15 -07002264bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002265 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002266}
2267
Prabir Pradhan33da9462022-06-14 14:55:57 +00002268// Applies the given transform to the region, while protecting against overflows caused by any
2269// offsets. If applying the offset in the transform to any of the Rects in the region would result
2270// in an overflow, they are not added to the output Region.
2271static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2272 const std::string& debugWindowName) {
2273 // Round the translation using the same rounding strategy used by ui::Transform.
2274 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2275 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2276
2277 ui::Transform transformWithoutOffset = t;
2278 transformWithoutOffset.set(0.f, 0.f);
2279
2280 const Region transformed = transformWithoutOffset.transform(r);
2281
2282 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2283 Region ret;
2284 for (const auto& rect : transformed) {
2285 Rect newRect;
2286 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2287 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2288 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2289 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2290 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2291 debugWindowName.c_str());
2292 continue;
2293 }
2294 ret.orSelf(newRect);
2295 }
2296 return ret;
2297}
2298
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002299void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
2300 Rect tmpBounds = getInputBounds();
2301 if (!tmpBounds.isValid()) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002302 info.touchableRegion.clear();
2303 // A layer could have invalid input bounds and still expect to receive touch input if it has
2304 // replaceTouchableRegionWithCrop. For that case, the input transform needs to be calculated
2305 // correctly to determine the coordinate space for input events. Use an empty rect so that
2306 // the layer will receive input in its own layer space.
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002307 tmpBounds = Rect::EMPTY_RECT;
chaviw7e72caf2020-12-02 16:50:43 -08002308 }
2309
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002310 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2311 // frame and transform used for the layer, which determines the bounds and the coordinate space
2312 // within which the layer will receive input.
2313 //
2314 // The coordinate space within which each of the bounds are specified is explicitly documented
2315 // in the variable name. For example "inputBoundsInLayer" is specified in layer space. A
2316 // Transform converts one coordinate space to another, which is apparent in its naming. For
2317 // example, "layerToDisplay" transforms layer space to display space.
2318 //
2319 // Coordinate space definitions:
2320 // - display: The display device's coordinate space. Correlates to pixels on the display.
2321 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2322 // - layer: The coordinate space of this layer.
2323 // - input: The coordinate space in which this layer will receive input events. This could be
2324 // different than layer space if a surfaceInset is used, which changes the origin
2325 // of the input space.
2326 const FloatRect inputBoundsInLayer = tmpBounds.toFloatRect();
chaviw7e72caf2020-12-02 16:50:43 -08002327
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002328 // Clamp surface inset to the input bounds.
2329 const auto surfaceInset = static_cast<float>(info.surfaceInset);
2330 const float xSurfaceInset =
2331 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getWidth() / 2.f));
2332 const float ySurfaceInset =
2333 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getHeight() / 2.f));
chaviw1ff3d1e2020-07-01 15:53:47 -07002334
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002335 // Apply the insets to the input bounds.
2336 const FloatRect insetBoundsInLayer(inputBoundsInLayer.left + xSurfaceInset,
2337 inputBoundsInLayer.top + ySurfaceInset,
2338 inputBoundsInLayer.right - xSurfaceInset,
2339 inputBoundsInLayer.bottom - ySurfaceInset);
Ady Abraham282f1d72019-07-24 18:05:56 -07002340
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002341 // Crop the input bounds to ensure it is within the parent's bounds.
2342 const FloatRect croppedInsetBoundsInLayer = mBounds.intersect(insetBoundsInLayer);
Ady Abraham282f1d72019-07-24 18:05:56 -07002343
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002344 const ui::Transform layerToScreen = getInputTransform();
2345 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
Vishnu Nair8033a492018-12-05 07:27:23 -08002346
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002347 const Rect roundedFrameInDisplay{layerToDisplay.transform(croppedInsetBoundsInLayer)};
2348 info.frameLeft = roundedFrameInDisplay.left;
2349 info.frameTop = roundedFrameInDisplay.top;
2350 info.frameRight = roundedFrameInDisplay.right;
2351 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002352
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002353 ui::Transform inputToLayer;
2354 inputToLayer.set(insetBoundsInLayer.left, insetBoundsInLayer.top);
2355 const ui::Transform inputToDisplay = layerToDisplay * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002356
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002357 // InputDispatcher expects a display-to-input transform.
2358 info.transform = inputToDisplay.inverse();
2359
2360 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002361 info.touchableRegion =
2362 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002363}
2364
chaviw3277faf2021-05-19 16:45:23 -05002365void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002366 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002367 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002368 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002369 }
2370 if (p != nullptr) {
2371 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2372 }
2373}
2374
Vishnu Naira066d902021-09-13 18:40:17 -07002375gui::DropInputMode Layer::getDropInputMode() const {
2376 gui::DropInputMode mode = mDrawingState.dropInputMode;
2377 if (mode == gui::DropInputMode::ALL) {
2378 return mode;
2379 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002380 sp<Layer> parent = mDrawingParent.promote();
2381 if (parent) {
2382 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002383 if (parentMode != gui::DropInputMode::NONE) {
2384 return parentMode;
2385 }
2386 }
2387 return mode;
2388}
2389
2390void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002391 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002392 return;
2393 }
2394
2395 // Check if we need to drop input unconditionally
2396 gui::DropInputMode dropInputMode = getDropInputMode();
2397 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002398 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002399 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2400 return;
2401 }
2402
2403 // Check if we need to check if the window is obscured by parent
2404 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2405 return;
2406 }
2407
2408 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002409 sp<Layer> parent = mDrawingParent.promote();
2410 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002411 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002412 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2413 static_cast<float>(getAlpha()));
2414 }
2415
2416 // Check if the parent has cropped the buffer
2417 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2418 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002419 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002420 return;
2421 }
2422
2423 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2424 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2425 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2426 // match then the layer has not been cropped by its parents.
2427 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2428 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2429
2430 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002431 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002432 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2433 getDebugName());
2434 } else {
2435 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2436 // input if the window is obscured. This check should be done in surfaceflinger but the
2437 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2438 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002439 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002440 }
2441}
2442
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002443WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002444 if (!hasInputInfo()) {
2445 mDrawingState.inputInfo.name = getName();
2446 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2447 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002448 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002449 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002450 }
2451
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002452 const ui::Transform& displayTransform =
2453 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2454
chaviw3277faf2021-05-19 16:45:23 -05002455 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002456 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002457 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002458
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002459 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002460
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002461 if (displayArgs.transform == nullptr) {
2462 // Do not let the window receive touches if it is not associated with a valid display
2463 // transform. We still allow the window to receive keys and prevent ANRs.
2464 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2465 }
2466
Robert Carr5dc426e2020-06-10 14:29:14 -07002467 // For compatibility reasons we let layers which can receive input
2468 // receive input before they have actually submitted a buffer. Because
2469 // of this we use canReceiveInput instead of isVisible to check the
2470 // policy-visibility, ignoring the buffer state. However for layers with
2471 // hasInputInfo()==false we can use the real visibility state.
2472 // We are just using these layers for occlusion detection in
2473 // InputDispatcher, and obviously if they aren't visible they can't occlude
2474 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002475 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2476 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2477
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002478 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002479 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002480 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002481
Vishnu Nair16a938f2021-09-24 07:14:54 -07002482 // If the window will be blacked out on a display because the display does not have the secure
2483 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002484 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002485 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002486 }
2487
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002488 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2489 if (info.replaceTouchableRegionWithCrop) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002490 const Rect bounds(cropLayer ? cropLayer->mScreenBounds : mScreenBounds);
2491 info.touchableRegion = Region(displayTransform.transform(bounds));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002492 } else if (cropLayer != nullptr) {
[1;3C2b9fc252021-02-04 16:16:50 -08002493 info.touchableRegion = info.touchableRegion.intersect(
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002494 displayTransform.transform(Rect{cropLayer->mScreenBounds}));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002495 }
2496
Winson Chunga30f7c92021-06-29 15:42:56 -07002497 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2498 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002499 if (isTrustedOverlay()) {
2500 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2501 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002502
chaviwaf87b3e2019-10-01 16:59:28 -07002503 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2504 // touches from going outside the cloned area.
2505 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002506 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002507 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2508 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002509 info.touchableRegion = info.touchableRegion.intersect(rect);
2510 }
2511 }
2512
Robert Carr720e5062018-07-30 17:45:14 -07002513 return info;
2514}
2515
chaviwaf87b3e2019-10-01 16:59:28 -07002516sp<Layer> Layer::getClonedRoot() {
2517 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002518 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002519 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002520 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002521 return nullptr;
2522 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002523 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002524}
2525
Robert Carredd13602020-04-13 17:24:34 -07002526bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002527 return mDrawingState.inputInfo.token != nullptr ||
2528 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002529}
2530
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002531compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002532 const DisplayDevice* display) const {
2533 if (!display) return nullptr;
Vishnu Naird47bcee2023-02-24 18:08:51 +00002534 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2535 return display->getCompositionDisplay()->getOutputLayerForLayer(
2536 getCompositionEngineLayerFE());
2537 }
2538 sp<LayerFE> layerFE;
2539 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2540 for (auto& [p, layer] : mLayerFEs) {
2541 if (p == path) {
2542 layerFE = layer;
2543 }
2544 }
2545
2546 if (!layerFE) return nullptr;
2547 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002548}
2549
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002550Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2551 const auto outputLayer = findOutputLayerForDisplay(display);
2552 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002553}
2554
chaviwb4c6e582019-08-16 14:35:07 -07002555void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002556 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002557 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002558 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2559 mPotentialCursor = clonedFrom->mPotentialCursor;
2560 mProtectedByApp = clonedFrom->mProtectedByApp;
2561 updateCloneBufferInfo();
2562}
2563
2564void Layer::updateCloneBufferInfo() {
2565 if (!isClone() || !isClonedFromAlive()) {
2566 return;
2567 }
2568
2569 sp<Layer> clonedFrom = getClonedFrom();
2570 mBufferInfo = clonedFrom->mBufferInfo;
2571 mSidebandStream = clonedFrom->mSidebandStream;
2572 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2573 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2574 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2575
2576 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2577 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2578 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2579 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2580 // the cloned drawingState again.
2581 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2582 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2583 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2584 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2585
2586 cloneDrawingState(clonedFrom.get());
2587
2588 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2589 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2590 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2591 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002592}
chaviw74b03172019-08-19 11:09:03 -07002593
2594void Layer::updateMirrorInfo() {
2595 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2596 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2597 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2598 // that case, we want to delete the reference to the clone since we want it to get
2599 // destroyed. The root, this layer, will still be around since the client can continue
2600 // to hold a reference, but no cloned layers will be displayed.
2601 mClonedChild = nullptr;
2602 return;
2603 }
2604
2605 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2606 // If the real layer exists and is in current state, add the clone as a child of the root.
2607 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2608 // copied to drawingState for the root layer. So the clonedChild is always removed from
2609 // drawingState and then needs to be added back each traversal.
2610 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2611 addChildToDrawing(mClonedChild);
2612 }
2613
2614 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002615 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002616 mClonedChild->updateClonedRelatives(clonedLayersMap);
2617}
2618
2619void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2620 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2621 // to the clone. If the real layer is no longer alive, continue traversing the children
2622 // since we may be able to pull out other children that are still alive.
2623 if (isClonedFromAlive()) {
2624 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002625 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002626 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002627 }
2628
2629 // The clone layer may have children in drawingState since they may have been created and
2630 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2631 // that already exist, since we can just re-use them.
2632 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2633 // not updated in the regular traversal. They are skipped since the root will lose the
2634 // reference to them when it copies its currentChildren to drawing.
2635 for (sp<Layer>& child : mDrawingChildren) {
2636 child->updateClonedDrawingState(clonedLayersMap);
2637 }
2638}
2639
2640void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2641 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2642 mDrawingChildren.clear();
2643
2644 if (!isClonedFromAlive()) {
2645 return;
2646 }
2647
2648 sp<Layer> clonedFrom = getClonedFrom();
2649 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2650 if (child == mirrorRoot) {
2651 // This is to avoid cyclical mirroring.
2652 continue;
2653 }
2654 sp<Layer> clonedChild = clonedLayersMap[child];
2655 if (clonedChild == nullptr) {
2656 clonedChild = child->createClone();
2657 clonedLayersMap[child] = clonedChild;
2658 }
2659 addChildToDrawing(clonedChild);
2660 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2661 }
2662}
2663
chaviwaf87b3e2019-10-01 16:59:28 -07002664void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2665 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2666 if (cropLayer != nullptr) {
2667 if (clonedLayersMap.count(cropLayer) == 0) {
2668 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2669 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002670 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002671 } else {
2672 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2673 mDrawingState.touchableRegionCrop = clonedCropLayer;
2674 }
2675 }
2676 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2677 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002678 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002679}
2680
2681void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002682 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002683 mDrawingState.zOrderRelatives.clear();
2684
2685 if (!isClonedFromAlive()) {
2686 return;
2687 }
2688
chaviwaf87b3e2019-10-01 16:59:28 -07002689 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002690 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002691 const sp<Layer>& relative = relativeWeak.promote();
2692 if (clonedLayersMap.count(relative) > 0) {
2693 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002694 mDrawingState.zOrderRelatives.add(clonedRelative);
2695 }
2696 }
2697
2698 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2699 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2700 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2701 // still traverse the children, but the layer with the missing relativeOf will not be shown
2702 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002703 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2704 if (clonedLayersMap.count(relativeOf) > 0) {
2705 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002706 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2707 }
2708
chaviwaf87b3e2019-10-01 16:59:28 -07002709 updateClonedInputInfo(clonedLayersMap);
2710
chaviw74b03172019-08-19 11:09:03 -07002711 for (sp<Layer>& child : mDrawingChildren) {
2712 child->updateClonedRelatives(clonedLayersMap);
2713 }
2714}
2715
2716void Layer::addChildToDrawing(const sp<Layer>& layer) {
2717 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002718 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002719}
2720
Steven Thomas62a4cf82020-01-31 12:04:03 -08002721Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2722 switch (compatibility) {
2723 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2724 return FrameRateCompatibility::Default;
2725 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2726 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002727 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2728 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002729 case ANATIVEWINDOW_FRAME_RATE_MIN:
2730 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002731 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2732 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002733 default:
2734 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2735 return FrameRateCompatibility::Default;
2736 }
2737}
2738
Marin Shalamanovc5986772021-03-16 16:09:49 +01002739scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2740 switch (strategy) {
2741 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2742 return Seamlessness::OnlySeamless;
2743 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2744 return Seamlessness::SeamedAndSeamless;
2745 default:
2746 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2747 return Seamlessness::Default;
2748 }
2749}
2750
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002751bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002752 const State& s(mDrawingState);
2753 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2754 return true;
2755 }
2756
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002757 sp<Layer> parent = mDrawingParent.promote();
2758 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002759}
2760
Robert Carr6a0382d2021-07-01 15:57:17 -07002761void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2762 mClonedChild = clonedChild;
2763 mHadClonedChild = true;
2764 mFlinger->mNumClones++;
2765}
2766
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002767bool Layer::setDropInputMode(gui::DropInputMode mode) {
2768 if (mDrawingState.dropInputMode == mode) {
2769 return false;
2770 }
2771 mDrawingState.dropInputMode = mode;
2772 return true;
2773}
2774
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002775void Layer::cloneDrawingState(const Layer* from) {
2776 mDrawingState = from->mDrawingState;
2777 // Skip callback info since they are not applicable for cloned layers.
2778 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002779 // TODO (b/238781169) currently broken for mirror layers because we do not
2780 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002781 mDrawingState.callbackHandles = {};
2782}
2783
Patrick Williamsbb25f802022-08-30 23:02:34 +00002784void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2785 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002786 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002787 if (!listener) {
2788 return;
2789 }
2790 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002791 uint32_t currentMaxAcquiredBufferCount =
2792 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002793 listener->onReleaseBuffer({buffer->getId(), framenumber},
2794 releaseFence ? releaseFence : Fence::NO_FENCE,
2795 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002796}
2797
2798void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2799 // If we are displayed on multiple displays in a single composition cycle then we would
2800 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2801 // For example we can only use it if all the displays are client comp, and we need
2802 // to merge all the client comp fences. We could do this, but for now we just
2803 // disable the optimization when a layer is composed on multiple displays.
2804 if (mClearClientCompositionFenceOnLayerDisplayed) {
2805 mLastClientCompositionFence = nullptr;
2806 } else {
2807 mClearClientCompositionFenceOnLayerDisplayed = true;
2808 }
2809
2810 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2811 // buffer that was presented on this layer. The first transaction that came in this frame that
2812 // replaced the previous buffer on this layer needs this release fence, because the fence will
2813 // let the client know when that previous buffer is removed from the screen.
2814 //
2815 // Every other transaction on this layer does not need a release fence because no other
2816 // Transactions that were set on this layer this frame are going to have their preceding buffer
2817 // removed from the display this frame.
2818 //
2819 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2820 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2821 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2822 // the previous buffer will be released this frame. The third transaction also contains a
2823 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2824 // transaction will now no longer be presented so it is released immediately and the third
2825 // transaction doesn't need a previous release fence.
2826 sp<CallbackHandle> ch;
2827 for (auto& handle : mDrawingState.callbackHandles) {
2828 if (handle->releasePreviousBuffer &&
2829 mDrawingState.releaseBufferEndpoint == handle->listener) {
2830 ch = handle;
2831 break;
2832 }
2833 }
2834
2835 // Prevent tracing the same release multiple times.
2836 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2837 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2838 }
2839
2840 if (ch != nullptr) {
2841 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2842 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2843 ch->name = mName;
2844 }
2845}
2846
2847void Layer::onSurfaceFrameCreated(
2848 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2849 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2850 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2851 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2852 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002853 if (hasBufferOrSidebandStreamInDrawing()) {
2854 // Only log for layers with a buffer, since we expect the jank data to be drained for
2855 // these, while there may be no jank listeners for bufferless layers.
2856 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2857 mName.c_str());
2858 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2859 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2860 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002861 mPendingJankClassifications.pop_front();
2862 }
2863 mPendingJankClassifications.emplace_back(surfaceFrame);
2864}
2865
2866void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2867 for (const auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair71fcf912022-10-18 09:14:20 -07002868 handle->transformHint = mSkipReportingTransformHint
2869 ? std::nullopt
2870 : std::make_optional<uint32_t>(mTransformHint);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002871 handle->dequeueReadyTime = dequeueReadyTime;
2872 handle->currentMaxAcquiredBufferCount =
2873 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2874 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2875 handle->previousReleaseCallbackId.framenumber);
2876 }
2877
2878 for (auto& handle : mDrawingState.callbackHandles) {
2879 if (handle->releasePreviousBuffer &&
2880 mDrawingState.releaseBufferEndpoint == handle->listener) {
2881 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2882 break;
2883 }
2884 }
2885
2886 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002887 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002888 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2889 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002890 mDrawingState.callbackHandles = {};
2891}
2892
2893bool Layer::willPresentCurrentTransaction() const {
2894 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2895 return (getSidebandStreamChanged() || getAutoRefresh() ||
2896 (mDrawingState.modified &&
2897 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2898}
2899
2900bool Layer::setTransform(uint32_t transform) {
2901 if (mDrawingState.bufferTransform == transform) return false;
2902 mDrawingState.bufferTransform = transform;
2903 mDrawingState.modified = true;
2904 setTransactionFlags(eTransactionNeeded);
2905 return true;
2906}
2907
2908bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2909 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2910 mDrawingState.sequence++;
2911 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2912 mDrawingState.modified = true;
2913 setTransactionFlags(eTransactionNeeded);
2914 return true;
2915}
2916
2917bool Layer::setBufferCrop(const Rect& bufferCrop) {
2918 if (mDrawingState.bufferCrop == bufferCrop) return false;
2919
2920 mDrawingState.sequence++;
2921 mDrawingState.bufferCrop = bufferCrop;
2922
2923 mDrawingState.modified = true;
2924 setTransactionFlags(eTransactionNeeded);
2925 return true;
2926}
2927
2928bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2929 if (mDrawingState.destinationFrame == destinationFrame) return false;
2930
2931 mDrawingState.sequence++;
2932 mDrawingState.destinationFrame = destinationFrame;
2933
2934 mDrawingState.modified = true;
2935 setTransactionFlags(eTransactionNeeded);
2936 return true;
2937}
2938
2939// Translate destination frame into scale and position. If a destination frame is not set, use the
2940// provided scale and position
2941bool Layer::updateGeometry() {
2942 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2943 mDrawingState.destinationFrame.isEmpty()) {
2944 // If destination frame is not set, use the requested transform set via
2945 // Layer::setPosition and Layer::setMatrix.
2946 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2947 }
2948
2949 Rect destRect = mDrawingState.destinationFrame;
2950 int32_t destW = destRect.width();
2951 int32_t destH = destRect.height();
2952 if (destRect.left < 0) {
2953 destRect.left = 0;
2954 destRect.right = destW;
2955 }
2956 if (destRect.top < 0) {
2957 destRect.top = 0;
2958 destRect.bottom = destH;
2959 }
2960
2961 if (!mDrawingState.buffer) {
2962 ui::Transform t;
2963 t.set(destRect.left, destRect.top);
2964 return assignTransform(&mDrawingState.transform, t);
2965 }
2966
2967 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2968 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2969 // Undo any transformations on the buffer.
2970 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2971 std::swap(bufferWidth, bufferHeight);
2972 }
2973 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
2974 if (mDrawingState.transformToDisplayInverse) {
2975 if (invTransform & ui::Transform::ROT_90) {
2976 std::swap(bufferWidth, bufferHeight);
2977 }
2978 }
2979
2980 float sx = destW / static_cast<float>(bufferWidth);
2981 float sy = destH / static_cast<float>(bufferHeight);
2982 ui::Transform t;
2983 t.set(sx, 0, 0, sy);
2984 t.set(destRect.left, destRect.top);
2985 return assignTransform(&mDrawingState.transform, t);
2986}
2987
2988bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
2989 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
2990 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
2991 return false;
2992 }
2993
2994 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
2995
2996 mDrawingState.sequence++;
2997 mDrawingState.modified = true;
2998 setTransactionFlags(eTransactionNeeded);
2999
3000 return true;
3001}
3002
3003bool Layer::setPosition(float x, float y) {
3004 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3005 return false;
3006 }
3007
3008 mRequestedTransform.set(x, y);
3009
3010 mDrawingState.sequence++;
3011 mDrawingState.modified = true;
3012 setTransactionFlags(eTransactionNeeded);
3013
3014 return true;
3015}
3016
3017bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3018 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3019 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003020 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003021 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003022 if (!buffer) {
3023 return false;
3024 }
3025
3026 const bool frameNumberChanged =
3027 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3028 const uint64_t frameNumber =
3029 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003030 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003031
3032 if (mDrawingState.buffer) {
3033 mReleasePreviousBuffer = true;
3034 if (!mBufferInfo.mBuffer ||
3035 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3036 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3037 // If mDrawingState has a buffer, and we are about to update again
3038 // before swapping to drawing state, then the first buffer will be
3039 // dropped and we should decrement the pending buffer count and
3040 // call any release buffer callbacks if set.
3041 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3042 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003043 mDrawingState.acquireFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003044 decrementPendingBufferCount();
3045 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3046 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3047 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
3048 mDrawingState.bufferSurfaceFrameTX.reset();
3049 }
3050 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3051 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3052 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
liulijuneb489f62022-10-17 22:02:14 +08003053 mLastClientCompositionFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003054 mLastClientCompositionFence = nullptr;
3055 }
Vishnu Nairc09c0232023-03-02 03:22:35 +00003056 } else {
3057 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3058 // we don't want to incorrectly classify a frame if we miss the desired present time.
3059 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003060 }
3061
liulijuneb489f62022-10-17 22:02:14 +08003062 mDrawingState.producerId = bufferData.producerId;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003063 mDrawingState.frameNumber = frameNumber;
3064 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3065 mDrawingState.buffer = std::move(buffer);
3066 mDrawingState.clientCacheId = bufferData.cachedBuffer;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003067 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3068 ? bufferData.acquireFence
3069 : Fence::NO_FENCE;
3070 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3071 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3072 // We latched this buffer unsiganled, so we need to pass the acquire fence
3073 // on the callback instead of just the acquire time, since it's unknown at
3074 // this point.
3075 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3076 } else {
3077 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3078 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003079 mDrawingState.latchedVsyncId = info.vsyncId;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003080 mDrawingState.modified = true;
3081 setTransactionFlags(eTransactionNeeded);
3082
3083 const int32_t layerId = getSequence();
3084 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3085 mOwnerUid, postTime, getGameMode());
3086 mDrawingState.desiredPresentTime = desiredPresentTime;
3087 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3088
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003089 if (mFlinger->mLegacyFrontEndEnabled) {
3090 recordLayerHistoryBufferUpdate(getLayerProps());
3091 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003092
3093 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3094
3095 if (dequeueTime && *dequeueTime != 0) {
3096 const uint64_t bufferId = mDrawingState.buffer->getId();
3097 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3098 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3099 FrameTracer::FrameEvent::DEQUEUE);
3100 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3101 FrameTracer::FrameEvent::QUEUE);
3102 }
3103
3104 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3105 return true;
3106}
3107
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003108void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3109 mDrawingState.desiredPresentTime = desiredPresentTime;
3110 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3111}
3112
3113void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps) {
3114 const nsecs_t presentTime = [&] {
3115 if (!mDrawingState.isAutoTimestamp) return mDrawingState.desiredPresentTime;
3116
3117 const auto prediction = mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3118 mDrawingState.latchedVsyncId);
3119 if (prediction.has_value()) return prediction->presentTime;
3120
3121 return static_cast<nsecs_t>(0);
3122 }();
3123 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3124 scheduler::LayerHistory::LayerUpdateType::Buffer);
3125}
3126
3127void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps) {
3128 const nsecs_t presentTime =
3129 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
3130 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3131 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3132}
3133
Patrick Williamsbb25f802022-08-30 23:02:34 +00003134bool Layer::setDataspace(ui::Dataspace dataspace) {
3135 mDrawingState.dataspaceRequested = true;
3136 if (mDrawingState.dataspace == dataspace) return false;
3137 mDrawingState.dataspace = dataspace;
3138 mDrawingState.modified = true;
3139 setTransactionFlags(eTransactionNeeded);
3140 return true;
3141}
3142
John Reck68796592023-01-25 13:47:12 -05003143bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07003144 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3145 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05003146 return false;
Sally Qi963049b2023-03-23 14:06:21 -07003147 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3148 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05003149 mDrawingState.modified = true;
3150 setTransactionFlags(eTransactionNeeded);
3151 return true;
3152}
3153
Alec Mourif4af03e2023-02-11 00:25:24 +00003154bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3155 if (mDrawingState.cachingHint == cachingHint) return false;
3156 mDrawingState.cachingHint = cachingHint;
3157 mDrawingState.modified = true;
3158 setTransactionFlags(eTransactionNeeded);
3159 return true;
3160}
3161
Patrick Williamsbb25f802022-08-30 23:02:34 +00003162bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3163 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3164 mDrawingState.hdrMetadata = hdrMetadata;
3165 mDrawingState.modified = true;
3166 setTransactionFlags(eTransactionNeeded);
3167 return true;
3168}
3169
3170bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003171 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003172 mDrawingState.surfaceDamageRegion = surfaceDamage;
3173 mDrawingState.modified = true;
3174 setTransactionFlags(eTransactionNeeded);
3175 return true;
3176}
3177
3178bool Layer::setApi(int32_t api) {
3179 if (mDrawingState.api == api) return false;
3180 mDrawingState.api = api;
3181 mDrawingState.modified = true;
3182 setTransactionFlags(eTransactionNeeded);
3183 return true;
3184}
3185
3186bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3187 if (mDrawingState.sidebandStream == sidebandStream) return false;
3188
3189 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3190 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3191 } else if (sidebandStream != nullptr) {
3192 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3193 }
3194
3195 mDrawingState.sidebandStream = sidebandStream;
3196 mDrawingState.modified = true;
3197 setTransactionFlags(eTransactionNeeded);
3198 if (!mSidebandStreamChanged.exchange(true)) {
3199 // mSidebandStreamChanged was false
3200 mFlinger->onLayerUpdate();
3201 }
3202 return true;
3203}
3204
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003205bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3206 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003207 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3208 if (handles.empty()) {
3209 mReleasePreviousBuffer = false;
3210 return false;
3211 }
3212
Pascal Muetschard81cef292023-02-06 12:18:52 +01003213 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003214 for (const auto& handle : handles) {
3215 // If this transaction set a buffer on this layer, release its previous buffer
3216 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3217
3218 // If this layer will be presented in this frame
3219 if (willPresent) {
3220 // If this transaction set an acquire fence on this layer, set its acquire time
3221 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3222 handle->frameNumber = mDrawingState.frameNumber;
3223
3224 // Store so latched time and release fence can be set
3225 mDrawingState.callbackHandles.push_back(handle);
3226
3227 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003228 // Queue this handle to be notified below.
3229 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003230 }
3231 }
3232
Pascal Muetschard81cef292023-02-06 12:18:52 +01003233 if (!remainingHandles.empty()) {
3234 // Notify the transaction completed threads these handles are done. These are only the
3235 // handles that were not added to the mDrawingState, which will be notified later.
3236 std::vector<JankData> jankData;
3237 transferAvailableJankData(remainingHandles, jankData);
3238 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3239 }
3240
Patrick Williamsbb25f802022-08-30 23:02:34 +00003241 mReleasePreviousBuffer = false;
3242 mCallbackHandleAcquireTimeOrFence = -1;
3243
3244 return willPresent;
3245}
3246
3247Rect Layer::getBufferSize(const State& /*s*/) const {
3248 // for buffer state layers we use the display frame size as the buffer size.
3249
3250 if (mBufferInfo.mBuffer == nullptr) {
3251 return Rect::INVALID_RECT;
3252 }
3253
3254 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3255 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3256
3257 // Undo any transformations on the buffer and return the result.
3258 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3259 std::swap(bufWidth, bufHeight);
3260 }
3261
3262 if (getTransformToDisplayInverse()) {
3263 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3264 if (invTransform & ui::Transform::ROT_90) {
3265 std::swap(bufWidth, bufHeight);
3266 }
3267 }
3268
3269 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3270}
3271
3272FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3273 if (mBufferInfo.mBuffer == nullptr) {
3274 return parentBounds;
3275 }
3276
3277 return getBufferSize(getDrawingState()).toFloatRect();
3278}
3279
3280bool Layer::fenceHasSignaled() const {
3281 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3282 return true;
3283 }
3284
3285 const bool fenceSignaled =
3286 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3287 if (!fenceSignaled) {
3288 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3289 TimeStats::LatchSkipReason::LateAcquire);
3290 }
3291
3292 return fenceSignaled;
3293}
3294
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003295void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003296 for (const auto& handle : mDrawingState.callbackHandles) {
3297 handle->refreshStartTime = refreshStartTime;
3298 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003299}
3300
3301void Layer::setAutoRefresh(bool autoRefresh) {
3302 mDrawingState.autoRefresh = autoRefresh;
3303}
3304
3305bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3306 // 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 +00003307 auto* snapshot = editLayerSnapshot();
3308 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003309
3310 if (mSidebandStreamChanged.exchange(false)) {
3311 const State& s(getDrawingState());
3312 // mSidebandStreamChanged was true
3313 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003314 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003315 if (mSidebandStream != nullptr) {
3316 setTransactionFlags(eTransactionNeeded);
3317 mFlinger->setTransactionFlags(eTraversalNeeded);
3318 }
3319 recomputeVisibleRegions = true;
3320
3321 return true;
3322 }
3323 return false;
3324}
3325
3326bool Layer::hasFrameUpdate() const {
3327 const State& c(getDrawingState());
3328 return (mDrawingStateModified || mDrawingState.modified) &&
3329 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3330}
3331
Vishnu Naird47bcee2023-02-24 18:08:51 +00003332void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003333 const State& s(getDrawingState());
3334
3335 if (!s.buffer) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003336 if (bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003337 for (auto& handle : mDrawingState.callbackHandles) {
3338 handle->latchTime = latchTime;
3339 }
3340 }
3341 return;
3342 }
3343
3344 for (auto& handle : mDrawingState.callbackHandles) {
3345 if (handle->frameNumber == mDrawingState.frameNumber) {
3346 handle->latchTime = latchTime;
3347 }
3348 }
3349
3350 const int32_t layerId = getSequence();
3351 const uint64_t bufferId = mDrawingState.buffer->getId();
3352 const uint64_t frameNumber = mDrawingState.frameNumber;
3353 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3354 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3355 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3356
3357 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3358 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3359 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3360 FrameTracer::FrameEvent::LATCH);
3361
3362 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3363 if (bufferSurfaceFrame != nullptr &&
3364 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3365 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3366 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3367 // are processing the next state.
3368 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3369 mDrawingState.acquireFenceTime->getSignalTime(),
3370 latchTime);
3371 mDrawingState.bufferSurfaceFrameTX.reset();
3372 }
3373
3374 std::deque<sp<CallbackHandle>> remainingHandles;
3375 mFlinger->getTransactionCallbackInvoker()
3376 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3377 mDrawingState.callbackHandles = remainingHandles;
3378
3379 mDrawingStateModified = false;
3380}
3381
3382void Layer::gatherBufferInfo() {
3383 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3384 decrementPendingBufferCount();
3385 }
3386
3387 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3388 mBufferInfo.mBuffer = mDrawingState.buffer;
3389 mBufferInfo.mFence = mDrawingState.acquireFence;
3390 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3391 mBufferInfo.mPixelFormat =
3392 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3393 mBufferInfo.mFrameLatencyNeeded = true;
3394 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3395 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3396 mBufferInfo.mFence = mDrawingState.acquireFence;
3397 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3398 auto lastDataspace = mBufferInfo.mDataspace;
3399 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3400 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003401 mFlinger->mHdrLayerInfoChanged = true;
3402 }
Sally Qi963049b2023-03-23 14:06:21 -07003403 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3404 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05003405 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003406 }
3407 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3408 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3409 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3410 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3411 mBufferInfo.mApi = mDrawingState.api;
3412 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003413}
3414
3415Rect Layer::computeBufferCrop(const State& s) {
3416 if (s.buffer && !s.bufferCrop.isEmpty()) {
3417 Rect bufferCrop;
3418 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3419 return bufferCrop;
3420 } else if (s.buffer) {
3421 return s.buffer->getBounds();
3422 } else {
3423 return s.bufferCrop;
3424 }
3425}
3426
3427sp<Layer> Layer::createClone() {
3428 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3429 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003430 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003431 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3432 return layer;
3433}
3434
Patrick Williamsbb25f802022-08-30 23:02:34 +00003435void Layer::decrementPendingBufferCount() {
3436 int32_t pendingBuffers = --mPendingBufferTransactions;
3437 tracePendingBufferCount(pendingBuffers);
3438}
3439
3440void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3441 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3442}
3443
3444/*
3445 * We don't want to send the layer's transform to input, but rather the
3446 * parent's transform. This is because Layer's transform is
3447 * information about how the buffer is placed on screen. The parent's
3448 * transform makes more sense to send since it's information about how the
3449 * layer is placed on screen. This transform is used by input to determine
3450 * how to go from screen space back to window space.
3451 */
3452ui::Transform Layer::getInputTransform() const {
3453 if (!hasBufferOrSidebandStream()) {
3454 return getTransform();
3455 }
3456 sp<Layer> parent = mDrawingParent.promote();
3457 if (parent == nullptr) {
3458 return ui::Transform();
3459 }
3460
3461 return parent->getTransform();
3462}
3463
3464/**
3465 * Similar to getInputTransform, we need to update the bounds to include the transform.
3466 * This is because bounds don't include the buffer transform, where the input assumes
3467 * that's already included.
3468 */
3469Rect Layer::getInputBounds() const {
3470 if (!hasBufferOrSidebandStream()) {
3471 return getCroppedBufferSize(getDrawingState());
3472 }
3473
3474 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
3475 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
3476 return bufferBounds;
3477 }
3478 return mDrawingState.transform.transform(bufferBounds);
3479}
3480
3481bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3482 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3483
3484 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3485 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3486 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3487 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3488 layer_state_t::eReparent;
3489
3490 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3491 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3492 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3493 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3494 layer_state_t::eInputInfoChanged;
3495
3496 if ((s.what & requiredFlags) != requiredFlags) {
3497 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3498 (s.what | requiredFlags) & ~s.what);
3499 return false;
3500 }
3501
3502 if (s.what & deniedFlags) {
3503 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3504 return false;
3505 }
3506
3507 if (s.what & allowedFlags) {
3508 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3509 }
3510
3511 if (s.what & layer_state_t::ePositionChanged) {
3512 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3513 ALOGV("%s: false [ePositionChanged changed]", __func__);
3514 return false;
3515 }
3516 }
3517
3518 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003519 if (mDrawingState.color.a != s.color.a) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003520 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3521 return false;
3522 }
3523 }
3524
3525 if (s.what & layer_state_t::eColorTransformChanged) {
3526 if (mDrawingState.colorTransform != s.colorTransform) {
3527 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3528 return false;
3529 }
3530 }
3531
3532 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003533 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003534 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3535 return false;
3536 }
3537 }
3538
3539 if (s.what & layer_state_t::eMatrixChanged) {
3540 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3541 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3542 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3543 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3544 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3545 return false;
3546 }
3547 }
3548
3549 if (s.what & layer_state_t::eCornerRadiusChanged) {
3550 if (mDrawingState.cornerRadius != s.cornerRadius) {
3551 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3552 return false;
3553 }
3554 }
3555
3556 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3557 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3558 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3559 return false;
3560 }
3561 }
3562
Vishnu Nairbbceb462022-10-10 04:52:13 +00003563 if (s.what & layer_state_t::eBufferTransformChanged) {
3564 if (mDrawingState.bufferTransform != s.bufferTransform) {
3565 ALOGV("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003566 return false;
3567 }
3568 }
3569
3570 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3571 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3572 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3573 return false;
3574 }
3575 }
3576
3577 if (s.what & layer_state_t::eCropChanged) {
3578 if (mDrawingState.crop != s.crop) {
3579 ALOGV("%s: false [eCropChanged changed]", __func__);
3580 return false;
3581 }
3582 }
3583
3584 if (s.what & layer_state_t::eDataspaceChanged) {
3585 if (mDrawingState.dataspace != s.dataspace) {
3586 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3587 return false;
3588 }
3589 }
3590
3591 if (s.what & layer_state_t::eHdrMetadataChanged) {
3592 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3593 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3594 return false;
3595 }
3596 }
3597
3598 if (s.what & layer_state_t::eSidebandStreamChanged) {
3599 if (mDrawingState.sidebandStream != s.sidebandStream) {
3600 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3601 return false;
3602 }
3603 }
3604
3605 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3606 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3607 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3608 return false;
3609 }
3610 }
3611
3612 if (s.what & layer_state_t::eShadowRadiusChanged) {
3613 if (mDrawingState.shadowRadius != s.shadowRadius) {
3614 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3615 return false;
3616 }
3617 }
3618
3619 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3620 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3621 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3622 return false;
3623 }
3624 }
3625
3626 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3627 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3628 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3629 return false;
3630 }
3631 }
3632
3633 if (s.what & layer_state_t::eStretchChanged) {
3634 StretchEffect temp = s.stretchEffect;
3635 temp.sanitize();
3636 if (mDrawingState.stretchEffect != temp) {
3637 ALOGV("%s: false [eStretchChanged changed]", __func__);
3638 return false;
3639 }
3640 }
3641
3642 if (s.what & layer_state_t::eBufferCropChanged) {
3643 if (mDrawingState.bufferCrop != s.bufferCrop) {
3644 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3645 return false;
3646 }
3647 }
3648
3649 if (s.what & layer_state_t::eDestinationFrameChanged) {
3650 if (mDrawingState.destinationFrame != s.destinationFrame) {
3651 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3652 return false;
3653 }
3654 }
3655
3656 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3657 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3658 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3659 return false;
3660 }
3661 }
3662
John Reck68796592023-01-25 13:47:12 -05003663 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07003664 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
3665 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
3666 ALOGV("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05003667 return false;
3668 }
3669 }
3670
Patrick Williamsbb25f802022-08-30 23:02:34 +00003671 ALOGV("%s: true", __func__);
3672 return true;
3673}
3674
3675bool Layer::isHdrY410() const {
3676 // pixel format is HDR Y410 masquerading as RGBA_1010102
3677 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3678 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3679 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3680}
3681
Vishnu Naire14c6b32022-08-06 04:20:15 +00003682sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003683 // 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 +00003684 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003685}
3686
Vishnu Naire14c6b32022-08-06 04:20:15 +00003687const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003688 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003689}
3690
Vishnu Naire14c6b32022-08-06 04:20:15 +00003691LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003692 return mSnapshot.get();
3693}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003694
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003695std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3696 return std::move(mSnapshot);
3697}
3698
3699void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3700 mSnapshot = std::move(snapshot);
3701}
3702
Patrick Williamsbb25f802022-08-30 23:02:34 +00003703const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003704 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003705}
3706
Patrick Williams7584c6a2022-10-29 02:10:58 +00003707sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003708 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003709 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3710 return result;
3711}
3712
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003713sp<LayerFE> Layer::getCompositionEngineLayerFE(
3714 const frontend::LayerHierarchy::TraversalPath& path) {
3715 for (auto& [p, layerFE] : mLayerFEs) {
3716 if (p == path) {
3717 return layerFE;
3718 }
3719 }
3720 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3721 mLayerFEs.emplace_back(path, layerFE);
3722 return layerFE;
3723}
3724
Patrick Williamsbb25f802022-08-30 23:02:34 +00003725void Layer::useSurfaceDamage() {
3726 if (mFlinger->mForceFullDamage) {
3727 surfaceDamageRegion = Region::INVALID_REGION;
3728 } else {
3729 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3730 }
3731}
3732
3733void Layer::useEmptyDamage() {
3734 surfaceDamageRegion.clear();
3735}
3736
3737bool Layer::isOpaque(const Layer::State& s) const {
3738 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3739 // layer's opaque flag.
3740 if (!hasSomethingToDraw()) {
3741 return false;
3742 }
3743
3744 // if the layer has the opaque flag, then we're always opaque
3745 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3746 return true;
3747 }
3748
3749 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003750 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003751 return true;
3752 }
3753
3754 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3755 return fillsColor() && getAlpha() == 1.0_hf;
3756}
3757
3758bool Layer::canReceiveInput() const {
3759 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3760}
3761
3762bool Layer::isVisible() const {
3763 if (!hasSomethingToDraw()) {
3764 return false;
3765 }
3766
3767 if (isHiddenByPolicy()) {
3768 return false;
3769 }
3770
3771 return getAlpha() > 0.0f || hasBlur();
3772}
3773
3774void Layer::onPostComposition(const DisplayDevice* display,
3775 const std::shared_ptr<FenceTime>& glDoneFence,
3776 const std::shared_ptr<FenceTime>& presentFence,
3777 const CompositorTiming& compositorTiming) {
3778 // mFrameLatencyNeeded is true when a new frame was latched for the
3779 // composition.
3780 if (!mBufferInfo.mFrameLatencyNeeded) return;
3781
3782 for (const auto& handle : mDrawingState.callbackHandles) {
3783 handle->gpuCompositionDoneFence = glDoneFence;
3784 handle->compositorTiming = compositorTiming;
3785 }
3786
3787 // Update mFrameTracker.
3788 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3789 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3790
3791 const int32_t layerId = getSequence();
3792 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3793
3794 const auto outputLayer = findOutputLayerForDisplay(display);
3795 if (outputLayer && outputLayer->requiresClientComposition()) {
3796 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3797 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3798 clientCompositionTimestamp,
3799 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3800 // Update the SurfaceFrames in the drawing state
3801 if (mDrawingState.bufferSurfaceFrameTX) {
3802 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3803 }
3804 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3805 surfaceFrame->setGpuComposition();
3806 }
3807 }
3808
3809 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3810 if (frameReadyFence->isValid()) {
3811 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3812 } else {
3813 // There was no fence for this frame, so assume that it was ready
3814 // to be presented at the desired present time.
3815 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3816 }
3817
3818 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08003819 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003820 const std::optional<Fps> renderRate =
3821 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3822
3823 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3824 const auto gameMode = getGameMode();
3825
3826 if (presentFence->isValid()) {
3827 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3828 refreshRate, renderRate, vote, gameMode);
3829 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3830 presentFence,
3831 FrameTracer::FrameEvent::PRESENT_FENCE);
3832 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3833 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3834 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003835 // The HWC doesn't support present fences, so use the present timestamp instead.
3836 const nsecs_t presentTimestamp =
3837 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3838
3839 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3840 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3841 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3842
Patrick Williamsbb25f802022-08-30 23:02:34 +00003843 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3844 refreshRate, renderRate, vote, gameMode);
3845 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3846 mCurrentFrameNumber, actualPresentTime,
3847 FrameTracer::FrameEvent::PRESENT_FENCE);
3848 mFrameTracker.setActualPresentTime(actualPresentTime);
3849 }
3850 }
3851
3852 mFrameTracker.advanceFrame();
3853 mBufferInfo.mFrameLatencyNeeded = false;
3854}
3855
3856bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003857 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
3858 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
3859}
3860
3861bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003862 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3863 getDrawingState().frameNumber);
3864
3865 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3866
3867 if (refreshRequired) {
3868 return refreshRequired;
3869 }
3870
3871 // If the head buffer's acquire fence hasn't signaled yet, return and
3872 // try again later
3873 if (!fenceHasSignaled()) {
3874 ATRACE_NAME("!fenceHasSignaled()");
3875 mFlinger->onLayerUpdate();
3876 return false;
3877 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00003878 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003879 if (mDrawingState.buffer == nullptr) {
3880 return false;
3881 }
3882
3883 // Capture the old state of the layer for comparisons later
3884 BufferInfo oldBufferInfo = mBufferInfo;
3885 const bool oldOpacity = isOpaque(mDrawingState);
3886 mPreviousFrameNumber = mCurrentFrameNumber;
3887 mCurrentFrameNumber = mDrawingState.frameNumber;
3888 gatherBufferInfo();
3889
3890 if (oldBufferInfo.mBuffer == nullptr) {
3891 // the first time we receive a buffer, we need to trigger a
3892 // geometry invalidation.
3893 recomputeVisibleRegions = true;
3894 }
3895
3896 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3897 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3898 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3899 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3900 recomputeVisibleRegions = true;
3901 }
3902
3903 if (oldBufferInfo.mBuffer != nullptr) {
3904 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3905 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3906 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3907 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3908 recomputeVisibleRegions = true;
3909 }
3910 }
3911
3912 if (oldOpacity != isOpaque(mDrawingState)) {
3913 recomputeVisibleRegions = true;
3914 }
3915
3916 return true;
3917}
3918
3919bool Layer::hasReadyFrame() const {
3920 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
3921}
3922
3923bool Layer::isProtected() const {
3924 return (mBufferInfo.mBuffer != nullptr) &&
3925 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
3926}
3927
Patrick Williamsbb25f802022-08-30 23:02:34 +00003928void Layer::latchAndReleaseBuffer() {
3929 if (hasReadyFrame()) {
3930 bool ignored = false;
3931 latchBuffer(ignored, systemTime());
3932 }
3933 releasePendingBuffer(systemTime());
3934}
3935
3936PixelFormat Layer::getPixelFormat() const {
3937 return mBufferInfo.mPixelFormat;
3938}
3939
3940bool Layer::getTransformToDisplayInverse() const {
3941 return mBufferInfo.mTransformToDisplayInverse;
3942}
3943
3944Rect Layer::getBufferCrop() const {
3945 // this is the crop rectangle that applies to the buffer
3946 // itself (as opposed to the window)
3947 if (!mBufferInfo.mCrop.isEmpty()) {
3948 // if the buffer crop is defined, we use that
3949 return mBufferInfo.mCrop;
3950 } else if (mBufferInfo.mBuffer != nullptr) {
3951 // otherwise we use the whole buffer
3952 return mBufferInfo.mBuffer->getBounds();
3953 } else {
3954 // if we don't have a buffer yet, we use an empty/invalid crop
3955 return Rect();
3956 }
3957}
3958
3959uint32_t Layer::getBufferTransform() const {
3960 return mBufferInfo.mTransform;
3961}
3962
3963ui::Dataspace Layer::getDataSpace() const {
3964 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
3965}
3966
3967ui::Dataspace Layer::getRequestedDataSpace() const {
3968 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
3969}
3970
3971ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
3972 ui::Dataspace updatedDataspace = dataspace;
3973 // translate legacy dataspaces to modern dataspaces
3974 switch (dataspace) {
3975 case ui::Dataspace::SRGB:
3976 updatedDataspace = ui::Dataspace::V0_SRGB;
3977 break;
3978 case ui::Dataspace::SRGB_LINEAR:
3979 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
3980 break;
3981 case ui::Dataspace::JFIF:
3982 updatedDataspace = ui::Dataspace::V0_JFIF;
3983 break;
3984 case ui::Dataspace::BT601_625:
3985 updatedDataspace = ui::Dataspace::V0_BT601_625;
3986 break;
3987 case ui::Dataspace::BT601_525:
3988 updatedDataspace = ui::Dataspace::V0_BT601_525;
3989 break;
3990 case ui::Dataspace::BT709:
3991 updatedDataspace = ui::Dataspace::V0_BT709;
3992 break;
3993 default:
3994 break;
3995 }
3996
3997 return updatedDataspace;
3998}
3999
4000sp<GraphicBuffer> Layer::getBuffer() const {
4001 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4002}
4003
Patrick Williamsbb25f802022-08-30 23:02:34 +00004004void Layer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
4005 mTransformHint = getFixedTransformHint();
4006 if (mTransformHint == ui::Transform::ROT_INVALID) {
4007 mTransformHint = displayTransformHint;
4008 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004009 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004010}
4011
4012const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4013 return mBufferInfo.mBuffer;
4014}
4015
4016bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004017 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004018 return false;
4019 }
4020
4021 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004022 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004023 mDrawingState.modified = true;
4024 setTransactionFlags(eTransactionNeeded);
4025 return true;
4026}
4027
4028bool Layer::fillsColor() const {
4029 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4030 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4031}
4032
4033bool Layer::hasBlur() const {
4034 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4035}
4036
Vishnu Nairba354102022-08-01 00:14:18 +00004037void Layer::updateSnapshot(bool updateGeometry) {
4038 if (!getCompositionEngineLayerFE()) {
4039 return;
4040 }
4041
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004042 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004043 if (updateGeometry) {
4044 prepareBasicGeometryCompositionState();
4045 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004046 snapshot->roundedCorner = getRoundedCornerState();
4047 snapshot->stretchEffect = getStretchEffect();
4048 snapshot->transformedBounds = mScreenBounds;
4049 if (mEffectiveShadowRadius > 0.f) {
4050 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4051
4052 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4053 // it if transparent regions are present. This may not be necessary since shadows are
4054 // typically cast by layers without transparent regions.
4055 snapshot->shadowSettings.boundaries = mBounds;
4056
4057 const float casterAlpha = snapshot->alpha;
4058 const bool casterIsOpaque =
4059 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4060
4061 // If the casting layer is translucent, we need to fill in the shadow underneath the
4062 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4063 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4064 snapshot->shadowSettings.ambientColor *= casterAlpha;
4065 snapshot->shadowSettings.spotColor *= casterAlpha;
4066 }
4067 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004068 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004069 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004070 snapshot->layerOpaqueFlagSet =
4071 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004072 snapshot->isHdrY410 = isHdrY410();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004073 sp<Layer> p = mDrawingParent.promote();
4074 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004075 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004076 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004077 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004078 }
4079 snapshot->bufferSize = getBufferSize(mDrawingState);
4080 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004081 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004082 preparePerFrameCompositionState();
4083}
4084
Vishnu Naire14c6b32022-08-06 04:20:15 +00004085void Layer::updateChildrenSnapshots(bool updateGeometry) {
4086 for (const sp<Layer>& child : mDrawingChildren) {
4087 child->updateSnapshot(updateGeometry);
4088 child->updateChildrenSnapshots(updateGeometry);
4089 }
4090}
4091
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004092void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4093 mSnapshot->layerMetadata = parentMetadata;
4094 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4095 for (const sp<Layer>& child : mDrawingChildren) {
4096 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4097 }
4098}
4099
4100void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4101 std::unordered_set<Layer*>& visited) {
4102 if (visited.find(this) != visited.end()) {
4103 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4104 return;
4105 }
4106 visited.insert(this);
4107
4108 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4109
4110 if (mDrawingState.zOrderRelatives.empty()) {
4111 return;
4112 }
4113 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4114 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4115 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4116 sp<Layer> relative = weakRelative.promote();
4117 if (!relative) {
4118 continue;
4119 }
4120 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4121 }
4122}
4123
Chavi Weingarten328a8312023-01-26 21:17:52 +00004124bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004125 TrustedPresentationListener const& listener) {
4126 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4127 mTrustedPresentationListener = listener;
4128 mTrustedPresentationThresholds = thresholds;
4129 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4130 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4131 mFlinger->mNumTrustedPresentationListeners++;
4132 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4133 mFlinger->mNumTrustedPresentationListeners--;
4134 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004135
4136 // Reset trusted presentation states to ensure we start the time again.
4137 mEnteredTrustedPresentationStateTime = -1;
4138 mLastReportedTrustedPresentationState = false;
4139 mLastComputedTrustedPresentationState = false;
4140
4141 // If there's a new trusted presentation listener, the code needs to go through the composite
4142 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4143 // we're already in the requested state.
4144 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004145}
4146
Vishnu Naira156f482023-02-22 00:23:38 +00004147void Layer::updateLastLatchTime(nsecs_t latchTime) {
4148 mLastLatchTime = latchTime;
4149}
4150
Mathias Agopian13127d82013-03-05 17:47:11 -08004151// ---------------------------------------------------------------------------
4152
Marin Shalamanov46084422020-10-13 12:33:42 +02004153std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004154 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4155 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004156}
4157
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004158} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004159
4160#if defined(__gl_h_)
4161#error "don't include gl/gl.h in this file"
4162#endif
4163
4164#if defined(__gl2_h_)
4165#error "don't include gl2/gl2.h in this file"
4166#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004167
4168// TODO(b/129481165): remove the #pragma below and fix conversion issues
4169#pragma clang diagnostic pop // ignored "-Wconversion"