blob: 91e32f3bfe61b81c0ce33622c229a8ba5bc08e5c [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>
Patrick Williamsbb25f802022-08-30 23:02:34 +000043#include <gui/GLConsumer.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080044#include <gui/LayerDebugInfo.h>
45#include <gui/Surface.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000046#include <gui/TraceUtils.h>
Alec Mourie60041e2019-06-14 18:59:51 -070047#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070048#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080049#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070050#include <stdint.h>
51#include <stdlib.h>
52#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000053#include <system/graphics-base-v1.0.h>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070054#include <ui/DataspaceUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080055#include <ui/DebugUtils.h>
56#include <ui/GraphicBuffer.h>
57#include <ui/PixelFormat.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058#include <utils/Errors.h>
59#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080060#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080062#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Alec Mourie60041e2019-06-14 18:59:51 -070064#include <algorithm>
65#include <mutex>
66#include <sstream>
67
Patrick Williams46b61b92022-09-01 17:25:49 +000068#include "BufferStateLayer.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070069#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080070#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070071#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070072#include "FrameTracer/FrameTracer.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080073#include "LayerProtoHelper.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080075#include "TimeStats/TimeStats.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070076#include "TunnelModeEnabledReporter.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070077
David Sodman41fdfc92017-11-06 16:09:56 -080078#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000079#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081namespace android {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010082namespace {
83constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000084
85static constexpr float defaultMaxLuminance = 1000.0;
86
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000087const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000088
89constexpr mat4 inverseOrientation(uint32_t transform) {
90 const mat4 flipH(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
91 const mat4 flipV(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1);
92 const mat4 rot90(0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
93 mat4 tr;
94
95 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
96 tr = tr * rot90;
97 }
98 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
99 tr = tr * flipH;
100 }
101 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
102 tr = tr * flipV;
103 }
104 return inverse(tr);
105}
106
107bool assignTransform(ui::Transform* dst, ui::Transform& from) {
108 if (*dst == from) {
109 return false;
110 }
111 *dst = from;
112 return true;
113}
114
115TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
116 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
117 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
118 const auto frameRateCompatibility = [frameRate] {
119 switch (frameRate.type) {
120 case Layer::FrameRateCompatibility::Default:
121 return FrameRateCompatibility::Default;
122 case Layer::FrameRateCompatibility::ExactOrMultiple:
123 return FrameRateCompatibility::ExactOrMultiple;
124 default:
125 return FrameRateCompatibility::Undefined;
126 }
127 }();
128
129 const auto seamlessness = [frameRate] {
130 switch (frameRate.seamlessness) {
131 case scheduler::Seamlessness::OnlySeamless:
132 return Seamlessness::ShouldBeSeamless;
133 case scheduler::Seamlessness::SeamedAndSeamless:
134 return Seamlessness::NotRequired;
135 default:
136 return Seamlessness::Undefined;
137 }
138 }();
139
140 return TimeStats::SetFrameRateVote{.frameRate = frameRate.rate.getValue(),
141 .frameRateCompatibility = frameRateCompatibility,
142 .seamlessness = seamlessness};
143}
144
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100145} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800146
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700147using namespace ftl::flag_operators;
148
Yiwei Zhang5434a782018-12-05 18:06:32 -0800149using base::StringAppendF;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800150using gui::GameMode;
151using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500152using gui::WindowInfo;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800153
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700154using PresentState = frametimeline::SurfaceFrame::PresentState;
155
Lloyd Piquef1c675b2018-09-12 20:45:39 -0700156std::atomic<int32_t> Layer::sSequence{1};
Mathias Agopian13127d82013-03-05 17:47:11 -0800157
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700158Layer::Layer(const LayerCreationArgs& args)
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800159 : sequence(args.sequence.value_or(sSequence++)),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700160 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000161 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700162 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800163 mWindowType(static_cast<WindowInfo::Type>(
164 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000165 mLayerCreationFlags(args.flags),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000166 mBorderEnabled(false),
167 mTextureName(args.textureName),
168 mCompositionState{mFlinger->getCompositionEngine().createLayerFECompositionState()},
169 mHwcSlotGenerator(sp<HwcSlotGenerator>::make()) {
170 ALOGV("Creating Layer %s", getDebugName());
171
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700172 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700173 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
174 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
175 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700176 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
177 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Vishnu Naira84a2202022-01-12 20:12:55 -0800178 if (args.sequence) {
179 sSequence = *args.sequence + 1;
180 }
Robert Carr6a160312021-05-17 12:08:20 -0700181 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700182 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700183 mDrawingState.z = 0;
184 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700185 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700186 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700187 mDrawingState.transform.set(0, 0);
188 mDrawingState.frameNumber = 0;
189 mDrawingState.bufferTransform = 0;
190 mDrawingState.transformToDisplayInverse = false;
191 mDrawingState.crop.makeInvalid();
192 mDrawingState.acquireFence = sp<Fence>::make(-1);
193 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
194 mDrawingState.dataspace = ui::Dataspace::UNKNOWN;
Vishnu Nairbc4ee5c2022-08-16 03:19:37 +0000195 mDrawingState.dataspaceRequested = false;
Robert Carr6a160312021-05-17 12:08:20 -0700196 mDrawingState.hdrMetadata.validTypes = 0;
197 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
198 mDrawingState.cornerRadius = 0.0f;
199 mDrawingState.backgroundBlurRadius = 0;
200 mDrawingState.api = -1;
201 mDrawingState.hasColorTransform = false;
202 mDrawingState.colorSpaceAgnostic = false;
203 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
204 mDrawingState.metadata = args.metadata;
205 mDrawingState.shadowRadius = 0.f;
206 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
207 mDrawingState.frameTimelineInfo = {};
208 mDrawingState.postTime = -1;
209 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000210 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700211 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700212 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000213 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700214
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700215 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
216 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700217 mDrawingState.color.r = -1.0_hf;
218 mDrawingState.color.g = -1.0_hf;
219 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700220 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700221
222 mFrameTracker.setDisplayRefreshPeriod(
223 args.flinger->mScheduler->getVsyncPeriodFromRefreshRateConfigs());
Robert Carr2e102c92018-10-23 12:11:15 -0700224
Vishnu Nair0f085c62019-08-30 08:49:12 -0700225 mCallingPid = args.callingPid;
226 mCallingUid = args.callingUid;
chaviw250bcbb2020-08-05 11:17:54 -0700227
228 if (mCallingUid == AID_GRAPHICS || mCallingUid == AID_SYSTEM) {
229 // If the system didn't send an ownerUid, use the callingUid for the ownerUid.
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800230 mOwnerUid = args.metadata.getInt32(gui::METADATA_OWNER_UID, mCallingUid);
231 mOwnerPid = args.metadata.getInt32(gui::METADATA_OWNER_PID, mCallingPid);
chaviw250bcbb2020-08-05 11:17:54 -0700232 } else {
233 // A create layer request from a non system request cannot specify the owner uid
234 mOwnerUid = mCallingUid;
Adithya Srinivasan9febda82020-10-19 10:49:41 -0700235 mOwnerPid = mCallingPid;
chaviw250bcbb2020-08-05 11:17:54 -0700236 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000237
238 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
239 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
240 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
241 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Dominik Laskowski75848362019-11-11 17:57:20 -0800242}
243
244void Layer::onFirstRef() {
245 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700246}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700247
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700248Layer::~Layer() {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000249 // The original layer and the clone layer share the same texture and buffer. Therefore, only
250 // one of the layers, in this case the original layer, needs to handle the deletion. The
251 // original layer and the clone should be removed at the same time so there shouldn't be any
252 // issue with the clone layer trying to use the texture.
253 if (mBufferInfo.mBuffer != nullptr) {
254 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
255 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
256 mBufferInfo.mFence,
257 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
258 mOwnerUid));
259 }
260 if (!isClone()) {
261 // The original layer and the clone layer share the same texture. Therefore, only one of
262 // the layers, in this case the original layer, needs to handle the deletion. The original
263 // layer and the clone should be removed at the same time so there shouldn't be any issue
264 // with the clone layer trying to use the deleted texture.
265 mFlinger->deleteTextureAsync(mTextureName);
266 }
267 const int32_t layerId = getSequence();
268 mFlinger->mTimeStats->onDestroy(layerId);
269 mFlinger->mFrameTracer->onDestroy(layerId);
270
David Sodman577c8962017-12-08 14:50:53 -0800271 sp<Client> c(mClientRef.promote());
272 if (c != 0) {
273 c->detachLayer(this);
274 }
275
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000276 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700277 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700278
279 if (mDrawingState.sidebandStream != nullptr) {
280 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
281 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700282 if (mHadClonedChild) {
283 mFlinger->mNumClones--;
284 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700285}
286
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700287LayerCreationArgs::LayerCreationArgs(SurfaceFlinger* flinger, sp<Client> client, std::string name,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800288 uint32_t flags, LayerMetadata metadata)
Vishnu Nair0f085c62019-08-30 08:49:12 -0700289 : flinger(flinger),
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700290 client(std::move(client)),
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700291 name(std::move(name)),
Vishnu Nair0f085c62019-08-30 08:49:12 -0700292 flags(flags),
293 metadata(std::move(metadata)) {
294 IPCThreadState* ipc = IPCThreadState::self();
295 callingPid = ipc->getCallingPid();
296 callingUid = ipc->getCallingUid();
297}
298
Mathias Agopian13127d82013-03-05 17:47:11 -0800299// ---------------------------------------------------------------------------
300// callbacks
301// ---------------------------------------------------------------------------
302
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700303void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700304 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700305 return;
306 }
Robert Carr2e102c92018-10-23 12:11:15 -0700307
Robert Carr6a160312021-05-17 12:08:20 -0700308 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700309 if (strongRelative == nullptr) {
310 setZOrderRelativeOf(nullptr);
311 return;
312 }
313
314 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700315 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700316 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800317 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700318 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700319}
320
321void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700322 if (!mRemovedFromDrawingState) {
323 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700324 mFlinger->mScheduler->deregisterLayer(this);
325 }
Rob Carr4bba3702018-10-08 21:53:30 +0000326
Ady Abrahamd11bade2022-08-01 16:18:03 -0700327 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700328}
Chia-I Wu38512252017-05-17 14:36:16 -0700329
chaviw68d4dab2020-06-08 15:07:32 -0700330sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000331 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700332 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700333 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700334 }
335 return parent->getRootLayer();
336}
337
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700338void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700339 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
340 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700341 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700342
343 traverse(LayerVector::StateSet::Current, [&](Layer* layer) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700344 layer->removeFromCurrentState();
345 layer->removeRelativeZ(layersInTree);
chaviw68d4dab2020-06-08 15:07:32 -0700346 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700347}
348
chaviw61626f22018-11-15 16:26:27 -0800349void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700350 if (mRemovedFromDrawingState) {
351 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700352 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700353 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700354 }
chaviw61626f22018-11-15 16:26:27 -0800355
356 for (const auto& child : mCurrentChildren) {
357 child->addToCurrentState();
358 }
359}
360
Mathias Agopian13127d82013-03-05 17:47:11 -0800361// ---------------------------------------------------------------------------
362// set-up
363// ---------------------------------------------------------------------------
364
chaviw13fdc492017-06-27 12:40:18 -0700365bool Layer::getPremultipledAlpha() const {
366 return mPremultipliedAlpha;
367}
368
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700369sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800370 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700371 if (mGetHandleCalled) {
372 ALOGE("Get handle called twice" );
373 return nullptr;
374 }
375 mGetHandleCalled = true;
Ady Abrahamd11bade2022-08-01 16:18:03 -0700376 return sp<Handle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800377}
378
379// ---------------------------------------------------------------------------
380// h/w composer set-up
381// ---------------------------------------------------------------------------
382
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700383static Rect reduce(const Rect& win, const Region& exclude) {
384 if (CC_LIKELY(exclude.isEmpty())) {
385 return win;
386 }
387 if (exclude.isRect()) {
388 return win.reduce(exclude.getBounds());
389 }
390 return Region(win).subtract(exclude).getBounds();
391}
392
Dan Stoza80d61162017-12-20 15:57:52 -0800393static FloatRect reduce(const FloatRect& win, const Region& exclude) {
394 if (CC_LIKELY(exclude.isEmpty())) {
395 return win;
396 }
397 // Convert through Rect (by rounding) for lack of FloatRegion
398 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
399}
400
Vishnu Nair4351ad52019-02-11 14:13:02 -0800401Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800402 if (!reduceTransparentRegion) {
403 return Rect{mScreenBounds};
404 }
405
406 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800407 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800408 // Transform to screen space.
409 bounds = t.transform(bounds);
410 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700411}
412
Vishnu Nair4351ad52019-02-11 14:13:02 -0800413FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000414 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800415 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700416}
417
Vishnu Nairf0c28512019-02-08 12:40:28 -0800418FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
419 // Subtract the transparent region and snap to the bounds.
420 return reduce(mBounds, activeTransparentRegion);
421}
422
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700423void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
424 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800425 const State& s(getDrawingState());
426
427 // Calculate effective layer transform
428 mEffectiveTransform = parentTransform * getActiveTransform(s);
429
Garfield Tan2c1782c2022-02-16 15:25:05 -0800430 if (CC_UNLIKELY(!isTransformValid())) {
431 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
432 getDebugName());
433 return;
434 }
435
Vishnu Nair4351ad52019-02-11 14:13:02 -0800436 // Transform parent bounds to layer space
437 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
438
Vishnu Nairc652ff82019-03-15 12:48:54 -0700439 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800440 mSourceBounds = computeSourceBounds(parentBounds);
441
442 // Calculate bounds by croping diplay frame with layer crop and parent bounds
443 FloatRect bounds = mSourceBounds;
444 const Rect layerCrop = getCrop(s);
445 if (!layerCrop.isEmpty()) {
446 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
447 }
448 bounds = bounds.intersect(parentBounds);
449
450 mBounds = bounds;
451 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700452
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700453 // Use the layer's own shadow radius if set. Otherwise get the radius from
454 // parent.
455 if (s.shadowRadius > 0.f) {
456 mEffectiveShadowRadius = s.shadowRadius;
457 } else {
458 mEffectiveShadowRadius = parentShadowRadius;
459 }
460
461 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
462 // don't pass it to its children.
463 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
464
Vishnu Nair4351ad52019-02-11 14:13:02 -0800465 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700466 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800467 }
Vishnu Nairba354102022-08-01 00:14:18 +0000468
469 if (mPotentialCursor) {
470 prepareCursorCompositionState();
471 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800472}
473
Vishnu Nair60356342018-11-13 13:00:45 -0800474Rect Layer::getCroppedBufferSize(const State& s) const {
475 Rect size = getBufferSize(s);
476 Rect crop = getCrop(s);
477 if (!crop.isEmpty() && size.isValid()) {
478 size.intersect(crop, &size);
479 } else if (!crop.isEmpty()) {
480 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700481 }
Vishnu Nair60356342018-11-13 13:00:45 -0800482 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800483}
484
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700485void Layer::setupRoundedCornersCropCoordinates(Rect win,
486 const FloatRect& roundedCornersCrop) const {
487 // Translate win by the rounded corners rect coordinates, to have all values in
488 // layer coordinate space.
489 win.left -= roundedCornersCrop.left;
490 win.right -= roundedCornersCrop.left;
491 win.top -= roundedCornersCrop.top;
492 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700493}
494
Lloyd Piquede196652020-01-22 17:29:58 -0800495void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800496 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800497 const auto alpha = static_cast<float>(getAlpha());
498 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700499 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800500
501 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
502 if (!opaque || alpha != 1.0f) {
503 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
504 : Hwc2::IComposerClient::BlendMode::COVERAGE;
505 }
506
Lloyd Piquede196652020-01-22 17:29:58 -0800507 auto* compositionState = editCompositionState();
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700508 compositionState->outputFilter = getOutputFilter();
Lloyd Piquede196652020-01-22 17:29:58 -0800509 compositionState->isVisible = isVisible();
510 compositionState->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
511 compositionState->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800512
Lloyd Piquede196652020-01-22 17:29:58 -0800513 compositionState->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800514 contentDirty = false;
515
Lloyd Piquede196652020-01-22 17:29:58 -0800516 compositionState->geomLayerBounds = mBounds;
517 compositionState->geomLayerTransform = getTransform();
518 compositionState->geomInverseLayerTransform = compositionState->geomLayerTransform.inverse();
519 compositionState->transparentRegionHint = getActiveTransparentRegion(drawingState);
Lloyd Piquec6687342019-03-07 21:34:57 -0800520
Lloyd Piquede196652020-01-22 17:29:58 -0800521 compositionState->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
522 compositionState->alpha = alpha;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400523 compositionState->backgroundBlurRadius = drawingState.backgroundBlurRadius;
524 compositionState->blurRegions = drawingState.blurRegions;
John Reckc00c6692021-02-16 11:37:33 -0500525 compositionState->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800526}
527
Lloyd Piquede196652020-01-22 17:29:58 -0800528void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800529 const auto& drawingState{getDrawingState()};
Lloyd Piquede196652020-01-22 17:29:58 -0800530 auto* compositionState = editCompositionState();
David Sodman15094112018-10-11 09:39:37 -0700531
Lloyd Piquede196652020-01-22 17:29:58 -0800532 compositionState->geomBufferSize = getBufferSize(drawingState);
533 compositionState->geomContentCrop = getBufferCrop();
534 compositionState->geomCrop = getCrop(drawingState);
535 compositionState->geomBufferTransform = getBufferTransform();
536 compositionState->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
537 compositionState->geomUsesSourceCrop = usesSourceCrop();
538 compositionState->isSecure = isSecure();
539
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800540 compositionState->metadata.clear();
541 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
542 for (const auto& [key, mandatory] : supportedMetadata) {
543 const auto& genericLayerMetadataCompatibilityMap =
544 mFlinger->getGenericLayerMetadataKeyMap();
545 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
546 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
547 continue;
548 }
549 const uint32_t id = compatIter->second;
550
551 auto it = drawingState.metadata.mMap.find(id);
552 if (it == std::end(drawingState.metadata.mMap)) {
553 continue;
554 }
555
556 compositionState->metadata
557 .emplace(key, compositionengine::GenericLayerMetadataEntry{mandatory, it->second});
558 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800559}
David Sodmanba340492018-08-05 21:51:33 -0700560
Lloyd Piquede196652020-01-22 17:29:58 -0800561void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800562 const auto& drawingState{getDrawingState()};
Lloyd Piquede196652020-01-22 17:29:58 -0800563 auto* compositionState = editCompositionState();
Lloyd Piquef5275482019-01-29 18:42:42 -0800564
Lloyd Piquede196652020-01-22 17:29:58 -0800565 compositionState->forceClientComposition = false;
566
567 compositionState->isColorspaceAgnostic = isColorSpaceAgnostic();
568 compositionState->dataspace = getDataSpace();
569 compositionState->colorTransform = getColorTransform();
570 compositionState->colorTransformIsIdentity = !hasColorTransform();
571 compositionState->surfaceDamage = surfaceDamageRegion;
572 compositionState->hasProtectedContent = isProtected();
Sally Qi81d95e62022-03-21 19:41:33 -0700573 compositionState->dimmingEnabled = isDimmingEnabled();
Lloyd Pique688abd42019-02-15 15:42:24 -0800574
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700575 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700576
Lloyd Piquede196652020-01-22 17:29:58 -0800577 compositionState->isOpaque =
Lloyd Pique688abd42019-02-15 15:42:24 -0800578 isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800579
580 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400581 // Rounded corners no longer force client composition, since we may use a
582 // hole punch so that the layer will appear to have rounded corners.
583 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
John Reckc00c6692021-02-16 11:37:33 -0500584 compositionState->stretchEffect.hasEffect()) {
Lloyd Piquede196652020-01-22 17:29:58 -0800585 compositionState->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800586 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700587 // If there are no visible region changes, we still need to update blur parameters.
588 compositionState->blurRegions = drawingState.blurRegions;
589 compositionState->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400590
591 // Layer framerate is used in caching decisions.
592 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
593 // LayerFECompositionState where it would be visible to Flattener.
594 compositionState->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000595
596 if (hasBufferOrSidebandStream()) {
597 preparePerFrameBufferCompositionState();
598 } else {
599 preparePerFrameEffectsCompositionState();
600 }
601}
602
603void Layer::preparePerFrameBufferCompositionState() {
604 // Sideband layers
605 auto* compositionState = editCompositionState();
606 if (compositionState->sidebandStream.get() && !compositionState->sidebandStreamHasFrame) {
607 compositionState->compositionType =
608 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
609 return;
610 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
611 compositionState->compositionType =
612 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
613 } else {
614 // Normal buffer layers
615 compositionState->hdrMetadata = mBufferInfo.mHdrMetadata;
616 compositionState->compositionType = mPotentialCursor
617 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
618 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
619 }
620
621 compositionState->buffer = getBuffer();
622 compositionState->bufferSlot = (mBufferInfo.mBufferSlot == BufferQueue::INVALID_BUFFER_SLOT)
623 ? 0
624 : mBufferInfo.mBufferSlot;
625 compositionState->acquireFence = mBufferInfo.mFence;
626 compositionState->frameNumber = mBufferInfo.mFrameNumber;
627 compositionState->sidebandStreamHasFrame = false;
628}
629
630void Layer::preparePerFrameEffectsCompositionState() {
631 auto* compositionState = editCompositionState();
632 compositionState->color = getColor();
633 compositionState->compositionType =
634 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800635}
636
Lloyd Piquede196652020-01-22 17:29:58 -0800637void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800638 const State& drawingState{getDrawingState()};
Lloyd Piquede196652020-01-22 17:29:58 -0800639 auto* compositionState = editCompositionState();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800640
641 // Apply the layer's transform, followed by the display's global transform
642 // Here we're guaranteed that the layer's transform preserves rects
643 Rect win = getCroppedBufferSize(drawingState);
644 // Subtract the transparent region and snap to the bounds
645 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
646 Rect frame(getTransform().transform(bounds));
647
Lloyd Piquede196652020-01-22 17:29:58 -0800648 compositionState->cursorFrame = frame;
649}
650
651sp<compositionengine::LayerFE> Layer::asLayerFE() const {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700652 compositionengine::LayerFE* layerFE = const_cast<compositionengine::LayerFE*>(
Lloyd Piquede196652020-01-22 17:29:58 -0800653 static_cast<const compositionengine::LayerFE*>(this));
Ady Abrahamd11bade2022-08-01 16:18:03 -0700654 return sp<compositionengine::LayerFE>::fromExisting(layerFE);
Lloyd Piquede196652020-01-22 17:29:58 -0800655}
656
Lloyd Piquea83776c2019-01-29 18:42:32 -0800657const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700658 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800659}
660
Mathias Agopian13127d82013-03-05 17:47:11 -0800661// ---------------------------------------------------------------------------
662// drawing...
663// ---------------------------------------------------------------------------
664
Vishnu Nair9b079a22020-01-21 14:36:08 -0800665std::optional<compositionengine::LayerFE::LayerSettings> Layer::prepareClientComposition(
Patrick Williams16d8b2c2022-08-08 17:29:05 +0000666 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000667 std::optional<compositionengine::LayerFE::LayerSettings> layerSettings =
668 prepareClientCompositionInternal(targetSettings);
669 // Nothing to render.
670 if (!layerSettings) {
671 return {};
672 }
673
674 // HWC requests to clear this layer.
675 if (targetSettings.clearContent) {
676 prepareClearClientComposition(*layerSettings, false /* blackout */);
677 return layerSettings;
678 }
679
680 // set the shadow for the layer if needed
681 prepareShadowClientComposition(*layerSettings, targetSettings.viewport);
682
683 return layerSettings;
684}
685
686std::optional<compositionengine::LayerFE::LayerSettings> Layer::prepareClientCompositionInternal(
687 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
688 ATRACE_CALL();
689
Lloyd Piquede196652020-01-22 17:29:58 -0800690 if (!getCompositionState()) {
Lloyd Piquef16688f2019-02-19 17:47:57 -0800691 return {};
692 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800693
Vishnu Nair4351ad52019-02-11 14:13:02 -0800694 FloatRect bounds = getBounds();
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000695 half alpha = getAlpha();
Vishnu Nair9b079a22020-01-21 14:36:08 -0800696
697 compositionengine::LayerFE::LayerSettings layerSettings;
Lloyd Piquef16688f2019-02-19 17:47:57 -0800698 layerSettings.geometry.boundaries = bounds;
chaviwc6ad8af2020-08-03 11:33:30 -0700699 layerSettings.geometry.positionTransform = getTransform().asMatrix4();
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000700
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400701 // skip drawing content if the targetSettings indicate the content will be occluded
Ady Abrahambaa6cf52021-07-13 14:02:19 -0700702 const bool drawContent = targetSettings.realContentIsVisible || targetSettings.clearContent;
703 layerSettings.skipContentDraw = !drawContent;
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400704
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000705 if (hasColorTransform()) {
Lloyd Piquef16688f2019-02-19 17:47:57 -0800706 layerSettings.colorTransform = getColorTransform();
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000707 }
708
709 const auto roundedCornerState = getRoundedCornerState();
Lloyd Piquef16688f2019-02-19 17:47:57 -0800710 layerSettings.geometry.roundedCornersRadius = roundedCornerState.radius;
711 layerSettings.geometry.roundedCornersCrop = roundedCornerState.cropRect;
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000712
Lloyd Piquef16688f2019-02-19 17:47:57 -0800713 layerSettings.alpha = alpha;
chaviw4244e032019-09-04 11:27:49 -0700714 layerSettings.sourceDataspace = getDataSpace();
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700715
Alec Mouridda07d92022-04-25 22:39:25 +0000716 // Override the dataspace transfer from 170M to sRGB if the device configuration requests this.
717 // We do this here instead of in buffer info so that dumpsys can still report layers that are
718 // using the 170M transfer.
719 if (mFlinger->mTreat170mAsSrgb &&
720 (layerSettings.sourceDataspace & HAL_DATASPACE_TRANSFER_MASK) ==
721 HAL_DATASPACE_TRANSFER_SMPTE_170M) {
722 layerSettings.sourceDataspace = static_cast<ui::Dataspace>(
723 (layerSettings.sourceDataspace & HAL_DATASPACE_STANDARD_MASK) |
724 (layerSettings.sourceDataspace & HAL_DATASPACE_RANGE_MASK) |
725 HAL_DATASPACE_TRANSFER_SRGB);
726 }
727
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700728 layerSettings.whitePointNits = targetSettings.whitePointNits;
Alec Mourif54453c2021-05-13 16:28:28 -0700729 switch (targetSettings.blurSetting) {
730 case LayerFE::ClientCompositionTargetSettings::BlurSetting::Enabled:
731 layerSettings.backgroundBlurRadius = getBackgroundBlurRadius();
732 layerSettings.blurRegions = getBlurRegions();
733 layerSettings.blurRegionTransform =
734 getActiveTransform(getDrawingState()).inverse().asMatrix4();
735 break;
736 case LayerFE::ClientCompositionTargetSettings::BlurSetting::BackgroundBlurOnly:
737 layerSettings.backgroundBlurRadius = getBackgroundBlurRadius();
738 break;
739 case LayerFE::ClientCompositionTargetSettings::BlurSetting::BlurRegionsOnly:
740 layerSettings.blurRegions = getBlurRegions();
741 layerSettings.blurRegionTransform =
742 getActiveTransform(getDrawingState()).inverse().asMatrix4();
743 break;
744 case LayerFE::ClientCompositionTargetSettings::BlurSetting::Disabled:
745 default:
746 break;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +0100747 }
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700748 layerSettings.stretchEffect = getStretchEffect();
Ana Krulec6eab17a2020-12-09 15:52:36 -0800749 // Record the name of the layer for debugging further down the stack.
750 layerSettings.name = getName();
Patrick Williamsbb25f802022-08-30 23:02:34 +0000751
Vishnu Nairf115db82022-09-06 16:59:33 -0700752 if (hasEffect() && !hasBufferOrSidebandStream()) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000753 prepareEffectsClientComposition(layerSettings, targetSettings);
754 return layerSettings;
755 }
756
757 prepareBufferStateClientComposition(layerSettings, targetSettings);
Lloyd Piquef16688f2019-02-19 17:47:57 -0800758 return layerSettings;
Mathias Agopian13127d82013-03-05 17:47:11 -0800759}
760
Vishnu Nairb87d94f2020-02-13 09:17:36 -0800761void Layer::prepareClearClientComposition(LayerFE::LayerSettings& layerSettings,
762 bool blackout) const {
763 layerSettings.source.buffer.buffer = nullptr;
764 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
765 layerSettings.disableBlending = true;
Vishnu Nair3b653e72020-02-24 16:40:50 -0800766 layerSettings.bufferId = 0;
Vishnu Nairb87d94f2020-02-13 09:17:36 -0800767 layerSettings.frameNumber = 0;
768
769 // If layer is blacked out, force alpha to 1 so that we draw a black color layer.
770 layerSettings.alpha = blackout ? 1.0f : 0.0f;
Alec Mouribd17b3b2020-12-17 11:08:30 -0800771 layerSettings.name = getName();
Vishnu Nairb87d94f2020-02-13 09:17:36 -0800772}
773
Patrick Williamsbb25f802022-08-30 23:02:34 +0000774void Layer::prepareEffectsClientComposition(
775 compositionengine::LayerFE::LayerSettings& layerSettings,
776 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
777 // If fill bounds are occluded or the fill color is invalid skip the fill settings.
778 if (targetSettings.realContentIsVisible && fillsColor()) {
779 // Set color for color fill settings.
780 layerSettings.source.solidColor = getColor().rgb;
781 } else if (hasBlur() || drawShadows()) {
782 layerSettings.skipContentDraw = true;
783 }
784}
785
786void Layer::prepareBufferStateClientComposition(
787 compositionengine::LayerFE::LayerSettings& layerSettings,
788 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
Patrick Williams22e33d62022-09-02 19:18:16 +0000789 if (CC_UNLIKELY(!mBufferInfo.mBuffer)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000790 // For surfaceview of tv sideband, there is no activeBuffer
791 // in bufferqueue, we need return LayerSettings.
792 return;
793 }
794 const bool blackOutLayer = (isProtected() && !targetSettings.supportsProtectedContent) ||
795 ((isSecure() || isProtected()) && !targetSettings.isSecure);
796 const bool bufferCanBeUsedAsHwTexture =
797 mBufferInfo.mBuffer->getUsage() & GraphicBuffer::USAGE_HW_TEXTURE;
798 if (blackOutLayer || !bufferCanBeUsedAsHwTexture) {
799 ALOGE_IF(!bufferCanBeUsedAsHwTexture, "%s is blacked out as buffer is not gpu readable",
800 mName.c_str());
801 prepareClearClientComposition(layerSettings, true /* blackout */);
802 return;
803 }
804
805 const State& s(getDrawingState());
806 layerSettings.source.buffer.buffer = mBufferInfo.mBuffer;
807 layerSettings.source.buffer.isOpaque = isOpaque(s);
808 layerSettings.source.buffer.fence = mBufferInfo.mFence;
809 layerSettings.source.buffer.textureName = mTextureName;
810 layerSettings.source.buffer.usePremultipliedAlpha = getPremultipledAlpha();
811 layerSettings.source.buffer.isY410BT2020 = isHdrY410();
812 bool hasSmpte2086 = mBufferInfo.mHdrMetadata.validTypes & HdrMetadata::SMPTE2086;
813 bool hasCta861_3 = mBufferInfo.mHdrMetadata.validTypes & HdrMetadata::CTA861_3;
814 float maxLuminance = 0.f;
815 if (hasSmpte2086 && hasCta861_3) {
816 maxLuminance = std::min(mBufferInfo.mHdrMetadata.smpte2086.maxLuminance,
817 mBufferInfo.mHdrMetadata.cta8613.maxContentLightLevel);
818 } else if (hasSmpte2086) {
819 maxLuminance = mBufferInfo.mHdrMetadata.smpte2086.maxLuminance;
820 } else if (hasCta861_3) {
821 maxLuminance = mBufferInfo.mHdrMetadata.cta8613.maxContentLightLevel;
822 } else {
823 switch (layerSettings.sourceDataspace & HAL_DATASPACE_TRANSFER_MASK) {
824 case HAL_DATASPACE_TRANSFER_ST2084:
825 case HAL_DATASPACE_TRANSFER_HLG:
826 // Behavior-match previous releases for HDR content
827 maxLuminance = defaultMaxLuminance;
828 break;
829 }
830 }
831 layerSettings.source.buffer.maxLuminanceNits = maxLuminance;
832 layerSettings.frameNumber = mCurrentFrameNumber;
833 layerSettings.bufferId = mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getId() : 0;
834
835 const bool useFiltering =
836 targetSettings.needsFiltering || mNeedsFiltering || bufferNeedsFiltering();
837
838 // Query the texture matrix given our current filtering mode.
839 float textureMatrix[16];
840 getDrawingTransformMatrix(useFiltering, textureMatrix);
841
842 if (getTransformToDisplayInverse()) {
843 /*
844 * the code below applies the primary display's inverse transform to
845 * the texture transform
846 */
847 uint32_t transform = DisplayDevice::getPrimaryDisplayRotationFlags();
848 mat4 tr = inverseOrientation(transform);
849
850 /**
851 * TODO(b/36727915): This is basically a hack.
852 *
853 * Ensure that regardless of the parent transformation,
854 * this buffer is always transformed from native display
855 * orientation to display orientation. For example, in the case
856 * of a camera where the buffer remains in native orientation,
857 * we want the pixels to always be upright.
858 */
859 sp<Layer> p = mDrawingParent.promote();
860 if (p != nullptr) {
861 const auto parentTransform = p->getTransform();
862 tr = tr * inverseOrientation(parentTransform.getOrientation());
863 }
864
865 // and finally apply it to the original texture matrix
866 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
867 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
868 }
869
870 const Rect win{getBounds()};
871 float bufferWidth = getBufferSize(s).getWidth();
872 float bufferHeight = getBufferSize(s).getHeight();
873
874 // BufferStateLayers can have a "buffer size" of [0, 0, -1, -1] when no display frame has
875 // been set and there is no parent layer bounds. In that case, the scale is meaningless so
876 // ignore them.
877 if (!getBufferSize(s).isValid()) {
878 bufferWidth = float(win.right) - float(win.left);
879 bufferHeight = float(win.bottom) - float(win.top);
880 }
881
882 const float scaleHeight = (float(win.bottom) - float(win.top)) / bufferHeight;
883 const float scaleWidth = (float(win.right) - float(win.left)) / bufferWidth;
884 const float translateY = float(win.top) / bufferHeight;
885 const float translateX = float(win.left) / bufferWidth;
886
887 // Flip y-coordinates because GLConsumer expects OpenGL convention.
888 mat4 tr = mat4::translate(vec4(.5f, .5f, 0.f, 1.f)) * mat4::scale(vec4(1.f, -1.f, 1.f, 1.f)) *
889 mat4::translate(vec4(-.5f, -.5f, 0.f, 1.f)) *
890 mat4::translate(vec4(translateX, translateY, 0.f, 1.f)) *
891 mat4::scale(vec4(scaleWidth, scaleHeight, 1.0f, 1.0f));
892
893 layerSettings.source.buffer.useTextureFiltering = useFiltering;
894 layerSettings.source.buffer.textureTransform =
895 mat4(static_cast<const float*>(textureMatrix)) * tr;
896
897 return;
898}
899
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500900aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
901 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700902 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800903 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500904 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800905 }
906 if (outputLayer->getState().hwc) {
907 return (*outputLayer->getState().hwc).hwcCompositionType;
908 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500909 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800910 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800911}
912
Mathias Agopian13127d82013-03-05 17:47:11 -0800913// ----------------------------------------------------------------------------
914// local state
915// ----------------------------------------------------------------------------
916
David Sodman41fdfc92017-11-06 16:09:56 -0800917bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800918 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700919 if (s.flags & layer_state_t::eLayerSecure) {
920 return true;
921 }
922
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000923 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700924 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700925}
926
Mathias Agopian13127d82013-03-05 17:47:11 -0800927// ----------------------------------------------------------------------------
928// transaction
929// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800930
Marissa Wall61c58622018-07-18 10:12:20 -0700931uint32_t Layer::doTransaction(uint32_t flags) {
932 ATRACE_CALL();
933
Robert Carr0758e5d2021-03-11 22:15:04 -0800934 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700935 mDrawingStateModified = mDrawingState.modified;
936 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700937
Alec Mourib416efd2018-09-06 21:01:59 +0000938 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700939
Robert Carr6a160312021-05-17 12:08:20 -0700940 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800941 // invalidate and recompute the visible regions if needed
942 flags |= Layer::eVisibleRegion;
943 }
944
Robert Carr6a160312021-05-17 12:08:20 -0700945 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800946 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000947 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800948 flags |= eVisibleRegion;
949 this->contentDirty = true;
950
951 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700952 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800953 }
954
Arthur Hung9ed43392022-05-27 06:31:57 +0000955 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
956 mFlinger->mUpdateInputInfo = true;
957 }
958
Robert Carr6a160312021-05-17 12:08:20 -0700959 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800960
Mathias Agopian13127d82013-03-05 17:47:11 -0800961 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800962}
963
Robert Carr6a160312021-05-17 12:08:20 -0700964void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000965 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
966 // bufferSurfaceFrameTX will be presented in latchBuffer.
967 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
968 if (surfaceFrame->getPresentState() != PresentState::Presented) {
969 // With applyPendingStates, we could end up having presented surfaceframes from previous
970 // states
971 surfaceFrame->setPresentState(PresentState::Presented);
972 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
973 }
974 }
Robert Carr6a160312021-05-17 12:08:20 -0700975 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700976}
977
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700978uint32_t Layer::clearTransactionFlags(uint32_t mask) {
979 const auto flags = mTransactionFlags & mask;
980 mTransactionFlags &= ~mask;
981 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800982}
983
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700984void Layer::setTransactionFlags(uint32_t mask) {
985 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800986}
987
Robert Carr1f0a16a2016-10-24 16:27:39 -0700988bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
989 ssize_t idx = mCurrentChildren.indexOf(childLayer);
990 if (idx < 0) {
991 return false;
992 }
993 if (childLayer->setLayer(z)) {
994 mCurrentChildren.removeAt(idx);
995 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800996 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700997 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800998 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700999}
1000
Robert Carr503c7042017-09-27 15:06:08 -07001001bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
1002 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
1003 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1004 if (idx < 0) {
1005 return false;
1006 }
1007 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
1008 mCurrentChildren.removeAt(idx);
1009 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -08001010 return true;
Robert Carr503c7042017-09-27 15:06:08 -07001011 }
Robert Carr503d2bd2017-12-04 15:49:47 -08001012 return false;
Robert Carr503c7042017-09-27 15:06:08 -07001013}
1014
Robert Carrae060832016-11-28 10:51:00 -08001015bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -07001016 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
1017 mDrawingState.sequence++;
1018 mDrawingState.z = z;
1019 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001020
Robert Carra70e91c2021-06-11 13:59:52 -07001021 mFlinger->mSomeChildrenChanged = true;
1022
Robert Carrdb66e622017-04-10 16:55:57 -07001023 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -07001024 if (mDrawingState.zOrderRelativeOf != nullptr) {
1025 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -07001026 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001027 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -07001028 }
chaviw606e5cf2019-03-01 10:12:10 -08001029 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -07001030 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001031 setTransactionFlags(eTransactionNeeded);
1032 return true;
1033}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001034
Robert Carrdb66e622017-04-10 16:55:57 -07001035void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -07001036 mDrawingState.zOrderRelatives.remove(relative);
1037 mDrawingState.sequence++;
1038 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001039 setTransactionFlags(eTransactionNeeded);
1040}
1041
1042void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -07001043 mDrawingState.zOrderRelatives.add(relative);
1044 mDrawingState.modified = true;
1045 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -07001046 setTransactionFlags(eTransactionNeeded);
1047}
1048
chaviw606e5cf2019-03-01 10:12:10 -08001049void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -07001050 mDrawingState.zOrderRelativeOf = relativeOf;
1051 mDrawingState.sequence++;
1052 mDrawingState.modified = true;
1053 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -07001054
chaviw606e5cf2019-03-01 10:12:10 -08001055 setTransactionFlags(eTransactionNeeded);
1056}
1057
Robert Carr503d2bd2017-12-04 15:49:47 -08001058bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nairf9096652021-07-20 18:49:42 -07001059 sp<Layer> relative = fromHandle(relativeToHandle).promote();
Robert Carrdb66e622017-04-10 16:55:57 -07001060 if (relative == nullptr) {
1061 return false;
1062 }
1063
Robert Carr6a160312021-05-17 12:08:20 -07001064 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
1065 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -08001066 return false;
1067 }
1068
Robert Carr88b85e12022-03-21 15:47:35 -07001069 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
1070 (relative->mDrawingState.zOrderRelativeOf == this)) {
1071 ALOGE("Detected relative layer loop between %s and %s",
1072 mName.c_str(), relative->mName.c_str());
1073 ALOGE("Ignoring new call to set relative layer");
1074 return false;
1075 }
1076
Robert Carra70e91c2021-06-11 13:59:52 -07001077 mFlinger->mSomeChildrenChanged = true;
1078
Robert Carr6a160312021-05-17 12:08:20 -07001079 mDrawingState.sequence++;
1080 mDrawingState.modified = true;
1081 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -07001082
Robert Carr6a160312021-05-17 12:08:20 -07001083 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -07001084 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001085 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -07001086 }
chaviw606e5cf2019-03-01 10:12:10 -08001087 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001088 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -07001089
1090 setTransactionFlags(eTransactionNeeded);
1091
1092 return true;
1093}
1094
Winson Chunga30f7c92021-06-29 15:42:56 -07001095bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
1096 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
1097 mDrawingState.isTrustedOverlay = isTrustedOverlay;
1098 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00001099 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -07001100 setTransactionFlags(eTransactionNeeded);
1101 return true;
1102}
1103
1104bool Layer::isTrustedOverlay() const {
1105 if (getDrawingState().isTrustedOverlay) {
1106 return true;
1107 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001108 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -07001109 return (p != nullptr) && p->isTrustedOverlay();
1110}
1111
Dan Stoza9e56aa02015-11-02 13:00:03 -08001112bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -07001113 if (mDrawingState.color.a == alpha) return false;
1114 mDrawingState.sequence++;
1115 mDrawingState.color.a = alpha;
1116 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001117 setTransactionFlags(eTransactionNeeded);
1118 return true;
1119}
chaviw13fdc492017-06-27 12:40:18 -07001120
Valerie Haudd0b7572019-01-29 14:59:27 -08001121bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -07001122 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -07001123 return false;
Valerie Hauaa194562019-02-05 16:21:38 -08001124 }
Robert Carr6a160312021-05-17 12:08:20 -07001125 mDrawingState.sequence++;
1126 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -08001127 setTransactionFlags(eTransactionNeeded);
1128
Robert Carr6a160312021-05-17 12:08:20 -07001129 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001130 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001131 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001132 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001133 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08001134 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001135 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001136
Valerie Haudd0b7572019-01-29 14:59:27 -08001137 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001138 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001139 mFlinger->mLayersAdded = true;
1140 // set up SF to handle added color layer
1141 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -07001142 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001143 }
1144 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001145 } else if (mDrawingState.bgColorLayer && alpha == 0) {
1146 mDrawingState.bgColorLayer->reparent(nullptr);
1147 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001148 return true;
1149 }
1150
Robert Carr6a160312021-05-17 12:08:20 -07001151 mDrawingState.bgColorLayer->setColor(color);
1152 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1153 mDrawingState.bgColorLayer->setAlpha(alpha);
1154 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001155
chaviw13fdc492017-06-27 12:40:18 -07001156 return true;
1157}
1158
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001159bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001160 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001161
Robert Carr6a160312021-05-17 12:08:20 -07001162 mDrawingState.sequence++;
1163 mDrawingState.cornerRadius = cornerRadius;
1164 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001165 setTransactionFlags(eTransactionNeeded);
1166 return true;
1167}
1168
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001169bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001170 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001171 // If we start or stop drawing blur then the layer's visibility state may change so increment
1172 // the magic sequence number.
1173 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1174 mDrawingState.sequence++;
1175 }
Robert Carr6a160312021-05-17 12:08:20 -07001176 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1177 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001178 setTransactionFlags(eTransactionNeeded);
1179 return true;
1180}
Marissa Wall61c58622018-07-18 10:12:20 -07001181
Mathias Agopian13127d82013-03-05 17:47:11 -08001182bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001183 mDrawingState.sequence++;
1184 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001185 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001186 setTransactionFlags(eTransactionNeeded);
1187 return true;
1188}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001189
Lucas Dupinc3800b82020-10-02 16:24:48 -07001190bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001191 // If we start or stop drawing blur then the layer's visibility state may change so increment
1192 // the magic sequence number.
1193 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1194 mDrawingState.sequence++;
1195 }
Robert Carr6a160312021-05-17 12:08:20 -07001196 mDrawingState.blurRegions = blurRegions;
1197 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001198 setTransactionFlags(eTransactionNeeded);
1199 return true;
1200}
1201
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001202bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001203 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1204 if (mDrawingState.flags == newFlags) return false;
1205 mDrawingState.sequence++;
1206 mDrawingState.flags = newFlags;
1207 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001208 setTransactionFlags(eTransactionNeeded);
1209 return true;
1210}
Robert Carr99e27f02016-06-16 15:18:02 -07001211
chaviw25714502021-02-11 10:01:08 -08001212bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001213 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001214 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001215 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001216
Robert Carr6a160312021-05-17 12:08:20 -07001217 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001218 setTransactionFlags(eTransactionNeeded);
1219 return true;
1220}
Robert Carr8d5227b2017-03-16 15:41:03 -07001221
Evan Roskyef876c92019-01-25 17:46:06 -08001222bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001223 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1224 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001225 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001226 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001227}
1228
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001229bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001230 if (mDrawingState.layerStack == layerStack) return false;
1231 mDrawingState.sequence++;
1232 mDrawingState.layerStack = layerStack;
1233 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001234 setTransactionFlags(eTransactionNeeded);
1235 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001236}
1237
Peiyong Linc502cb72019-03-01 15:00:23 -08001238bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001239 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001240 return false;
1241 }
Robert Carr6a160312021-05-17 12:08:20 -07001242 mDrawingState.sequence++;
1243 mDrawingState.colorSpaceAgnostic = agnostic;
1244 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001245 setTransactionFlags(eTransactionNeeded);
1246 return true;
1247}
1248
Sally Qi81d95e62022-03-21 19:41:33 -07001249bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1250 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1251
1252 mDrawingState.sequence++;
1253 mDrawingState.dimmingEnabled = dimmingEnabled;
1254 mDrawingState.modified = true;
1255 setTransactionFlags(eTransactionNeeded);
1256 return true;
1257}
1258
Ana Krulecc84d09b2019-11-02 23:10:29 +01001259bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001260 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1261 mDrawingState.frameRateSelectionPriority = priority;
1262 mDrawingState.sequence++;
1263 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001264 setTransactionFlags(eTransactionNeeded);
1265 return true;
1266}
1267
1268int32_t Layer::getFrameRateSelectionPriority() const {
1269 // Check if layer has priority set.
1270 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1271 return mDrawingState.frameRateSelectionPriority;
1272 }
1273 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001274 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001275 if (parent != nullptr) {
1276 return parent->getFrameRateSelectionPriority();
1277 }
1278
1279 return Layer::PRIORITY_UNSET;
1280}
1281
Andy Labrada096227e2022-06-15 16:58:11 +00001282bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1283 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1284 mDrawingState.defaultFrameRateCompatibility = compatibility;
1285 mDrawingState.modified = true;
1286 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1287 setTransactionFlags(eTransactionNeeded);
1288 return true;
1289}
1290
1291scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1292 return mDrawingState.defaultFrameRateCompatibility;
1293}
1294
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001295bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1296 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1297};
1298
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001299ui::LayerStack Layer::getLayerStack() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001300 if (const auto parent = mDrawingParent.promote()) {
1301 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001302 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001303 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001304}
1305
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001306bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001307 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001308 return false;
1309 }
1310
Robert Carr6a160312021-05-17 12:08:20 -07001311 mDrawingState.sequence++;
1312 mDrawingState.shadowRadius = shadowRadius;
1313 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001314 setTransactionFlags(eTransactionNeeded);
1315 return true;
1316}
1317
Vishnu Nair6213bd92020-05-08 17:42:25 -07001318bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001319 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001320 return false;
1321 }
1322
Robert Carr6a160312021-05-17 12:08:20 -07001323 mDrawingState.sequence++;
1324 mDrawingState.fixedTransformHint = fixedTransformHint;
1325 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001326 setTransactionFlags(eTransactionNeeded);
1327 return true;
1328}
1329
John Reckcdb4ed72021-02-04 13:39:33 -05001330bool Layer::setStretchEffect(const StretchEffect& effect) {
1331 StretchEffect temp = effect;
1332 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001333 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001334 return false;
1335 }
Robert Carr6a160312021-05-17 12:08:20 -07001336 mDrawingState.sequence++;
1337 mDrawingState.stretchEffect = temp;
1338 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001339 setTransactionFlags(eTransactionNeeded);
1340 return true;
1341}
1342
John Reckc00c6692021-02-16 11:37:33 -05001343StretchEffect Layer::getStretchEffect() const {
1344 if (mDrawingState.stretchEffect.hasEffect()) {
1345 return mDrawingState.stretchEffect;
1346 }
1347
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001348 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001349 if (parent != nullptr) {
1350 auto effect = parent->getStretchEffect();
1351 if (effect.hasEffect()) {
1352 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1353 return effect;
1354 }
1355 }
1356 return StretchEffect{};
1357}
1358
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001359bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1360 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001361 return false;
1362 }
1363 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001364 mBorderWidth = width;
1365 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001366 return true;
1367}
1368
1369bool Layer::isBorderEnabled() {
1370 return mBorderEnabled;
1371}
1372
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001373float Layer::getBorderWidth() {
1374 return mBorderWidth;
1375}
1376
1377const half4& Layer::getBorderColor() {
1378 return mBorderColor;
1379}
1380
Ady Abrahama850c182021-08-04 13:04:37 -07001381bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1382 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1383 const auto frameRate = [&] {
1384 if (mDrawingState.frameRate.rate.isValid() ||
1385 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1386 return mDrawingState.frameRate;
1387 }
1388
1389 return parentFrameRate;
1390 }();
1391
1392 *transactionNeeded |= setFrameRateForLayerTree(frameRate);
1393
1394 // The frame rate is propagated to the children
1395 bool childrenHaveFrameRate = false;
1396 for (const sp<Layer>& child : mCurrentChildren) {
1397 childrenHaveFrameRate |=
1398 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1399 }
1400
1401 // If we don't have a valid frame rate, but the children do, we set this
1402 // layer as NoVote to allow the children to control the refresh rate
1403 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1404 childrenHaveFrameRate) {
1405 *transactionNeeded |=
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001406 setFrameRateForLayerTree(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001407 }
1408
1409 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1410 // the same reason we are allowing touch boost for those layers. See
1411 // RefreshRateConfigs::getBestRefreshRate for more details.
1412 const auto layerVotedWithDefaultCompatibility =
1413 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1414 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1415 const auto layerVotedWithExactCompatibility =
1416 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1417 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1418 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1419}
1420
Ady Abraham60e42ea2020-03-09 19:17:31 -07001421void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001422 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001423 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001424 while (auto parent = layer->getParent()) {
1425 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001426 }
Ady Abrahama850c182021-08-04 13:04:37 -07001427 return layer;
1428 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001429
Ady Abraham60e42ea2020-03-09 19:17:31 -07001430 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001431 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001432
Ady Abrahama850c182021-08-04 13:04:37 -07001433 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001434 if (transactionNeeded) {
1435 mFlinger->setTransactionFlags(eTraversalNeeded);
1436 }
1437}
1438
Ady Abraham71c437d2020-01-31 15:56:57 -08001439bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001440 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001441 return false;
1442 }
1443
Robert Carr6a160312021-05-17 12:08:20 -07001444 mDrawingState.sequence++;
1445 mDrawingState.frameRate = frameRate;
1446 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001447
1448 updateTreeHasFrameRateVote();
1449
Steven Thomas3172e202020-01-06 19:25:30 -08001450 setTransactionFlags(eTransactionNeeded);
1451 return true;
1452}
1453
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001454void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1455 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001456 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001457
1458 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1459 // there are two transactions with the same token, the first one without a buffer and the
1460 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1461 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001462 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1463 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001464 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001465 mDrawingState.bufferSurfaceFrameTX = it->second;
1466 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1467 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1468 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001469 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001470 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001471 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1472 }
1473}
1474
1475void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1476 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001477 mDrawingState.frameTimelineInfo = info;
1478 mDrawingState.postTime = postTime;
1479 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001480 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001481
Robert Carr6a160312021-05-17 12:08:20 -07001482 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001483 bufferSurfaceFrameTX != nullptr) {
1484 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1485 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1486 // being used for BufferSurfaceFrame, don't create a new one.
1487 return;
1488 }
1489 }
1490 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1491 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1492 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001493 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1494 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001495 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001496 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001497 } else {
1498 if (it->second->getPresentState() == PresentState::Presented) {
1499 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1500 // have been from previous vsync.
1501 it->second = createSurfaceFrameForTransaction(info, postTime);
1502 }
1503 }
1504}
1505
1506void Layer::addSurfaceFrameDroppedForBuffer(
1507 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001508 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001509 surfaceFrame->setPresentState(PresentState::Dropped);
1510 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1511}
1512
1513void Layer::addSurfaceFramePresentedForBuffer(
1514 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1515 nsecs_t currentLatchTime) {
1516 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1517 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1518 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1519 mLastLatchTime = currentLatchTime;
1520}
1521
1522std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1523 const FrameTimelineInfo& info, nsecs_t postTime) {
1524 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001525 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1526 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001527 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001528 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001529 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001530 // For Transactions, the post time is considered to be both queue and acquire fence time.
1531 surfaceFrame->setActualQueueTime(postTime);
1532 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001533 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1534 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001535 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001536 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001537 onSurfaceFrameCreated(surfaceFrame);
1538 return surfaceFrame;
1539}
1540
1541std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1542 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1543 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001544 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001545 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001546 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001547 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001548 // For buffers, acquire fence time will set during latch.
1549 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001550 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1551 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001552 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001553 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001554 // TODO(b/178542907): Implement onSurfaceFrameCreated for BQLayer as well.
1555 onSurfaceFrameCreated(surfaceFrame);
1556 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001557}
1558
Ady Abrahama850c182021-08-04 13:04:37 -07001559bool Layer::setFrameRateForLayerTree(FrameRate frameRate) {
1560 if (mDrawingState.frameRateForLayerTree == frameRate) {
1561 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001562 }
1563
Ady Abrahama850c182021-08-04 13:04:37 -07001564 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001565
Ady Abrahama850c182021-08-04 13:04:37 -07001566 // TODO(b/195668952): we probably don't need to dirty visible regions here
1567 // or even store frameRateForLayerTree in mDrawingState
1568 mDrawingState.sequence++;
1569 mDrawingState.modified = true;
1570 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001571
Dominik Laskowski068173d2021-08-11 17:22:59 -07001572 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
1573 mFlinger->mScheduler->recordLayerHistory(this, systemTime(), LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001574
1575 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001576}
1577
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001578Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1579 return getDrawingState().frameRateForLayerTree;
1580}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001581
Robert Carr1f0a16a2016-10-24 16:27:39 -07001582bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001583 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001584 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001585 if (parent != nullptr && parent->isHiddenByPolicy()) {
1586 return true;
1587 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001588 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1589 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1590 if (zOrderRelativeOf != nullptr) {
1591 if (zOrderRelativeOf->isHiddenByPolicy()) {
1592 return true;
1593 }
1594 }
1595 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001596 if (CC_UNLIKELY(!isTransformValid())) {
1597 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1598 return true;
1599 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001600 return s.flags & layer_state_t::eLayerHidden;
1601}
1602
David Sodman41fdfc92017-11-06 16:09:56 -08001603uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001604 // TODO: should we do something special if mSecure is set?
1605 if (mProtectedByApp) {
1606 // need a hardware-protected path to external video sink
1607 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001608 }
Riley Andrews03414a12014-07-01 14:22:59 -07001609 if (mPotentialCursor) {
1610 usage |= GraphicBuffer::USAGE_CURSOR;
1611 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001612 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001613 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001614}
1615
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001616void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1617 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1618 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001619 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001620
Vishnu Nair6213bd92020-05-08 17:42:25 -07001621 setTransformHint(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001622}
1623
Mathias Agopian13127d82013-03-05 17:47:11 -08001624// ----------------------------------------------------------------------------
1625// debugging
1626// ----------------------------------------------------------------------------
1627
Marissa Wall61c58622018-07-18 10:12:20 -07001628// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001629gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001630 using namespace std::string_literals;
1631
Huihong Luo05539a12022-02-23 10:29:40 -08001632 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001633 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001634 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001635 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001636 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001637 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001638
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001639 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001640 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001641 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001642 info.mX = ds.transform.tx();
1643 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001644 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001645 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001646 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001647 info.mFlags = ds.flags;
1648 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001649 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001650 info.mMatrix[0][0] = ds.transform[0][0];
1651 info.mMatrix[0][1] = ds.transform[0][1];
1652 info.mMatrix[1][0] = ds.transform[1][0];
1653 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001654 {
chaviwd62d3062019-09-04 14:48:02 -07001655 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001656 if (buffer != 0) {
1657 info.mActiveBufferWidth = buffer->getWidth();
1658 info.mActiveBufferHeight = buffer->getHeight();
1659 info.mActiveBufferStride = buffer->getStride();
1660 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001661 } else {
1662 info.mActiveBufferWidth = 0;
1663 info.mActiveBufferHeight = 0;
1664 info.mActiveBufferStride = 0;
1665 info.mActiveBufferFormat = 0;
1666 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001667 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001668 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001669 info.mIsOpaque = isOpaque(ds);
1670 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001671 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001672 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001673}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001674
Yiwei Zhang5434a782018-12-05 18:06:32 -08001675void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001676 result.append(kDumpTableRowLength, '-');
1677 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001678 result.append(" Layer name\n");
1679 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001680 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001681 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001682 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001683 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001684 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001685 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1686 result.append(kDumpTableRowLength, '-');
1687 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001688}
1689
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001690void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1691 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001692 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001693 return;
1694 }
1695
Yiwei Zhang5434a782018-12-05 18:06:32 -08001696 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001697 if (mName.length() > 77) {
1698 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001699 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001700 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001701 shortened.append(mName, mName.length() - 36);
1702 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001703 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001704 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001705 }
1706
Yiwei Zhang5434a782018-12-05 18:06:32 -08001707 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001708
Alec Mourib416efd2018-09-06 21:01:59 +00001709 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001710 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001711
Chia-I Wu1e043612018-03-01 09:45:09 -08001712 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001713 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001714 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001715 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001716 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001717 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001718 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001719 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1720 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001721 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001722 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001723 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001724 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001725 const auto frameRate = getFrameRateForLayerTree();
1726 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1727 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001728 ftl::enum_string(frameRate.type).c_str(),
1729 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001730 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001731 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001732 }
Dan Stozae22aec72016-08-01 13:20:59 -07001733
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001734 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1735 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1736
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001737 result.append(kDumpTableRowLength, '-');
1738 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001739}
Dan Stozae22aec72016-08-01 13:20:59 -07001740
Yiwei Zhang5434a782018-12-05 18:06:32 -08001741void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001742 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001743}
1744
Svetoslavd85084b2014-03-20 10:28:31 -07001745void Layer::clearFrameStats() {
1746 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001747}
1748
Jamie Gennis6547ff42013-07-16 20:12:42 -07001749void Layer::logFrameStats() {
1750 mFrameTracker.logAndResetStats(mName);
1751}
1752
Svetoslavd85084b2014-03-20 10:28:31 -07001753void Layer::getFrameStats(FrameStats* outStats) const {
1754 mFrameTracker.getStats(outStats);
1755}
1756
Vishnu Nair0f085c62019-08-30 08:49:12 -07001757void Layer::dumpCallingUidPid(std::string& result) const {
chaviw250bcbb2020-08-05 11:17:54 -07001758 StringAppendF(&result, "Layer %s (%s) callingPid:%d callingUid:%d ownerUid:%d\n",
1759 getName().c_str(), getType(), mCallingPid, mCallingUid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001760}
1761
Brian Anderson5ea5e592016-12-01 16:54:33 -08001762void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001763 const int32_t layerId = getSequence();
1764 mFlinger->mTimeStats->onDestroy(layerId);
1765 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001766}
1767
Chia-I Wu98f1c102017-05-30 14:54:08 -07001768size_t Layer::getChildrenCount() const {
1769 size_t count = 0;
1770 for (const sp<Layer>& child : mCurrentChildren) {
1771 count += 1 + child->getChildrenCount();
1772 }
1773 return count;
1774}
1775
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001776void Layer::setGameModeForTree(GameMode gameMode) {
1777 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001778 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1779 gameMode =
1780 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001781 }
1782 setGameMode(gameMode);
1783 for (const sp<Layer>& child : mCurrentChildren) {
1784 child->setGameModeForTree(gameMode);
1785 }
1786}
1787
Robert Carr1f0a16a2016-10-24 16:27:39 -07001788void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001789 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001790 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001791
Robert Carr1f0a16a2016-10-24 16:27:39 -07001792 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001793 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001794 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001795 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001796}
1797
1798ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001799 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001800 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001801
Robert Carr1323c952019-01-28 18:13:27 -08001802 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001803 const auto removeResult = mCurrentChildren.remove(layer);
1804
1805 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001806 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001807 layer->updateTreeHasFrameRateVote();
1808
1809 return removeResult;
1810}
1811
Robert Carr15eae092018-03-23 13:43:53 -07001812void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001813 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001814 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001815 const float parentShadowRadius =
1816 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001817 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001818 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001819 }
1820}
1821
chaviwf1961f72017-09-18 16:41:07 -07001822bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001823 sp<Layer> newParent;
1824 if (newParentHandle != nullptr) {
Vishnu Nairf9096652021-07-20 18:49:42 -07001825 newParent = fromHandle(newParentHandle).promote();
Robert Carr54cf5b12019-01-25 14:02:28 -08001826 if (newParent == nullptr) {
1827 ALOGE("Unable to promote Layer handle");
1828 return false;
1829 }
1830 if (newParent == this) {
1831 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1832 return false;
1833 }
1834 }
1835
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001836 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001837 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001838 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001839 }
1840
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001841 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001842 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001843 if (!newParent->isRemovedFromCurrentState()) {
1844 addToCurrentState();
1845 } else {
1846 onRemovedFromCurrentState();
1847 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001848 } else {
1849 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001850 }
1851
chaviw06178942017-07-27 10:25:59 -07001852 return true;
1853}
1854
Peiyong Lind3788632018-09-18 16:01:31 -07001855bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001856 static const mat4 identityMatrix = mat4();
1857
Robert Carr6a160312021-05-17 12:08:20 -07001858 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001859 return false;
1860 }
Robert Carr6a160312021-05-17 12:08:20 -07001861 ++mDrawingState.sequence;
1862 mDrawingState.colorTransform = matrix;
1863 mDrawingState.hasColorTransform = matrix != identityMatrix;
1864 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001865 setTransactionFlags(eTransactionNeeded);
1866 return true;
1867}
1868
chaviwf66724d2018-11-28 16:35:21 -08001869mat4 Layer::getColorTransform() const {
1870 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001871 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001872 colorTransform = parent->getColorTransform() * colorTransform;
1873 }
1874 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001875}
1876
1877bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001878 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001879 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001880 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1881 }
1882 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001883}
1884
Chia-I Wu11481472018-05-04 10:43:19 -07001885bool Layer::isLegacyDataSpace() const {
1886 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001887 return !(getDataSpace() &
1888 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1889 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001890}
1891
Robert Carr1f0a16a2016-10-24 16:27:39 -07001892void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001893 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001894}
1895
Robert Carr6a160312021-05-17 12:08:20 -07001896int32_t Layer::getZ(LayerVector::StateSet) const {
1897 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001898}
1899
Robert Carr1c5481e2019-07-01 14:42:27 -07001900bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001901 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001902 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001903 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001904}
1905
David Sodman41fdfc92017-11-06 16:09:56 -08001906__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001907 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001908 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1909 "makeTraversalList received invalid stateSet");
1910 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1911 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001912 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001913
Robert Carr29abff82017-12-04 13:51:20 -08001914 if (state.zOrderRelatives.size() == 0) {
1915 *outSkipRelativeZUsers = true;
1916 return children;
1917 }
1918
chaviwfd462612018-05-31 16:11:27 -07001919 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001920 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001921 sp<Layer> strongRelative = weakRelative.promote();
1922 if (strongRelative != nullptr) {
1923 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001924 }
1925 }
1926
Dan Stoza412903f2017-04-27 13:42:17 -07001927 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001928 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001929 continue;
1930 }
Robert Carrdb66e622017-04-10 16:55:57 -07001931 traverse.add(child);
1932 }
1933
1934 return traverse;
1935}
1936
Robert Carr1f0a16a2016-10-24 16:27:39 -07001937/**
Robert Carrdb66e622017-04-10 16:55:57 -07001938 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001939 */
Dan Stoza412903f2017-04-27 13:42:17 -07001940void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001941 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1942 // produce a new list for traversing, including our relatives, and not including our children
1943 // who are relatives of another surface. In the case that there are no relative Z,
1944 // makeTraversalList returns our children directly to avoid significant overhead.
1945 // However in this case we need to take the responsibility for filtering children which
1946 // are relatives of another surface here.
1947 bool skipRelativeZUsers = false;
1948 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001949
Robert Carr1f0a16a2016-10-24 16:27:39 -07001950 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001951 for (; i < list.size(); i++) {
1952 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001953 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1954 continue;
1955 }
1956
chaviw301b1d82019-11-06 13:15:09 -08001957 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001958 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001959 }
Dan Stoza412903f2017-04-27 13:42:17 -07001960 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001961 }
Robert Carr29abff82017-12-04 13:51:20 -08001962
Dan Stoza412903f2017-04-27 13:42:17 -07001963 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001964 for (; i < list.size(); i++) {
1965 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001966
Robert Carr29abff82017-12-04 13:51:20 -08001967 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1968 continue;
1969 }
Dan Stoza412903f2017-04-27 13:42:17 -07001970 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001971 }
1972}
1973
1974/**
Robert Carrdb66e622017-04-10 16:55:57 -07001975 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001976 */
Dan Stoza412903f2017-04-27 13:42:17 -07001977void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1978 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001979 // See traverseInZOrder for documentation.
1980 bool skipRelativeZUsers = false;
1981 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001982
Robert Carr1f0a16a2016-10-24 16:27:39 -07001983 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001984 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001985 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001986
1987 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1988 continue;
1989 }
1990
chaviw301b1d82019-11-06 13:15:09 -08001991 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001992 break;
1993 }
Dan Stoza412903f2017-04-27 13:42:17 -07001994 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001995 }
Dan Stoza412903f2017-04-27 13:42:17 -07001996 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001997 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001998 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001999
2000 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
2001 continue;
2002 }
2003
Dan Stoza412903f2017-04-27 13:42:17 -07002004 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002005 }
2006}
2007
Edgar Arriaga844fa672020-01-16 14:21:42 -08002008void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
2009 visitor(this);
2010 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07002011 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002012 for (const sp<Layer>& child : children) {
2013 child->traverse(state, visitor);
2014 }
2015}
2016
chaviw4b129c22018-04-09 16:19:43 -07002017LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
2018 const std::vector<Layer*>& layersInTree) {
2019 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2020 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07002021 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2022 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002023 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002024
chaviwfd462612018-05-31 16:11:27 -07002025 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07002026 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2027 sp<Layer> strongRelative = weakRelative.promote();
2028 // Only add relative layers that are also descendents of the top most parent of the tree.
2029 // If a relative layer is not a descendent, then it should be ignored.
2030 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
2031 traverse.add(strongRelative);
2032 }
2033 }
2034
2035 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07002036 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002037 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
2038 // descendent of the top most parent of the tree. If it's not a descendent, then just add
2039 // the child here since it won't be added later as a relative.
2040 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
2041 childState.zOrderRelativeOf.promote().get())) {
2042 continue;
2043 }
2044 traverse.add(child);
2045 }
2046
2047 return traverse;
2048}
2049
2050void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
2051 LayerVector::StateSet stateSet,
2052 const LayerVector::Visitor& visitor) {
2053 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07002054
2055 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07002056 for (; i < list.size(); i++) {
2057 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08002058 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07002059 break;
2060 }
chaviw4b129c22018-04-09 16:19:43 -07002061 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002062 }
chaviw4b129c22018-04-09 16:19:43 -07002063
chaviwa76b2712017-09-20 12:02:26 -07002064 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07002065 for (; i < list.size(); i++) {
2066 const auto& relative = list[i];
2067 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002068 }
2069}
2070
chaviw4b129c22018-04-09 16:19:43 -07002071std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2072 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2073 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2074
2075 std::vector<Layer*> layersInTree = {this};
2076 for (size_t i = 0; i < children.size(); i++) {
2077 const auto& child = children[i];
2078 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2079 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2080 }
2081
2082 return layersInTree;
2083}
2084
2085void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2086 const LayerVector::Visitor& visitor) {
2087 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2088 std::sort(layersInTree.begin(), layersInTree.end());
2089 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2090}
2091
Peiyong Linefefaac2018-08-17 12:27:51 -07002092ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08002093 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002094}
2095
Garfield Tan2c1782c2022-02-16 15:25:05 -08002096bool Layer::isTransformValid() const {
2097 float transformDet = getTransform().det();
2098 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2099}
2100
chaviw13fdc492017-06-27 12:40:18 -07002101half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002102 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002103
chaviw13fdc492017-06-27 12:40:18 -07002104 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2105 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002106}
Robert Carr6452f122017-03-21 10:41:29 -07002107
Vishnu Nair6213bd92020-05-08 17:42:25 -07002108ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002109 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002110 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2111 return fixedTransformHint;
2112 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002113 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002114 if (!p) return fixedTransformHint;
2115 return p->getFixedTransformHint();
2116}
2117
chaviw13fdc492017-06-27 12:40:18 -07002118half4 Layer::getColor() const {
2119 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002120 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002121}
Robert Carr6452f122017-03-21 10:41:29 -07002122
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002123int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002124 if (getDrawingState().backgroundBlurRadius == 0) {
2125 return 0;
2126 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002127
Vishnu Nair29810f72022-07-01 16:38:41 +00002128 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002129 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2130 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002131}
2132
Galia Peychevae0acf382021-04-12 21:22:34 +02002133const std::vector<BlurRegion> Layer::getBlurRegions() const {
2134 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002135 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002136 for (auto& region : regionsCopy) {
2137 region.alpha = region.alpha * layerAlpha;
2138 }
2139 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002140}
2141
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002142Layer::RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002143 // Get parent settings
2144 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002145 const auto& parent = mDrawingParent.promote();
2146 if (parent != nullptr) {
2147 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002148 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002149 ui::Transform t = getActiveTransform(getDrawingState());
2150 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002151 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002152 parentSettings.radius.x *= t.getScaleX();
2153 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002154 }
2155 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002156
2157 // Get layer settings
2158 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002159 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002160 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002161 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002162
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002163 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002164 // If the parent and the layer have rounded corner settings, use the parent settings if the
2165 // parent crop is entirely inside the layer crop.
2166 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2167 if (parentSettings.cropRect.left > layerCropRect.left &&
2168 parentSettings.cropRect.top > layerCropRect.top &&
2169 parentSettings.cropRect.right < layerCropRect.right &&
2170 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2171 return parentSettings;
2172 } else {
2173 return layerSettings;
2174 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002175 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002176 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002177 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002178 return parentSettings;
2179 }
2180 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002181}
2182
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04002183void Layer::prepareShadowClientComposition(LayerFE::LayerSettings& caster,
Patrick Williams16d8b2c2022-08-08 17:29:05 +00002184 const Rect& layerStackRect) const {
Vishnu Nair08f6eae2019-11-26 14:01:39 -08002185 renderengine::ShadowSettings state = mFlinger->mDrawingState.globalShadowSettings;
2186
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04002187 // Note: this preserves existing behavior of shadowing the entire layer and not cropping it if
Patrick Williams46b61b92022-09-01 17:25:49 +00002188 // transparent regions are present. This may not be necessary since shadows are typically cast
2189 // by layers without transparent regions.
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04002190 state.boundaries = mBounds;
2191
Vishnu Nair08f6eae2019-11-26 14:01:39 -08002192 // Shift the spot light x-position to the middle of the display and then
2193 // offset it by casting layer's screen pos.
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002194 state.lightPos.x = (layerStackRect.width() / 2.f) - mScreenBounds.left;
Vishnu Nair08f6eae2019-11-26 14:01:39 -08002195 state.lightPos.y -= mScreenBounds.top;
2196
2197 state.length = mEffectiveShadowRadius;
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04002198
2199 if (state.length > 0.f) {
2200 const float casterAlpha = caster.alpha;
2201 const bool casterIsOpaque =
2202 ((caster.source.buffer.buffer != nullptr) && caster.source.buffer.isOpaque);
2203
2204 // If the casting layer is translucent, we need to fill in the shadow underneath the layer.
2205 // Otherwise the generated shadow will only be shown around the casting layer.
2206 state.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
2207 state.ambientColor *= casterAlpha;
2208 state.spotColor *= casterAlpha;
2209
2210 if (state.ambientColor.a > 0.f && state.spotColor.a > 0.f) {
2211 caster.shadow = state;
2212 }
2213 }
Vishnu Nair08f6eae2019-11-26 14:01:39 -08002214}
2215
Robert Carr88b85e12022-03-21 15:47:35 -07002216bool Layer::findInHierarchy(const sp<Layer>& l) {
2217 if (l == this) {
2218 return true;
2219 }
2220 for (auto& child : mDrawingChildren) {
2221 if (child->findInHierarchy(l)) {
2222 return true;
2223 }
2224 }
2225 return false;
2226}
2227
Robert Carr1f0a16a2016-10-24 16:27:39 -07002228void Layer::commitChildList() {
2229 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2230 const auto& child = mCurrentChildren[i];
2231 child->commitChildList();
2232 }
2233 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002234 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002235 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2236 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2237 if (zOrderRelativeOf == nullptr) return;
2238 if (findInHierarchy(zOrderRelativeOf)) {
2239 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2240 zOrderRelativeOf->mName.c_str());
2241 ALOGE("Severing rel Z loop, potentially dangerous");
2242 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002243 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002244 }
2245 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002246}
2247
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002248
chaviw3277faf2021-05-19 16:45:23 -05002249void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002250 mDrawingState.inputInfo = info;
Vishnu Nairf9096652021-07-20 18:49:42 -07002251 mDrawingState.touchableRegionCrop = fromHandle(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002252 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002253 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002254 setTransactionFlags(eTransactionNeeded);
2255}
2256
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002257LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002258 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002259 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002260 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2261
Vishnu Nair00b90132021-11-05 14:03:40 -07002262 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002263 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2264
Vishnu Nair60db8c02020-04-02 11:55:16 -07002265 // Only populate for the primary display.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002266 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -05002267 const auto compositionType = getCompositionType(*display);
Vishnu Nair60db8c02020-04-02 11:55:16 -07002268 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002269 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2270 [&]() { return layerProto->mutable_visible_region(); });
Vishnu Nair60db8c02020-04-02 11:55:16 -07002271 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08002272 }
2273
chaviw08f3cb22020-01-13 13:17:21 -08002274 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002275 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002276 }
chaviw6d89e2d2020-01-14 14:42:01 -08002277
2278 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002279}
2280
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002281void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002282 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002283 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002284 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002285 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002286 [&]() { return layerInfo->mutable_active_buffer(); });
2287 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2288 layerInfo->mutable_buffer_transform());
2289 }
2290 layerInfo->set_invalidate(contentDirty);
2291 layerInfo->set_is_protected(isProtected());
2292 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2293 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002294 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002295 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002296 layerInfo->set_corner_radius(
2297 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002298 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2299 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2300 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2301 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2302 [&]() { return layerInfo->mutable_position(); });
2303 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002304 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2305 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002306
Vishnu Nair00b90132021-11-05 14:03:40 -07002307 if (hasColorTransform()) {
2308 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002309 }
2310
Vishnu Nair60db8c02020-04-02 11:55:16 -07002311 LayerProtoHelper::writeToProto(mSourceBounds,
2312 [&]() { return layerInfo->mutable_source_bounds(); });
2313 LayerProtoHelper::writeToProto(mScreenBounds,
2314 [&]() { return layerInfo->mutable_screen_bounds(); });
2315 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2316 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2317 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002318}
2319
2320void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002321 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002322 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2323 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002324 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002325
chaviw766c9c52021-02-10 17:36:47 -08002326 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002327
Vishnu Nair00b90132021-11-05 14:03:40 -07002328 layerInfo->set_id(sequence);
2329 layerInfo->set_name(getName().c_str());
2330 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002331
Vishnu Nair00b90132021-11-05 14:03:40 -07002332 for (const auto& child : children) {
2333 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002334 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002335
Vishnu Nair00b90132021-11-05 14:03:40 -07002336 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2337 sp<Layer> strongRelative = weakRelative.promote();
2338 if (strongRelative != nullptr) {
2339 layerInfo->add_relatives(strongRelative->sequence);
2340 }
2341 }
2342
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002343 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002344 [&]() { return layerInfo->mutable_transparent_region(); });
2345
2346 layerInfo->set_layer_stack(getLayerStack().id);
2347 layerInfo->set_z(state.z);
2348
2349 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2350 return layerInfo->mutable_requested_position();
2351 });
2352
Vishnu Nair00b90132021-11-05 14:03:40 -07002353 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2354
2355 layerInfo->set_is_opaque(isOpaque(state));
2356
2357 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2358 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2359 LayerProtoHelper::writeToProto(state.color,
2360 [&]() { return layerInfo->mutable_requested_color(); });
2361 layerInfo->set_flags(state.flags);
2362
2363 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2364 layerInfo->mutable_requested_transform());
2365
2366 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2367 if (parent != nullptr) {
2368 layerInfo->set_parent(parent->sequence);
2369 } else {
2370 layerInfo->set_parent(-1);
2371 }
2372
2373 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2374 if (zOrderRelativeOf != nullptr) {
2375 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2376 } else {
2377 layerInfo->set_z_order_relative_of(-1);
2378 }
2379
2380 layerInfo->set_is_relative_of(state.isRelativeOf);
2381
2382 layerInfo->set_owner_uid(mOwnerUid);
2383
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002384 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002385 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002386 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002387 info = fillInputInfo(
2388 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002389 } else {
2390 info = state.inputInfo;
2391 }
2392
2393 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002394 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002395 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002396
Vishnu Nair00b90132021-11-05 14:03:40 -07002397 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002398 auto protoMap = layerInfo->mutable_metadata();
2399 for (const auto& entry : state.metadata.mMap) {
2400 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2401 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002402 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002403
2404 LayerProtoHelper::writeToProto(state.destinationFrame,
2405 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002406}
2407
Robert Carr2e102c92018-10-23 12:11:15 -07002408bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002409 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002410}
2411
Prabir Pradhan33da9462022-06-14 14:55:57 +00002412// Applies the given transform to the region, while protecting against overflows caused by any
2413// offsets. If applying the offset in the transform to any of the Rects in the region would result
2414// in an overflow, they are not added to the output Region.
2415static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2416 const std::string& debugWindowName) {
2417 // Round the translation using the same rounding strategy used by ui::Transform.
2418 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2419 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2420
2421 ui::Transform transformWithoutOffset = t;
2422 transformWithoutOffset.set(0.f, 0.f);
2423
2424 const Region transformed = transformWithoutOffset.transform(r);
2425
2426 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2427 Region ret;
2428 for (const auto& rect : transformed) {
2429 Rect newRect;
2430 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2431 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2432 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2433 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2434 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2435 debugWindowName.c_str());
2436 continue;
2437 }
2438 ret.orSelf(newRect);
2439 }
2440 return ret;
2441}
2442
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002443void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
2444 Rect tmpBounds = getInputBounds();
2445 if (!tmpBounds.isValid()) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002446 info.touchableRegion.clear();
2447 // A layer could have invalid input bounds and still expect to receive touch input if it has
2448 // replaceTouchableRegionWithCrop. For that case, the input transform needs to be calculated
2449 // correctly to determine the coordinate space for input events. Use an empty rect so that
2450 // the layer will receive input in its own layer space.
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002451 tmpBounds = Rect::EMPTY_RECT;
chaviw7e72caf2020-12-02 16:50:43 -08002452 }
2453
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002454 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2455 // frame and transform used for the layer, which determines the bounds and the coordinate space
2456 // within which the layer will receive input.
2457 //
2458 // The coordinate space within which each of the bounds are specified is explicitly documented
2459 // in the variable name. For example "inputBoundsInLayer" is specified in layer space. A
2460 // Transform converts one coordinate space to another, which is apparent in its naming. For
2461 // example, "layerToDisplay" transforms layer space to display space.
2462 //
2463 // Coordinate space definitions:
2464 // - display: The display device's coordinate space. Correlates to pixels on the display.
2465 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2466 // - layer: The coordinate space of this layer.
2467 // - input: The coordinate space in which this layer will receive input events. This could be
2468 // different than layer space if a surfaceInset is used, which changes the origin
2469 // of the input space.
2470 const FloatRect inputBoundsInLayer = tmpBounds.toFloatRect();
chaviw7e72caf2020-12-02 16:50:43 -08002471
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002472 // Clamp surface inset to the input bounds.
2473 const auto surfaceInset = static_cast<float>(info.surfaceInset);
2474 const float xSurfaceInset =
2475 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getWidth() / 2.f));
2476 const float ySurfaceInset =
2477 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getHeight() / 2.f));
chaviw1ff3d1e2020-07-01 15:53:47 -07002478
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002479 // Apply the insets to the input bounds.
2480 const FloatRect insetBoundsInLayer(inputBoundsInLayer.left + xSurfaceInset,
2481 inputBoundsInLayer.top + ySurfaceInset,
2482 inputBoundsInLayer.right - xSurfaceInset,
2483 inputBoundsInLayer.bottom - ySurfaceInset);
Ady Abraham282f1d72019-07-24 18:05:56 -07002484
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002485 // Crop the input bounds to ensure it is within the parent's bounds.
2486 const FloatRect croppedInsetBoundsInLayer = mBounds.intersect(insetBoundsInLayer);
Ady Abraham282f1d72019-07-24 18:05:56 -07002487
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002488 const ui::Transform layerToScreen = getInputTransform();
2489 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
Vishnu Nair8033a492018-12-05 07:27:23 -08002490
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002491 const Rect roundedFrameInDisplay{layerToDisplay.transform(croppedInsetBoundsInLayer)};
2492 info.frameLeft = roundedFrameInDisplay.left;
2493 info.frameTop = roundedFrameInDisplay.top;
2494 info.frameRight = roundedFrameInDisplay.right;
2495 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002496
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002497 ui::Transform inputToLayer;
2498 inputToLayer.set(insetBoundsInLayer.left, insetBoundsInLayer.top);
2499 const ui::Transform inputToDisplay = layerToDisplay * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002500
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002501 // InputDispatcher expects a display-to-input transform.
2502 info.transform = inputToDisplay.inverse();
2503
2504 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002505 info.touchableRegion =
2506 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002507}
2508
chaviw3277faf2021-05-19 16:45:23 -05002509void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002510 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002511 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002512 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002513 }
2514 if (p != nullptr) {
2515 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2516 }
2517}
2518
Vishnu Naira066d902021-09-13 18:40:17 -07002519gui::DropInputMode Layer::getDropInputMode() const {
2520 gui::DropInputMode mode = mDrawingState.dropInputMode;
2521 if (mode == gui::DropInputMode::ALL) {
2522 return mode;
2523 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002524 sp<Layer> parent = mDrawingParent.promote();
2525 if (parent) {
2526 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002527 if (parentMode != gui::DropInputMode::NONE) {
2528 return parentMode;
2529 }
2530 }
2531 return mode;
2532}
2533
2534void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002535 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002536 return;
2537 }
2538
2539 // Check if we need to drop input unconditionally
2540 gui::DropInputMode dropInputMode = getDropInputMode();
2541 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002542 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002543 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2544 return;
2545 }
2546
2547 // Check if we need to check if the window is obscured by parent
2548 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2549 return;
2550 }
2551
2552 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002553 sp<Layer> parent = mDrawingParent.promote();
2554 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002555 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002556 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2557 static_cast<float>(getAlpha()));
2558 }
2559
2560 // Check if the parent has cropped the buffer
2561 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2562 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002563 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002564 return;
2565 }
2566
2567 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2568 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2569 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2570 // match then the layer has not been cropped by its parents.
2571 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2572 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2573
2574 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002575 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002576 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2577 getDebugName());
2578 } else {
2579 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2580 // input if the window is obscured. This check should be done in surfaceflinger but the
2581 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2582 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002583 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002584 }
2585}
2586
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002587WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002588 if (!hasInputInfo()) {
2589 mDrawingState.inputInfo.name = getName();
2590 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2591 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002592 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002593 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002594 }
2595
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002596 const ui::Transform& displayTransform =
2597 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2598
chaviw3277faf2021-05-19 16:45:23 -05002599 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002600 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002601 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002602
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002603 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002604
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002605 if (displayArgs.transform == nullptr) {
2606 // Do not let the window receive touches if it is not associated with a valid display
2607 // transform. We still allow the window to receive keys and prevent ANRs.
2608 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2609 }
2610
Robert Carr5dc426e2020-06-10 14:29:14 -07002611 // For compatibility reasons we let layers which can receive input
2612 // receive input before they have actually submitted a buffer. Because
2613 // of this we use canReceiveInput instead of isVisible to check the
2614 // policy-visibility, ignoring the buffer state. However for layers with
2615 // hasInputInfo()==false we can use the real visibility state.
2616 // We are just using these layers for occlusion detection in
2617 // InputDispatcher, and obviously if they aren't visible they can't occlude
2618 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002619 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2620 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2621
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002622 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002623 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002624 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002625
Vishnu Nair16a938f2021-09-24 07:14:54 -07002626 // If the window will be blacked out on a display because the display does not have the secure
2627 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002628 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002629 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002630 }
2631
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002632 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2633 if (info.replaceTouchableRegionWithCrop) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002634 const Rect bounds(cropLayer ? cropLayer->mScreenBounds : mScreenBounds);
2635 info.touchableRegion = Region(displayTransform.transform(bounds));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002636 } else if (cropLayer != nullptr) {
[1;3C2b9fc252021-02-04 16:16:50 -08002637 info.touchableRegion = info.touchableRegion.intersect(
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002638 displayTransform.transform(Rect{cropLayer->mScreenBounds}));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002639 }
2640
Winson Chunga30f7c92021-06-29 15:42:56 -07002641 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2642 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002643 if (isTrustedOverlay()) {
2644 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2645 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002646
chaviwaf87b3e2019-10-01 16:59:28 -07002647 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2648 // touches from going outside the cloned area.
2649 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002650 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002651 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2652 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002653 info.touchableRegion = info.touchableRegion.intersect(rect);
2654 }
2655 }
2656
Robert Carr720e5062018-07-30 17:45:14 -07002657 return info;
2658}
2659
chaviwaf87b3e2019-10-01 16:59:28 -07002660sp<Layer> Layer::getClonedRoot() {
2661 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002662 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002663 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002664 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002665 return nullptr;
2666 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002667 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002668}
2669
Robert Carredd13602020-04-13 17:24:34 -07002670bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002671 return mDrawingState.inputInfo.token != nullptr ||
2672 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002673}
2674
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002675compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002676 const DisplayDevice* display) const {
2677 if (!display) return nullptr;
Lloyd Piquede196652020-01-22 17:29:58 -08002678 return display->getCompositionDisplay()->getOutputLayerForLayer(getCompositionEngineLayerFE());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002679}
2680
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002681Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2682 const auto outputLayer = findOutputLayerForDisplay(display);
2683 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002684}
2685
chaviwb4c6e582019-08-16 14:35:07 -07002686void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002687 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002688 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002689 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2690 mPotentialCursor = clonedFrom->mPotentialCursor;
2691 mProtectedByApp = clonedFrom->mProtectedByApp;
2692 updateCloneBufferInfo();
2693}
2694
2695void Layer::updateCloneBufferInfo() {
2696 if (!isClone() || !isClonedFromAlive()) {
2697 return;
2698 }
2699
2700 sp<Layer> clonedFrom = getClonedFrom();
2701 mBufferInfo = clonedFrom->mBufferInfo;
2702 mSidebandStream = clonedFrom->mSidebandStream;
2703 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2704 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2705 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2706
2707 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2708 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2709 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2710 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2711 // the cloned drawingState again.
2712 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2713 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2714 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2715 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2716
2717 cloneDrawingState(clonedFrom.get());
2718
2719 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2720 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2721 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2722 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002723}
chaviw74b03172019-08-19 11:09:03 -07002724
2725void Layer::updateMirrorInfo() {
2726 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2727 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2728 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2729 // that case, we want to delete the reference to the clone since we want it to get
2730 // destroyed. The root, this layer, will still be around since the client can continue
2731 // to hold a reference, but no cloned layers will be displayed.
2732 mClonedChild = nullptr;
2733 return;
2734 }
2735
2736 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2737 // If the real layer exists and is in current state, add the clone as a child of the root.
2738 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2739 // copied to drawingState for the root layer. So the clonedChild is always removed from
2740 // drawingState and then needs to be added back each traversal.
2741 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2742 addChildToDrawing(mClonedChild);
2743 }
2744
2745 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002746 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002747 mClonedChild->updateClonedRelatives(clonedLayersMap);
2748}
2749
2750void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2751 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2752 // to the clone. If the real layer is no longer alive, continue traversing the children
2753 // since we may be able to pull out other children that are still alive.
2754 if (isClonedFromAlive()) {
2755 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002756 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002757 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002758 }
2759
2760 // The clone layer may have children in drawingState since they may have been created and
2761 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2762 // that already exist, since we can just re-use them.
2763 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2764 // not updated in the regular traversal. They are skipped since the root will lose the
2765 // reference to them when it copies its currentChildren to drawing.
2766 for (sp<Layer>& child : mDrawingChildren) {
2767 child->updateClonedDrawingState(clonedLayersMap);
2768 }
2769}
2770
2771void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2772 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2773 mDrawingChildren.clear();
2774
2775 if (!isClonedFromAlive()) {
2776 return;
2777 }
2778
2779 sp<Layer> clonedFrom = getClonedFrom();
2780 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2781 if (child == mirrorRoot) {
2782 // This is to avoid cyclical mirroring.
2783 continue;
2784 }
2785 sp<Layer> clonedChild = clonedLayersMap[child];
2786 if (clonedChild == nullptr) {
2787 clonedChild = child->createClone();
2788 clonedLayersMap[child] = clonedChild;
2789 }
2790 addChildToDrawing(clonedChild);
2791 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2792 }
2793}
2794
chaviwaf87b3e2019-10-01 16:59:28 -07002795void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2796 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2797 if (cropLayer != nullptr) {
2798 if (clonedLayersMap.count(cropLayer) == 0) {
2799 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2800 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002801 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002802 } else {
2803 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2804 mDrawingState.touchableRegionCrop = clonedCropLayer;
2805 }
2806 }
2807 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2808 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002809 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002810}
2811
2812void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002813 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002814 mDrawingState.zOrderRelatives.clear();
2815
2816 if (!isClonedFromAlive()) {
2817 return;
2818 }
2819
chaviwaf87b3e2019-10-01 16:59:28 -07002820 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002821 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002822 const sp<Layer>& relative = relativeWeak.promote();
2823 if (clonedLayersMap.count(relative) > 0) {
2824 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002825 mDrawingState.zOrderRelatives.add(clonedRelative);
2826 }
2827 }
2828
2829 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2830 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2831 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2832 // still traverse the children, but the layer with the missing relativeOf will not be shown
2833 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002834 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2835 if (clonedLayersMap.count(relativeOf) > 0) {
2836 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002837 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2838 }
2839
chaviwaf87b3e2019-10-01 16:59:28 -07002840 updateClonedInputInfo(clonedLayersMap);
2841
chaviw74b03172019-08-19 11:09:03 -07002842 for (sp<Layer>& child : mDrawingChildren) {
2843 child->updateClonedRelatives(clonedLayersMap);
2844 }
2845}
2846
2847void Layer::addChildToDrawing(const sp<Layer>& layer) {
2848 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002849 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002850}
2851
Steven Thomas62a4cf82020-01-31 12:04:03 -08002852Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2853 switch (compatibility) {
2854 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2855 return FrameRateCompatibility::Default;
2856 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2857 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002858 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2859 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002860 case ANATIVEWINDOW_FRAME_RATE_MIN:
2861 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002862 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2863 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002864 default:
2865 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2866 return FrameRateCompatibility::Default;
2867 }
2868}
2869
Marin Shalamanovc5986772021-03-16 16:09:49 +01002870scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2871 switch (strategy) {
2872 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2873 return Seamlessness::OnlySeamless;
2874 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2875 return Seamlessness::SeamedAndSeamless;
2876 default:
2877 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2878 return Seamlessness::Default;
2879 }
2880}
2881
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002882bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002883 const State& s(mDrawingState);
2884 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2885 return true;
2886 }
2887
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002888 sp<Layer> parent = mDrawingParent.promote();
2889 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002890}
2891
Robert Carr6a0382d2021-07-01 15:57:17 -07002892void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2893 mClonedChild = clonedChild;
2894 mHadClonedChild = true;
2895 mFlinger->mNumClones++;
2896}
2897
Vishnu Nairf9096652021-07-20 18:49:42 -07002898const String16 Layer::Handle::kDescriptor = String16("android.Layer.Handle");
2899
2900wp<Layer> Layer::fromHandle(const sp<IBinder>& handleBinder) {
2901 if (handleBinder == nullptr) {
2902 return nullptr;
2903 }
2904
2905 BBinder* b = handleBinder->localBinder();
2906 if (b == nullptr || b->getInterfaceDescriptor() != Handle::kDescriptor) {
2907 return nullptr;
2908 }
2909
2910 // We can safely cast this binder since its local and we verified its interface descriptor.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002911 sp<Handle> handle = sp<Handle>::cast(handleBinder);
Vishnu Nairf9096652021-07-20 18:49:42 -07002912 return handle->owner;
2913}
2914
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002915bool Layer::setDropInputMode(gui::DropInputMode mode) {
2916 if (mDrawingState.dropInputMode == mode) {
2917 return false;
2918 }
2919 mDrawingState.dropInputMode = mode;
2920 return true;
2921}
2922
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002923void Layer::cloneDrawingState(const Layer* from) {
2924 mDrawingState = from->mDrawingState;
2925 // Skip callback info since they are not applicable for cloned layers.
2926 mDrawingState.releaseBufferListener = nullptr;
2927 mDrawingState.callbackHandles = {};
2928}
2929
Patrick Williamsbb25f802022-08-30 23:02:34 +00002930void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2931 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
2932 const sp<Fence>& releaseFence,
2933 uint32_t currentMaxAcquiredBufferCount) {
2934 if (!listener) {
2935 return;
2936 }
2937 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
2938 listener->onReleaseBuffer({buffer->getId(), framenumber},
2939 releaseFence ? releaseFence : Fence::NO_FENCE,
2940 currentMaxAcquiredBufferCount);
2941}
2942
2943void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2944 // If we are displayed on multiple displays in a single composition cycle then we would
2945 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2946 // For example we can only use it if all the displays are client comp, and we need
2947 // to merge all the client comp fences. We could do this, but for now we just
2948 // disable the optimization when a layer is composed on multiple displays.
2949 if (mClearClientCompositionFenceOnLayerDisplayed) {
2950 mLastClientCompositionFence = nullptr;
2951 } else {
2952 mClearClientCompositionFenceOnLayerDisplayed = true;
2953 }
2954
2955 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2956 // buffer that was presented on this layer. The first transaction that came in this frame that
2957 // replaced the previous buffer on this layer needs this release fence, because the fence will
2958 // let the client know when that previous buffer is removed from the screen.
2959 //
2960 // Every other transaction on this layer does not need a release fence because no other
2961 // Transactions that were set on this layer this frame are going to have their preceding buffer
2962 // removed from the display this frame.
2963 //
2964 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2965 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2966 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2967 // the previous buffer will be released this frame. The third transaction also contains a
2968 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2969 // transaction will now no longer be presented so it is released immediately and the third
2970 // transaction doesn't need a previous release fence.
2971 sp<CallbackHandle> ch;
2972 for (auto& handle : mDrawingState.callbackHandles) {
2973 if (handle->releasePreviousBuffer &&
2974 mDrawingState.releaseBufferEndpoint == handle->listener) {
2975 ch = handle;
2976 break;
2977 }
2978 }
2979
2980 // Prevent tracing the same release multiple times.
2981 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2982 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2983 }
2984
2985 if (ch != nullptr) {
2986 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2987 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2988 ch->name = mName;
2989 }
2990}
2991
2992void Layer::onSurfaceFrameCreated(
2993 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2994 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2995 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2996 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2997 // leak.
2998 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2999 mName.c_str());
3000 std::string miniDump = mPendingJankClassifications.front()->miniDump();
3001 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
3002 mPendingJankClassifications.pop_front();
3003 }
3004 mPendingJankClassifications.emplace_back(surfaceFrame);
3005}
3006
3007void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
3008 for (const auto& handle : mDrawingState.callbackHandles) {
3009 handle->transformHint = mTransformHint;
3010 handle->dequeueReadyTime = dequeueReadyTime;
3011 handle->currentMaxAcquiredBufferCount =
3012 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
3013 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
3014 handle->previousReleaseCallbackId.framenumber);
3015 }
3016
3017 for (auto& handle : mDrawingState.callbackHandles) {
3018 if (handle->releasePreviousBuffer &&
3019 mDrawingState.releaseBufferEndpoint == handle->listener) {
3020 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
3021 break;
3022 }
3023 }
3024
3025 std::vector<JankData> jankData;
3026 jankData.reserve(mPendingJankClassifications.size());
3027 while (!mPendingJankClassifications.empty() &&
3028 mPendingJankClassifications.front()->getJankType()) {
3029 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
3030 mPendingJankClassifications.front();
3031 mPendingJankClassifications.pop_front();
3032 jankData.emplace_back(
3033 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
3034 }
3035
3036 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
3037 jankData);
3038
3039 sp<Fence> releaseFence = Fence::NO_FENCE;
3040 for (auto& handle : mDrawingState.callbackHandles) {
3041 if (handle->releasePreviousBuffer &&
3042 mDrawingState.releaseBufferEndpoint == handle->listener) {
3043 releaseFence =
3044 handle->previousReleaseFence ? handle->previousReleaseFence : Fence::NO_FENCE;
3045 break;
3046 }
3047 }
3048
3049 mDrawingState.callbackHandles = {};
3050}
3051
3052bool Layer::willPresentCurrentTransaction() const {
3053 // Returns true if the most recent Transaction applied to CurrentState will be presented.
3054 return (getSidebandStreamChanged() || getAutoRefresh() ||
3055 (mDrawingState.modified &&
3056 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
3057}
3058
3059bool Layer::setTransform(uint32_t transform) {
3060 if (mDrawingState.bufferTransform == transform) return false;
3061 mDrawingState.bufferTransform = transform;
3062 mDrawingState.modified = true;
3063 setTransactionFlags(eTransactionNeeded);
3064 return true;
3065}
3066
3067bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
3068 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
3069 mDrawingState.sequence++;
3070 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
3071 mDrawingState.modified = true;
3072 setTransactionFlags(eTransactionNeeded);
3073 return true;
3074}
3075
3076bool Layer::setBufferCrop(const Rect& bufferCrop) {
3077 if (mDrawingState.bufferCrop == bufferCrop) return false;
3078
3079 mDrawingState.sequence++;
3080 mDrawingState.bufferCrop = bufferCrop;
3081
3082 mDrawingState.modified = true;
3083 setTransactionFlags(eTransactionNeeded);
3084 return true;
3085}
3086
3087bool Layer::setDestinationFrame(const Rect& destinationFrame) {
3088 if (mDrawingState.destinationFrame == destinationFrame) return false;
3089
3090 mDrawingState.sequence++;
3091 mDrawingState.destinationFrame = destinationFrame;
3092
3093 mDrawingState.modified = true;
3094 setTransactionFlags(eTransactionNeeded);
3095 return true;
3096}
3097
3098// Translate destination frame into scale and position. If a destination frame is not set, use the
3099// provided scale and position
3100bool Layer::updateGeometry() {
3101 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
3102 mDrawingState.destinationFrame.isEmpty()) {
3103 // If destination frame is not set, use the requested transform set via
3104 // Layer::setPosition and Layer::setMatrix.
3105 return assignTransform(&mDrawingState.transform, mRequestedTransform);
3106 }
3107
3108 Rect destRect = mDrawingState.destinationFrame;
3109 int32_t destW = destRect.width();
3110 int32_t destH = destRect.height();
3111 if (destRect.left < 0) {
3112 destRect.left = 0;
3113 destRect.right = destW;
3114 }
3115 if (destRect.top < 0) {
3116 destRect.top = 0;
3117 destRect.bottom = destH;
3118 }
3119
3120 if (!mDrawingState.buffer) {
3121 ui::Transform t;
3122 t.set(destRect.left, destRect.top);
3123 return assignTransform(&mDrawingState.transform, t);
3124 }
3125
3126 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3127 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3128 // Undo any transformations on the buffer.
3129 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3130 std::swap(bufferWidth, bufferHeight);
3131 }
3132 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3133 if (mDrawingState.transformToDisplayInverse) {
3134 if (invTransform & ui::Transform::ROT_90) {
3135 std::swap(bufferWidth, bufferHeight);
3136 }
3137 }
3138
3139 float sx = destW / static_cast<float>(bufferWidth);
3140 float sy = destH / static_cast<float>(bufferHeight);
3141 ui::Transform t;
3142 t.set(sx, 0, 0, sy);
3143 t.set(destRect.left, destRect.top);
3144 return assignTransform(&mDrawingState.transform, t);
3145}
3146
3147bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3148 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3149 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3150 return false;
3151 }
3152
3153 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3154
3155 mDrawingState.sequence++;
3156 mDrawingState.modified = true;
3157 setTransactionFlags(eTransactionNeeded);
3158
3159 return true;
3160}
3161
3162bool Layer::setPosition(float x, float y) {
3163 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3164 return false;
3165 }
3166
3167 mRequestedTransform.set(x, y);
3168
3169 mDrawingState.sequence++;
3170 mDrawingState.modified = true;
3171 setTransactionFlags(eTransactionNeeded);
3172
3173 return true;
3174}
3175
3176bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3177 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3178 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
3179 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003180 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003181 if (!buffer) {
3182 return false;
3183 }
3184
3185 const bool frameNumberChanged =
3186 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3187 const uint64_t frameNumber =
3188 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003189 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003190
3191 if (mDrawingState.buffer) {
3192 mReleasePreviousBuffer = true;
3193 if (!mBufferInfo.mBuffer ||
3194 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3195 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3196 // If mDrawingState has a buffer, and we are about to update again
3197 // before swapping to drawing state, then the first buffer will be
3198 // dropped and we should decrement the pending buffer count and
3199 // call any release buffer callbacks if set.
3200 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3201 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3202 mDrawingState.acquireFence,
3203 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
3204 mOwnerUid));
3205 decrementPendingBufferCount();
3206 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3207 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3208 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
3209 mDrawingState.bufferSurfaceFrameTX.reset();
3210 }
3211 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3212 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3213 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3214 mLastClientCompositionFence,
3215 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
3216 mOwnerUid));
3217 mLastClientCompositionFence = nullptr;
3218 }
3219 }
3220
3221 mDrawingState.frameNumber = frameNumber;
3222 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3223 mDrawingState.buffer = std::move(buffer);
3224 mDrawingState.clientCacheId = bufferData.cachedBuffer;
3225
3226 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3227 ? bufferData.acquireFence
3228 : Fence::NO_FENCE;
3229 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3230 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3231 // We latched this buffer unsiganled, so we need to pass the acquire fence
3232 // on the callback instead of just the acquire time, since it's unknown at
3233 // this point.
3234 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3235 } else {
3236 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3237 }
3238
3239 mDrawingState.modified = true;
3240 setTransactionFlags(eTransactionNeeded);
3241
3242 const int32_t layerId = getSequence();
3243 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3244 mOwnerUid, postTime, getGameMode());
3245 mDrawingState.desiredPresentTime = desiredPresentTime;
3246 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3247
3248 const nsecs_t presentTime = [&] {
3249 if (!isAutoTimestamp) return desiredPresentTime;
3250
3251 const auto prediction =
3252 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
3253 if (prediction.has_value()) return prediction->presentTime;
3254
3255 return static_cast<nsecs_t>(0);
3256 }();
3257
3258 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
3259 mFlinger->mScheduler->recordLayerHistory(this, presentTime, LayerUpdateType::Buffer);
3260
3261 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3262
3263 if (dequeueTime && *dequeueTime != 0) {
3264 const uint64_t bufferId = mDrawingState.buffer->getId();
3265 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3266 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3267 FrameTracer::FrameEvent::DEQUEUE);
3268 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3269 FrameTracer::FrameEvent::QUEUE);
3270 }
3271
3272 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3273 return true;
3274}
3275
3276bool Layer::setDataspace(ui::Dataspace dataspace) {
3277 mDrawingState.dataspaceRequested = true;
3278 if (mDrawingState.dataspace == dataspace) return false;
3279 mDrawingState.dataspace = dataspace;
3280 mDrawingState.modified = true;
3281 setTransactionFlags(eTransactionNeeded);
3282 return true;
3283}
3284
3285bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3286 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3287 mDrawingState.hdrMetadata = hdrMetadata;
3288 mDrawingState.modified = true;
3289 setTransactionFlags(eTransactionNeeded);
3290 return true;
3291}
3292
3293bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
3294 mDrawingState.surfaceDamageRegion = surfaceDamage;
3295 mDrawingState.modified = true;
3296 setTransactionFlags(eTransactionNeeded);
3297 return true;
3298}
3299
3300bool Layer::setApi(int32_t api) {
3301 if (mDrawingState.api == api) return false;
3302 mDrawingState.api = api;
3303 mDrawingState.modified = true;
3304 setTransactionFlags(eTransactionNeeded);
3305 return true;
3306}
3307
3308bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3309 if (mDrawingState.sidebandStream == sidebandStream) return false;
3310
3311 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3312 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3313 } else if (sidebandStream != nullptr) {
3314 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3315 }
3316
3317 mDrawingState.sidebandStream = sidebandStream;
3318 mDrawingState.modified = true;
3319 setTransactionFlags(eTransactionNeeded);
3320 if (!mSidebandStreamChanged.exchange(true)) {
3321 // mSidebandStreamChanged was false
3322 mFlinger->onLayerUpdate();
3323 }
3324 return true;
3325}
3326
3327bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles) {
3328 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3329 if (handles.empty()) {
3330 mReleasePreviousBuffer = false;
3331 return false;
3332 }
3333
3334 const bool willPresent = willPresentCurrentTransaction();
3335
3336 for (const auto& handle : handles) {
3337 // If this transaction set a buffer on this layer, release its previous buffer
3338 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3339
3340 // If this layer will be presented in this frame
3341 if (willPresent) {
3342 // If this transaction set an acquire fence on this layer, set its acquire time
3343 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3344 handle->frameNumber = mDrawingState.frameNumber;
3345
3346 // Store so latched time and release fence can be set
3347 mDrawingState.callbackHandles.push_back(handle);
3348
3349 } else { // If this layer will NOT need to be relatched and presented this frame
3350 // Notify the transaction completed thread this handle is done
3351 mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
3352 }
3353 }
3354
3355 mReleasePreviousBuffer = false;
3356 mCallbackHandleAcquireTimeOrFence = -1;
3357
3358 return willPresent;
3359}
3360
3361Rect Layer::getBufferSize(const State& /*s*/) const {
3362 // for buffer state layers we use the display frame size as the buffer size.
3363
3364 if (mBufferInfo.mBuffer == nullptr) {
3365 return Rect::INVALID_RECT;
3366 }
3367
3368 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3369 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3370
3371 // Undo any transformations on the buffer and return the result.
3372 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3373 std::swap(bufWidth, bufHeight);
3374 }
3375
3376 if (getTransformToDisplayInverse()) {
3377 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3378 if (invTransform & ui::Transform::ROT_90) {
3379 std::swap(bufWidth, bufHeight);
3380 }
3381 }
3382
3383 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3384}
3385
3386FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3387 if (mBufferInfo.mBuffer == nullptr) {
3388 return parentBounds;
3389 }
3390
3391 return getBufferSize(getDrawingState()).toFloatRect();
3392}
3393
3394bool Layer::fenceHasSignaled() const {
3395 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3396 return true;
3397 }
3398
3399 const bool fenceSignaled =
3400 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3401 if (!fenceSignaled) {
3402 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3403 TimeStats::LatchSkipReason::LateAcquire);
3404 }
3405
3406 return fenceSignaled;
3407}
3408
Vishnu Nairba354102022-08-01 00:14:18 +00003409bool Layer::onPreComposition(nsecs_t refreshStartTime, bool /* updatingOutputGeometryThisFrame */) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003410 for (const auto& handle : mDrawingState.callbackHandles) {
3411 handle->refreshStartTime = refreshStartTime;
3412 }
3413 return hasReadyFrame();
3414}
3415
3416void Layer::setAutoRefresh(bool autoRefresh) {
3417 mDrawingState.autoRefresh = autoRefresh;
3418}
3419
3420bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3421 // We need to update the sideband stream if the layer has both a buffer and a sideband stream.
3422 editCompositionState()->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
3423
3424 if (mSidebandStreamChanged.exchange(false)) {
3425 const State& s(getDrawingState());
3426 // mSidebandStreamChanged was true
3427 mSidebandStream = s.sidebandStream;
3428 editCompositionState()->sidebandStream = mSidebandStream;
3429 if (mSidebandStream != nullptr) {
3430 setTransactionFlags(eTransactionNeeded);
3431 mFlinger->setTransactionFlags(eTraversalNeeded);
3432 }
3433 recomputeVisibleRegions = true;
3434
3435 return true;
3436 }
3437 return false;
3438}
3439
3440bool Layer::hasFrameUpdate() const {
3441 const State& c(getDrawingState());
3442 return (mDrawingStateModified || mDrawingState.modified) &&
3443 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3444}
3445
3446void Layer::updateTexImage(nsecs_t latchTime) {
3447 const State& s(getDrawingState());
3448
3449 if (!s.buffer) {
3450 if (s.bgColorLayer) {
3451 for (auto& handle : mDrawingState.callbackHandles) {
3452 handle->latchTime = latchTime;
3453 }
3454 }
3455 return;
3456 }
3457
3458 for (auto& handle : mDrawingState.callbackHandles) {
3459 if (handle->frameNumber == mDrawingState.frameNumber) {
3460 handle->latchTime = latchTime;
3461 }
3462 }
3463
3464 const int32_t layerId = getSequence();
3465 const uint64_t bufferId = mDrawingState.buffer->getId();
3466 const uint64_t frameNumber = mDrawingState.frameNumber;
3467 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3468 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3469 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3470
3471 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3472 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3473 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3474 FrameTracer::FrameEvent::LATCH);
3475
3476 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3477 if (bufferSurfaceFrame != nullptr &&
3478 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3479 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3480 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3481 // are processing the next state.
3482 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3483 mDrawingState.acquireFenceTime->getSignalTime(),
3484 latchTime);
3485 mDrawingState.bufferSurfaceFrameTX.reset();
3486 }
3487
3488 std::deque<sp<CallbackHandle>> remainingHandles;
3489 mFlinger->getTransactionCallbackInvoker()
3490 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3491 mDrawingState.callbackHandles = remainingHandles;
3492
3493 mDrawingStateModified = false;
3494}
3495
3496void Layer::gatherBufferInfo() {
3497 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3498 decrementPendingBufferCount();
3499 }
3500
3501 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3502 mBufferInfo.mBuffer = mDrawingState.buffer;
3503 mBufferInfo.mFence = mDrawingState.acquireFence;
3504 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3505 mBufferInfo.mPixelFormat =
3506 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3507 mBufferInfo.mFrameLatencyNeeded = true;
3508 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3509 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3510 mBufferInfo.mFence = mDrawingState.acquireFence;
3511 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3512 auto lastDataspace = mBufferInfo.mDataspace;
3513 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3514 if (lastDataspace != mBufferInfo.mDataspace) {
3515 mFlinger->mSomeDataspaceChanged = true;
3516 }
3517 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3518 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3519 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3520 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3521 mBufferInfo.mApi = mDrawingState.api;
3522 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
3523 mBufferInfo.mBufferSlot = mHwcSlotGenerator->getHwcCacheSlot(mDrawingState.clientCacheId);
3524}
3525
3526Rect Layer::computeBufferCrop(const State& s) {
3527 if (s.buffer && !s.bufferCrop.isEmpty()) {
3528 Rect bufferCrop;
3529 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3530 return bufferCrop;
3531 } else if (s.buffer) {
3532 return s.buffer->getBounds();
3533 } else {
3534 return s.bufferCrop;
3535 }
3536}
3537
3538sp<Layer> Layer::createClone() {
3539 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3540 args.textureName = mTextureName;
3541 sp<BufferStateLayer> layer = mFlinger->getFactory().createBufferStateLayer(args);
3542 layer->mHwcSlotGenerator = mHwcSlotGenerator;
3543 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3544 return layer;
3545}
3546
3547bool Layer::bufferNeedsFiltering() const {
3548 const State& s(getDrawingState());
3549 if (!s.buffer) {
3550 return false;
3551 }
3552
3553 int32_t bufferWidth = static_cast<int32_t>(s.buffer->getWidth());
3554 int32_t bufferHeight = static_cast<int32_t>(s.buffer->getHeight());
3555
3556 // Undo any transformations on the buffer and return the result.
3557 if (s.bufferTransform & ui::Transform::ROT_90) {
3558 std::swap(bufferWidth, bufferHeight);
3559 }
3560
3561 if (s.transformToDisplayInverse) {
3562 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3563 if (invTransform & ui::Transform::ROT_90) {
3564 std::swap(bufferWidth, bufferHeight);
3565 }
3566 }
3567
3568 const Rect layerSize{getBounds()};
3569 int32_t layerWidth = layerSize.getWidth();
3570 int32_t layerHeight = layerSize.getHeight();
3571
3572 // Align the layer orientation with the buffer before comparism
3573 if (mTransformHint & ui::Transform::ROT_90) {
3574 std::swap(layerWidth, layerHeight);
3575 }
3576
3577 return layerWidth != bufferWidth || layerHeight != bufferHeight;
3578}
3579
3580void Layer::decrementPendingBufferCount() {
3581 int32_t pendingBuffers = --mPendingBufferTransactions;
3582 tracePendingBufferCount(pendingBuffers);
3583}
3584
3585void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3586 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3587}
3588
3589/*
3590 * We don't want to send the layer's transform to input, but rather the
3591 * parent's transform. This is because Layer's transform is
3592 * information about how the buffer is placed on screen. The parent's
3593 * transform makes more sense to send since it's information about how the
3594 * layer is placed on screen. This transform is used by input to determine
3595 * how to go from screen space back to window space.
3596 */
3597ui::Transform Layer::getInputTransform() const {
3598 if (!hasBufferOrSidebandStream()) {
3599 return getTransform();
3600 }
3601 sp<Layer> parent = mDrawingParent.promote();
3602 if (parent == nullptr) {
3603 return ui::Transform();
3604 }
3605
3606 return parent->getTransform();
3607}
3608
3609/**
3610 * Similar to getInputTransform, we need to update the bounds to include the transform.
3611 * This is because bounds don't include the buffer transform, where the input assumes
3612 * that's already included.
3613 */
3614Rect Layer::getInputBounds() const {
3615 if (!hasBufferOrSidebandStream()) {
3616 return getCroppedBufferSize(getDrawingState());
3617 }
3618
3619 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
3620 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
3621 return bufferBounds;
3622 }
3623 return mDrawingState.transform.transform(bufferBounds);
3624}
3625
3626bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3627 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3628
3629 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3630 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3631 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3632 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3633 layer_state_t::eReparent;
3634
3635 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3636 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3637 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3638 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3639 layer_state_t::eInputInfoChanged;
3640
3641 if ((s.what & requiredFlags) != requiredFlags) {
3642 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3643 (s.what | requiredFlags) & ~s.what);
3644 return false;
3645 }
3646
3647 if (s.what & deniedFlags) {
3648 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3649 return false;
3650 }
3651
3652 if (s.what & allowedFlags) {
3653 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3654 }
3655
3656 if (s.what & layer_state_t::ePositionChanged) {
3657 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3658 ALOGV("%s: false [ePositionChanged changed]", __func__);
3659 return false;
3660 }
3661 }
3662
3663 if (s.what & layer_state_t::eAlphaChanged) {
3664 if (mDrawingState.color.a != s.alpha) {
3665 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3666 return false;
3667 }
3668 }
3669
3670 if (s.what & layer_state_t::eColorTransformChanged) {
3671 if (mDrawingState.colorTransform != s.colorTransform) {
3672 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3673 return false;
3674 }
3675 }
3676
3677 if (s.what & layer_state_t::eBackgroundColorChanged) {
3678 if (mDrawingState.bgColorLayer || s.bgColorAlpha != 0) {
3679 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3680 return false;
3681 }
3682 }
3683
3684 if (s.what & layer_state_t::eMatrixChanged) {
3685 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3686 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3687 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3688 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3689 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3690 return false;
3691 }
3692 }
3693
3694 if (s.what & layer_state_t::eCornerRadiusChanged) {
3695 if (mDrawingState.cornerRadius != s.cornerRadius) {
3696 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3697 return false;
3698 }
3699 }
3700
3701 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3702 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3703 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3704 return false;
3705 }
3706 }
3707
3708 if (s.what & layer_state_t::eTransformChanged) {
3709 if (mDrawingState.bufferTransform != s.transform) {
3710 ALOGV("%s: false [eTransformChanged changed]", __func__);
3711 return false;
3712 }
3713 }
3714
3715 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3716 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3717 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3718 return false;
3719 }
3720 }
3721
3722 if (s.what & layer_state_t::eCropChanged) {
3723 if (mDrawingState.crop != s.crop) {
3724 ALOGV("%s: false [eCropChanged changed]", __func__);
3725 return false;
3726 }
3727 }
3728
3729 if (s.what & layer_state_t::eDataspaceChanged) {
3730 if (mDrawingState.dataspace != s.dataspace) {
3731 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3732 return false;
3733 }
3734 }
3735
3736 if (s.what & layer_state_t::eHdrMetadataChanged) {
3737 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3738 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3739 return false;
3740 }
3741 }
3742
3743 if (s.what & layer_state_t::eSidebandStreamChanged) {
3744 if (mDrawingState.sidebandStream != s.sidebandStream) {
3745 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3746 return false;
3747 }
3748 }
3749
3750 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3751 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3752 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3753 return false;
3754 }
3755 }
3756
3757 if (s.what & layer_state_t::eShadowRadiusChanged) {
3758 if (mDrawingState.shadowRadius != s.shadowRadius) {
3759 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3760 return false;
3761 }
3762 }
3763
3764 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3765 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3766 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3767 return false;
3768 }
3769 }
3770
3771 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3772 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3773 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3774 return false;
3775 }
3776 }
3777
3778 if (s.what & layer_state_t::eStretchChanged) {
3779 StretchEffect temp = s.stretchEffect;
3780 temp.sanitize();
3781 if (mDrawingState.stretchEffect != temp) {
3782 ALOGV("%s: false [eStretchChanged changed]", __func__);
3783 return false;
3784 }
3785 }
3786
3787 if (s.what & layer_state_t::eBufferCropChanged) {
3788 if (mDrawingState.bufferCrop != s.bufferCrop) {
3789 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3790 return false;
3791 }
3792 }
3793
3794 if (s.what & layer_state_t::eDestinationFrameChanged) {
3795 if (mDrawingState.destinationFrame != s.destinationFrame) {
3796 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3797 return false;
3798 }
3799 }
3800
3801 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3802 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3803 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3804 return false;
3805 }
3806 }
3807
3808 ALOGV("%s: true", __func__);
3809 return true;
3810}
3811
3812bool Layer::isHdrY410() const {
3813 // pixel format is HDR Y410 masquerading as RGBA_1010102
3814 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3815 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3816 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3817}
3818
3819sp<compositionengine::LayerFE> Layer::getCompositionEngineLayerFE() const {
3820 // There's no need to get a CE Layer if the layer isn't going to draw anything.
3821 if (hasSomethingToDraw()) {
3822 return asLayerFE();
3823 } else {
3824 return nullptr;
3825 }
3826}
3827
3828compositionengine::LayerFECompositionState* Layer::editCompositionState() {
3829 return mCompositionState.get();
3830}
3831
3832const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
3833 return mCompositionState.get();
3834}
3835
3836void Layer::useSurfaceDamage() {
3837 if (mFlinger->mForceFullDamage) {
3838 surfaceDamageRegion = Region::INVALID_REGION;
3839 } else {
3840 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3841 }
3842}
3843
3844void Layer::useEmptyDamage() {
3845 surfaceDamageRegion.clear();
3846}
3847
3848bool Layer::isOpaque(const Layer::State& s) const {
3849 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3850 // layer's opaque flag.
3851 if (!hasSomethingToDraw()) {
3852 return false;
3853 }
3854
3855 // if the layer has the opaque flag, then we're always opaque
3856 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3857 return true;
3858 }
3859
3860 // If the buffer has no alpha channel, then we are opaque
3861 if (hasBufferOrSidebandStream() && isOpaqueFormat(getPixelFormat())) {
3862 return true;
3863 }
3864
3865 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3866 return fillsColor() && getAlpha() == 1.0_hf;
3867}
3868
3869bool Layer::canReceiveInput() const {
3870 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3871}
3872
3873bool Layer::isVisible() const {
3874 if (!hasSomethingToDraw()) {
3875 return false;
3876 }
3877
3878 if (isHiddenByPolicy()) {
3879 return false;
3880 }
3881
3882 return getAlpha() > 0.0f || hasBlur();
3883}
3884
3885void Layer::onPostComposition(const DisplayDevice* display,
3886 const std::shared_ptr<FenceTime>& glDoneFence,
3887 const std::shared_ptr<FenceTime>& presentFence,
3888 const CompositorTiming& compositorTiming) {
3889 // mFrameLatencyNeeded is true when a new frame was latched for the
3890 // composition.
3891 if (!mBufferInfo.mFrameLatencyNeeded) return;
3892
3893 for (const auto& handle : mDrawingState.callbackHandles) {
3894 handle->gpuCompositionDoneFence = glDoneFence;
3895 handle->compositorTiming = compositorTiming;
3896 }
3897
3898 // Update mFrameTracker.
3899 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3900 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3901
3902 const int32_t layerId = getSequence();
3903 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3904
3905 const auto outputLayer = findOutputLayerForDisplay(display);
3906 if (outputLayer && outputLayer->requiresClientComposition()) {
3907 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3908 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3909 clientCompositionTimestamp,
3910 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3911 // Update the SurfaceFrames in the drawing state
3912 if (mDrawingState.bufferSurfaceFrameTX) {
3913 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3914 }
3915 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3916 surfaceFrame->setGpuComposition();
3917 }
3918 }
3919
3920 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3921 if (frameReadyFence->isValid()) {
3922 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3923 } else {
3924 // There was no fence for this frame, so assume that it was ready
3925 // to be presented at the desired present time.
3926 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3927 }
3928
3929 if (display) {
Dominik Laskowskif8734e02022-08-26 09:06:59 -07003930 const Fps refreshRate = display->refreshRateConfigs().getActiveModePtr()->getFps();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003931 const std::optional<Fps> renderRate =
3932 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3933
3934 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3935 const auto gameMode = getGameMode();
3936
3937 if (presentFence->isValid()) {
3938 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3939 refreshRate, renderRate, vote, gameMode);
3940 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3941 presentFence,
3942 FrameTracer::FrameEvent::PRESENT_FENCE);
3943 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3944 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3945 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
3946 // The HWC doesn't support present fences, so use the refresh
3947 // timestamp instead.
3948 const nsecs_t actualPresentTime = display->getRefreshTimestamp();
3949 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3950 refreshRate, renderRate, vote, gameMode);
3951 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3952 mCurrentFrameNumber, actualPresentTime,
3953 FrameTracer::FrameEvent::PRESENT_FENCE);
3954 mFrameTracker.setActualPresentTime(actualPresentTime);
3955 }
3956 }
3957
3958 mFrameTracker.advanceFrame();
3959 mBufferInfo.mFrameLatencyNeeded = false;
3960}
3961
3962bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
3963 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3964 getDrawingState().frameNumber);
3965
3966 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3967
3968 if (refreshRequired) {
3969 return refreshRequired;
3970 }
3971
3972 // If the head buffer's acquire fence hasn't signaled yet, return and
3973 // try again later
3974 if (!fenceHasSignaled()) {
3975 ATRACE_NAME("!fenceHasSignaled()");
3976 mFlinger->onLayerUpdate();
3977 return false;
3978 }
3979
3980 updateTexImage(latchTime);
3981 if (mDrawingState.buffer == nullptr) {
3982 return false;
3983 }
3984
3985 // Capture the old state of the layer for comparisons later
3986 BufferInfo oldBufferInfo = mBufferInfo;
3987 const bool oldOpacity = isOpaque(mDrawingState);
3988 mPreviousFrameNumber = mCurrentFrameNumber;
3989 mCurrentFrameNumber = mDrawingState.frameNumber;
3990 gatherBufferInfo();
3991
3992 if (oldBufferInfo.mBuffer == nullptr) {
3993 // the first time we receive a buffer, we need to trigger a
3994 // geometry invalidation.
3995 recomputeVisibleRegions = true;
3996 }
3997
3998 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3999 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
4000 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
4001 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
4002 recomputeVisibleRegions = true;
4003 }
4004
4005 if (oldBufferInfo.mBuffer != nullptr) {
4006 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
4007 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
4008 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
4009 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
4010 recomputeVisibleRegions = true;
4011 }
4012 }
4013
4014 if (oldOpacity != isOpaque(mDrawingState)) {
4015 recomputeVisibleRegions = true;
4016 }
4017
4018 return true;
4019}
4020
4021bool Layer::hasReadyFrame() const {
4022 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4023}
4024
4025bool Layer::isProtected() const {
4026 return (mBufferInfo.mBuffer != nullptr) &&
4027 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4028}
4029
4030// As documented in libhardware header, formats in the range
4031// 0x100 - 0x1FF are specific to the HAL implementation, and
4032// are known to have no alpha channel
4033// TODO: move definition for device-specific range into
4034// hardware.h, instead of using hard-coded values here.
4035#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
4036
4037bool Layer::isOpaqueFormat(PixelFormat format) {
4038 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
4039 return true;
4040 }
4041 switch (format) {
4042 case PIXEL_FORMAT_RGBA_8888:
4043 case PIXEL_FORMAT_BGRA_8888:
4044 case PIXEL_FORMAT_RGBA_FP16:
4045 case PIXEL_FORMAT_RGBA_1010102:
4046 case PIXEL_FORMAT_R_8:
4047 return false;
4048 }
4049 // in all other case, we have no blending (also for unknown formats)
4050 return true;
4051}
4052
4053bool Layer::needsFiltering(const DisplayDevice* display) const {
4054 if (!hasBufferOrSidebandStream()) {
4055 return false;
4056 }
4057 const auto outputLayer = findOutputLayerForDisplay(display);
4058 if (outputLayer == nullptr) {
4059 return false;
4060 }
4061
4062 // We need filtering if the sourceCrop rectangle size does not match the
4063 // displayframe rectangle size (not a 1:1 render)
4064 const auto& compositionState = outputLayer->getState();
4065 const auto displayFrame = compositionState.displayFrame;
4066 const auto sourceCrop = compositionState.sourceCrop;
4067 return sourceCrop.getHeight() != displayFrame.getHeight() ||
4068 sourceCrop.getWidth() != displayFrame.getWidth();
4069}
4070
4071bool Layer::needsFilteringForScreenshots(const DisplayDevice* display,
4072 const ui::Transform& inverseParentTransform) const {
4073 if (!hasBufferOrSidebandStream()) {
4074 return false;
4075 }
4076 const auto outputLayer = findOutputLayerForDisplay(display);
4077 if (outputLayer == nullptr) {
4078 return false;
4079 }
4080
4081 // We need filtering if the sourceCrop rectangle size does not match the
4082 // viewport rectangle size (not a 1:1 render)
4083 const auto& compositionState = outputLayer->getState();
4084 const ui::Transform& displayTransform = display->getTransform();
4085 const ui::Transform inverseTransform = inverseParentTransform * displayTransform.inverse();
4086 // Undo the transformation of the displayFrame so that we're back into
4087 // layer-stack space.
4088 const Rect frame = inverseTransform.transform(compositionState.displayFrame);
4089 const FloatRect sourceCrop = compositionState.sourceCrop;
4090
4091 int32_t frameHeight = frame.getHeight();
4092 int32_t frameWidth = frame.getWidth();
4093 // If the display transform had a rotational component then undo the
4094 // rotation so that the orientation matches the source crop.
4095 if (displayTransform.getOrientation() & ui::Transform::ROT_90) {
4096 std::swap(frameHeight, frameWidth);
4097 }
4098 return sourceCrop.getHeight() != frameHeight || sourceCrop.getWidth() != frameWidth;
4099}
4100
4101void Layer::latchAndReleaseBuffer() {
4102 if (hasReadyFrame()) {
4103 bool ignored = false;
4104 latchBuffer(ignored, systemTime());
4105 }
4106 releasePendingBuffer(systemTime());
4107}
4108
4109PixelFormat Layer::getPixelFormat() const {
4110 return mBufferInfo.mPixelFormat;
4111}
4112
4113bool Layer::getTransformToDisplayInverse() const {
4114 return mBufferInfo.mTransformToDisplayInverse;
4115}
4116
4117Rect Layer::getBufferCrop() const {
4118 // this is the crop rectangle that applies to the buffer
4119 // itself (as opposed to the window)
4120 if (!mBufferInfo.mCrop.isEmpty()) {
4121 // if the buffer crop is defined, we use that
4122 return mBufferInfo.mCrop;
4123 } else if (mBufferInfo.mBuffer != nullptr) {
4124 // otherwise we use the whole buffer
4125 return mBufferInfo.mBuffer->getBounds();
4126 } else {
4127 // if we don't have a buffer yet, we use an empty/invalid crop
4128 return Rect();
4129 }
4130}
4131
4132uint32_t Layer::getBufferTransform() const {
4133 return mBufferInfo.mTransform;
4134}
4135
4136ui::Dataspace Layer::getDataSpace() const {
4137 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
4138}
4139
4140ui::Dataspace Layer::getRequestedDataSpace() const {
4141 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4142}
4143
4144ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4145 ui::Dataspace updatedDataspace = dataspace;
4146 // translate legacy dataspaces to modern dataspaces
4147 switch (dataspace) {
4148 case ui::Dataspace::SRGB:
4149 updatedDataspace = ui::Dataspace::V0_SRGB;
4150 break;
4151 case ui::Dataspace::SRGB_LINEAR:
4152 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4153 break;
4154 case ui::Dataspace::JFIF:
4155 updatedDataspace = ui::Dataspace::V0_JFIF;
4156 break;
4157 case ui::Dataspace::BT601_625:
4158 updatedDataspace = ui::Dataspace::V0_BT601_625;
4159 break;
4160 case ui::Dataspace::BT601_525:
4161 updatedDataspace = ui::Dataspace::V0_BT601_525;
4162 break;
4163 case ui::Dataspace::BT709:
4164 updatedDataspace = ui::Dataspace::V0_BT709;
4165 break;
4166 default:
4167 break;
4168 }
4169
4170 return updatedDataspace;
4171}
4172
4173sp<GraphicBuffer> Layer::getBuffer() const {
4174 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4175}
4176
4177void Layer::getDrawingTransformMatrix(bool filteringEnabled, float outMatrix[16]) const {
4178 sp<GraphicBuffer> buffer = getBuffer();
4179 if (!buffer) {
4180 ALOGE("Buffer should not be null!");
4181 return;
4182 }
4183 GLConsumer::computeTransformMatrix(outMatrix, buffer->getWidth(), buffer->getHeight(),
4184 buffer->getPixelFormat(), mBufferInfo.mCrop,
4185 mBufferInfo.mTransform, filteringEnabled);
4186}
4187
4188void Layer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
4189 mTransformHint = getFixedTransformHint();
4190 if (mTransformHint == ui::Transform::ROT_INVALID) {
4191 mTransformHint = displayTransformHint;
4192 }
4193}
4194
4195const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4196 return mBufferInfo.mBuffer;
4197}
4198
4199bool Layer::setColor(const half3& color) {
4200 if (mDrawingState.color.r == color.r && mDrawingState.color.g == color.g &&
4201 mDrawingState.color.b == color.b) {
4202 return false;
4203 }
4204
4205 mDrawingState.sequence++;
4206 mDrawingState.color.r = color.r;
4207 mDrawingState.color.g = color.g;
4208 mDrawingState.color.b = color.b;
4209 mDrawingState.modified = true;
4210 setTransactionFlags(eTransactionNeeded);
4211 return true;
4212}
4213
4214bool Layer::fillsColor() const {
4215 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4216 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4217}
4218
4219bool Layer::hasBlur() const {
4220 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4221}
4222
Vishnu Nairba354102022-08-01 00:14:18 +00004223void Layer::updateSnapshot(bool updateGeometry) {
4224 if (!getCompositionEngineLayerFE()) {
4225 return;
4226 }
4227
4228 if (updateGeometry) {
4229 prepareBasicGeometryCompositionState();
4230 prepareGeometryCompositionState();
4231 }
4232 preparePerFrameCompositionState();
4233}
4234
Mathias Agopian13127d82013-03-05 17:47:11 -08004235// ---------------------------------------------------------------------------
4236
Marin Shalamanov46084422020-10-13 12:33:42 +02004237std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004238 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4239 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004240}
4241
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004242} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004243
4244#if defined(__gl_h_)
4245#error "don't include gl/gl.h in this file"
4246#endif
4247
4248#if defined(__gl2_h_)
4249#error "don't include gl2/gl2.h in this file"
4250#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004251
4252// TODO(b/129481165): remove the #pragma below and fix conversion issues
4253#pragma clang diagnostic pop // ignored "-Wconversion"