blob: b6927202f287302a728fa74844d7175184be849c [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
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070068#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080069#include "DisplayHardware/HWComposer.h"
Vishnu Nairfa247b12020-02-11 08:58:26 -080070#include "EffectLayer.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 }
468}
469
Vishnu Nair60356342018-11-13 13:00:45 -0800470Rect Layer::getCroppedBufferSize(const State& s) const {
471 Rect size = getBufferSize(s);
472 Rect crop = getCrop(s);
473 if (!crop.isEmpty() && size.isValid()) {
474 size.intersect(crop, &size);
475 } else if (!crop.isEmpty()) {
476 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700477 }
Vishnu Nair60356342018-11-13 13:00:45 -0800478 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800479}
480
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700481void Layer::setupRoundedCornersCropCoordinates(Rect win,
482 const FloatRect& roundedCornersCrop) const {
483 // Translate win by the rounded corners rect coordinates, to have all values in
484 // layer coordinate space.
485 win.left -= roundedCornersCrop.left;
486 win.right -= roundedCornersCrop.left;
487 win.top -= roundedCornersCrop.top;
488 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700489}
490
Lloyd Piquede196652020-01-22 17:29:58 -0800491void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800492 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800493 const auto alpha = static_cast<float>(getAlpha());
494 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700495 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800496
497 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
498 if (!opaque || alpha != 1.0f) {
499 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
500 : Hwc2::IComposerClient::BlendMode::COVERAGE;
501 }
502
Lloyd Piquede196652020-01-22 17:29:58 -0800503 auto* compositionState = editCompositionState();
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700504 compositionState->outputFilter = getOutputFilter();
Lloyd Piquede196652020-01-22 17:29:58 -0800505 compositionState->isVisible = isVisible();
506 compositionState->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
507 compositionState->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800508
Lloyd Piquede196652020-01-22 17:29:58 -0800509 compositionState->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800510 contentDirty = false;
511
Lloyd Piquede196652020-01-22 17:29:58 -0800512 compositionState->geomLayerBounds = mBounds;
513 compositionState->geomLayerTransform = getTransform();
514 compositionState->geomInverseLayerTransform = compositionState->geomLayerTransform.inverse();
515 compositionState->transparentRegionHint = getActiveTransparentRegion(drawingState);
Lloyd Piquec6687342019-03-07 21:34:57 -0800516
Lloyd Piquede196652020-01-22 17:29:58 -0800517 compositionState->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
518 compositionState->alpha = alpha;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400519 compositionState->backgroundBlurRadius = drawingState.backgroundBlurRadius;
520 compositionState->blurRegions = drawingState.blurRegions;
John Reckc00c6692021-02-16 11:37:33 -0500521 compositionState->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800522}
523
Lloyd Piquede196652020-01-22 17:29:58 -0800524void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800525 const auto& drawingState{getDrawingState()};
Lloyd Piquede196652020-01-22 17:29:58 -0800526 auto* compositionState = editCompositionState();
David Sodman15094112018-10-11 09:39:37 -0700527
Lloyd Piquede196652020-01-22 17:29:58 -0800528 compositionState->geomBufferSize = getBufferSize(drawingState);
529 compositionState->geomContentCrop = getBufferCrop();
530 compositionState->geomCrop = getCrop(drawingState);
531 compositionState->geomBufferTransform = getBufferTransform();
532 compositionState->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
533 compositionState->geomUsesSourceCrop = usesSourceCrop();
534 compositionState->isSecure = isSecure();
535
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800536 compositionState->metadata.clear();
537 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
538 for (const auto& [key, mandatory] : supportedMetadata) {
539 const auto& genericLayerMetadataCompatibilityMap =
540 mFlinger->getGenericLayerMetadataKeyMap();
541 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
542 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
543 continue;
544 }
545 const uint32_t id = compatIter->second;
546
547 auto it = drawingState.metadata.mMap.find(id);
548 if (it == std::end(drawingState.metadata.mMap)) {
549 continue;
550 }
551
552 compositionState->metadata
553 .emplace(key, compositionengine::GenericLayerMetadataEntry{mandatory, it->second});
554 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800555}
David Sodmanba340492018-08-05 21:51:33 -0700556
Lloyd Piquede196652020-01-22 17:29:58 -0800557void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800558 const auto& drawingState{getDrawingState()};
Lloyd Piquede196652020-01-22 17:29:58 -0800559 auto* compositionState = editCompositionState();
Lloyd Piquef5275482019-01-29 18:42:42 -0800560
Lloyd Piquede196652020-01-22 17:29:58 -0800561 compositionState->forceClientComposition = false;
562
563 compositionState->isColorspaceAgnostic = isColorSpaceAgnostic();
564 compositionState->dataspace = getDataSpace();
565 compositionState->colorTransform = getColorTransform();
566 compositionState->colorTransformIsIdentity = !hasColorTransform();
567 compositionState->surfaceDamage = surfaceDamageRegion;
568 compositionState->hasProtectedContent = isProtected();
Sally Qi81d95e62022-03-21 19:41:33 -0700569 compositionState->dimmingEnabled = isDimmingEnabled();
Lloyd Pique688abd42019-02-15 15:42:24 -0800570
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700571 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700572
Lloyd Piquede196652020-01-22 17:29:58 -0800573 compositionState->isOpaque =
Lloyd Pique688abd42019-02-15 15:42:24 -0800574 isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800575
576 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400577 // Rounded corners no longer force client composition, since we may use a
578 // hole punch so that the layer will appear to have rounded corners.
579 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
John Reckc00c6692021-02-16 11:37:33 -0500580 compositionState->stretchEffect.hasEffect()) {
Lloyd Piquede196652020-01-22 17:29:58 -0800581 compositionState->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800582 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700583 // If there are no visible region changes, we still need to update blur parameters.
584 compositionState->blurRegions = drawingState.blurRegions;
585 compositionState->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400586
587 // Layer framerate is used in caching decisions.
588 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
589 // LayerFECompositionState where it would be visible to Flattener.
590 compositionState->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000591
592 if (hasBufferOrSidebandStream()) {
593 preparePerFrameBufferCompositionState();
594 } else {
595 preparePerFrameEffectsCompositionState();
596 }
597}
598
599void Layer::preparePerFrameBufferCompositionState() {
600 // Sideband layers
601 auto* compositionState = editCompositionState();
602 if (compositionState->sidebandStream.get() && !compositionState->sidebandStreamHasFrame) {
603 compositionState->compositionType =
604 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
605 return;
606 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
607 compositionState->compositionType =
608 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
609 } else {
610 // Normal buffer layers
611 compositionState->hdrMetadata = mBufferInfo.mHdrMetadata;
612 compositionState->compositionType = mPotentialCursor
613 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
614 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
615 }
616
617 compositionState->buffer = getBuffer();
618 compositionState->bufferSlot = (mBufferInfo.mBufferSlot == BufferQueue::INVALID_BUFFER_SLOT)
619 ? 0
620 : mBufferInfo.mBufferSlot;
621 compositionState->acquireFence = mBufferInfo.mFence;
622 compositionState->frameNumber = mBufferInfo.mFrameNumber;
623 compositionState->sidebandStreamHasFrame = false;
624}
625
626void Layer::preparePerFrameEffectsCompositionState() {
627 auto* compositionState = editCompositionState();
628 compositionState->color = getColor();
629 compositionState->compositionType =
630 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800631}
632
Lloyd Piquede196652020-01-22 17:29:58 -0800633void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800634 const State& drawingState{getDrawingState()};
Lloyd Piquede196652020-01-22 17:29:58 -0800635 auto* compositionState = editCompositionState();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800636
637 // Apply the layer's transform, followed by the display's global transform
638 // Here we're guaranteed that the layer's transform preserves rects
639 Rect win = getCroppedBufferSize(drawingState);
640 // Subtract the transparent region and snap to the bounds
641 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
642 Rect frame(getTransform().transform(bounds));
643
Lloyd Piquede196652020-01-22 17:29:58 -0800644 compositionState->cursorFrame = frame;
645}
646
647sp<compositionengine::LayerFE> Layer::asLayerFE() const {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700648 compositionengine::LayerFE* layerFE = const_cast<compositionengine::LayerFE*>(
Lloyd Piquede196652020-01-22 17:29:58 -0800649 static_cast<const compositionengine::LayerFE*>(this));
Ady Abrahamd11bade2022-08-01 16:18:03 -0700650 return sp<compositionengine::LayerFE>::fromExisting(layerFE);
Lloyd Piquede196652020-01-22 17:29:58 -0800651}
652
Lloyd Piquede196652020-01-22 17:29:58 -0800653void Layer::prepareCompositionState(compositionengine::LayerFE::StateSubset subset) {
Lloyd Piquec6687342019-03-07 21:34:57 -0800654 using StateSubset = compositionengine::LayerFE::StateSubset;
Lloyd Piquef5275482019-01-29 18:42:42 -0800655
Lloyd Piquec6687342019-03-07 21:34:57 -0800656 switch (subset) {
657 case StateSubset::BasicGeometry:
Lloyd Piquede196652020-01-22 17:29:58 -0800658 prepareBasicGeometryCompositionState();
Lloyd Piquec6687342019-03-07 21:34:57 -0800659 break;
660
661 case StateSubset::GeometryAndContent:
Lloyd Piquede196652020-01-22 17:29:58 -0800662 prepareBasicGeometryCompositionState();
663 prepareGeometryCompositionState();
664 preparePerFrameCompositionState();
Lloyd Piquec6687342019-03-07 21:34:57 -0800665 break;
666
667 case StateSubset::Content:
Lloyd Piquede196652020-01-22 17:29:58 -0800668 preparePerFrameCompositionState();
669 break;
670
671 case StateSubset::Cursor:
672 prepareCursorCompositionState();
Lloyd Piquec6687342019-03-07 21:34:57 -0800673 break;
674 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800675}
Mathias Agopian29a367b2011-07-12 14:51:45 -0700676
Lloyd Piquea83776c2019-01-29 18:42:32 -0800677const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700678 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800679}
680
Mathias Agopian13127d82013-03-05 17:47:11 -0800681// ---------------------------------------------------------------------------
682// drawing...
683// ---------------------------------------------------------------------------
684
Vishnu Nair9b079a22020-01-21 14:36:08 -0800685std::optional<compositionengine::LayerFE::LayerSettings> Layer::prepareClientComposition(
Patrick Williams16d8b2c2022-08-08 17:29:05 +0000686 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000687 std::optional<compositionengine::LayerFE::LayerSettings> layerSettings =
688 prepareClientCompositionInternal(targetSettings);
689 // Nothing to render.
690 if (!layerSettings) {
691 return {};
692 }
693
694 // HWC requests to clear this layer.
695 if (targetSettings.clearContent) {
696 prepareClearClientComposition(*layerSettings, false /* blackout */);
697 return layerSettings;
698 }
699
700 // set the shadow for the layer if needed
701 prepareShadowClientComposition(*layerSettings, targetSettings.viewport);
702
703 return layerSettings;
704}
705
706std::optional<compositionengine::LayerFE::LayerSettings> Layer::prepareClientCompositionInternal(
707 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
708 ATRACE_CALL();
709
Lloyd Piquede196652020-01-22 17:29:58 -0800710 if (!getCompositionState()) {
Lloyd Piquef16688f2019-02-19 17:47:57 -0800711 return {};
712 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800713
Vishnu Nair4351ad52019-02-11 14:13:02 -0800714 FloatRect bounds = getBounds();
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000715 half alpha = getAlpha();
Vishnu Nair9b079a22020-01-21 14:36:08 -0800716
717 compositionengine::LayerFE::LayerSettings layerSettings;
Lloyd Piquef16688f2019-02-19 17:47:57 -0800718 layerSettings.geometry.boundaries = bounds;
chaviwc6ad8af2020-08-03 11:33:30 -0700719 layerSettings.geometry.positionTransform = getTransform().asMatrix4();
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000720
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400721 // skip drawing content if the targetSettings indicate the content will be occluded
Ady Abrahambaa6cf52021-07-13 14:02:19 -0700722 const bool drawContent = targetSettings.realContentIsVisible || targetSettings.clearContent;
723 layerSettings.skipContentDraw = !drawContent;
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400724
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000725 if (hasColorTransform()) {
Lloyd Piquef16688f2019-02-19 17:47:57 -0800726 layerSettings.colorTransform = getColorTransform();
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000727 }
728
729 const auto roundedCornerState = getRoundedCornerState();
Lloyd Piquef16688f2019-02-19 17:47:57 -0800730 layerSettings.geometry.roundedCornersRadius = roundedCornerState.radius;
731 layerSettings.geometry.roundedCornersCrop = roundedCornerState.cropRect;
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000732
Lloyd Piquef16688f2019-02-19 17:47:57 -0800733 layerSettings.alpha = alpha;
chaviw4244e032019-09-04 11:27:49 -0700734 layerSettings.sourceDataspace = getDataSpace();
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700735
Alec Mouridda07d92022-04-25 22:39:25 +0000736 // Override the dataspace transfer from 170M to sRGB if the device configuration requests this.
737 // We do this here instead of in buffer info so that dumpsys can still report layers that are
738 // using the 170M transfer.
739 if (mFlinger->mTreat170mAsSrgb &&
740 (layerSettings.sourceDataspace & HAL_DATASPACE_TRANSFER_MASK) ==
741 HAL_DATASPACE_TRANSFER_SMPTE_170M) {
742 layerSettings.sourceDataspace = static_cast<ui::Dataspace>(
743 (layerSettings.sourceDataspace & HAL_DATASPACE_STANDARD_MASK) |
744 (layerSettings.sourceDataspace & HAL_DATASPACE_RANGE_MASK) |
745 HAL_DATASPACE_TRANSFER_SRGB);
746 }
747
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700748 layerSettings.whitePointNits = targetSettings.whitePointNits;
Alec Mourif54453c2021-05-13 16:28:28 -0700749 switch (targetSettings.blurSetting) {
750 case LayerFE::ClientCompositionTargetSettings::BlurSetting::Enabled:
751 layerSettings.backgroundBlurRadius = getBackgroundBlurRadius();
752 layerSettings.blurRegions = getBlurRegions();
753 layerSettings.blurRegionTransform =
754 getActiveTransform(getDrawingState()).inverse().asMatrix4();
755 break;
756 case LayerFE::ClientCompositionTargetSettings::BlurSetting::BackgroundBlurOnly:
757 layerSettings.backgroundBlurRadius = getBackgroundBlurRadius();
758 break;
759 case LayerFE::ClientCompositionTargetSettings::BlurSetting::BlurRegionsOnly:
760 layerSettings.blurRegions = getBlurRegions();
761 layerSettings.blurRegionTransform =
762 getActiveTransform(getDrawingState()).inverse().asMatrix4();
763 break;
764 case LayerFE::ClientCompositionTargetSettings::BlurSetting::Disabled:
765 default:
766 break;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +0100767 }
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700768 layerSettings.stretchEffect = getStretchEffect();
Ana Krulec6eab17a2020-12-09 15:52:36 -0800769 // Record the name of the layer for debugging further down the stack.
770 layerSettings.name = getName();
Patrick Williamsbb25f802022-08-30 23:02:34 +0000771
772 if (hasEffect()) {
773 prepareEffectsClientComposition(layerSettings, targetSettings);
774 return layerSettings;
775 }
776
777 prepareBufferStateClientComposition(layerSettings, targetSettings);
Lloyd Piquef16688f2019-02-19 17:47:57 -0800778 return layerSettings;
Mathias Agopian13127d82013-03-05 17:47:11 -0800779}
780
Vishnu Nairb87d94f2020-02-13 09:17:36 -0800781void Layer::prepareClearClientComposition(LayerFE::LayerSettings& layerSettings,
782 bool blackout) const {
783 layerSettings.source.buffer.buffer = nullptr;
784 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
785 layerSettings.disableBlending = true;
Vishnu Nair3b653e72020-02-24 16:40:50 -0800786 layerSettings.bufferId = 0;
Vishnu Nairb87d94f2020-02-13 09:17:36 -0800787 layerSettings.frameNumber = 0;
788
789 // If layer is blacked out, force alpha to 1 so that we draw a black color layer.
790 layerSettings.alpha = blackout ? 1.0f : 0.0f;
Alec Mouribd17b3b2020-12-17 11:08:30 -0800791 layerSettings.name = getName();
Vishnu Nairb87d94f2020-02-13 09:17:36 -0800792}
793
Patrick Williamsbb25f802022-08-30 23:02:34 +0000794void Layer::prepareEffectsClientComposition(
795 compositionengine::LayerFE::LayerSettings& layerSettings,
796 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
797 // If fill bounds are occluded or the fill color is invalid skip the fill settings.
798 if (targetSettings.realContentIsVisible && fillsColor()) {
799 // Set color for color fill settings.
800 layerSettings.source.solidColor = getColor().rgb;
801 } else if (hasBlur() || drawShadows()) {
802 layerSettings.skipContentDraw = true;
803 }
804}
805
806void Layer::prepareBufferStateClientComposition(
807 compositionengine::LayerFE::LayerSettings& layerSettings,
808 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
809 if (CC_UNLIKELY(mBufferInfo.mBuffer == 0) && mSidebandStream != nullptr) {
810 // For surfaceview of tv sideband, there is no activeBuffer
811 // in bufferqueue, we need return LayerSettings.
812 return;
813 }
814 const bool blackOutLayer = (isProtected() && !targetSettings.supportsProtectedContent) ||
815 ((isSecure() || isProtected()) && !targetSettings.isSecure);
816 const bool bufferCanBeUsedAsHwTexture =
817 mBufferInfo.mBuffer->getUsage() & GraphicBuffer::USAGE_HW_TEXTURE;
818 if (blackOutLayer || !bufferCanBeUsedAsHwTexture) {
819 ALOGE_IF(!bufferCanBeUsedAsHwTexture, "%s is blacked out as buffer is not gpu readable",
820 mName.c_str());
821 prepareClearClientComposition(layerSettings, true /* blackout */);
822 return;
823 }
824
825 const State& s(getDrawingState());
826 layerSettings.source.buffer.buffer = mBufferInfo.mBuffer;
827 layerSettings.source.buffer.isOpaque = isOpaque(s);
828 layerSettings.source.buffer.fence = mBufferInfo.mFence;
829 layerSettings.source.buffer.textureName = mTextureName;
830 layerSettings.source.buffer.usePremultipliedAlpha = getPremultipledAlpha();
831 layerSettings.source.buffer.isY410BT2020 = isHdrY410();
832 bool hasSmpte2086 = mBufferInfo.mHdrMetadata.validTypes & HdrMetadata::SMPTE2086;
833 bool hasCta861_3 = mBufferInfo.mHdrMetadata.validTypes & HdrMetadata::CTA861_3;
834 float maxLuminance = 0.f;
835 if (hasSmpte2086 && hasCta861_3) {
836 maxLuminance = std::min(mBufferInfo.mHdrMetadata.smpte2086.maxLuminance,
837 mBufferInfo.mHdrMetadata.cta8613.maxContentLightLevel);
838 } else if (hasSmpte2086) {
839 maxLuminance = mBufferInfo.mHdrMetadata.smpte2086.maxLuminance;
840 } else if (hasCta861_3) {
841 maxLuminance = mBufferInfo.mHdrMetadata.cta8613.maxContentLightLevel;
842 } else {
843 switch (layerSettings.sourceDataspace & HAL_DATASPACE_TRANSFER_MASK) {
844 case HAL_DATASPACE_TRANSFER_ST2084:
845 case HAL_DATASPACE_TRANSFER_HLG:
846 // Behavior-match previous releases for HDR content
847 maxLuminance = defaultMaxLuminance;
848 break;
849 }
850 }
851 layerSettings.source.buffer.maxLuminanceNits = maxLuminance;
852 layerSettings.frameNumber = mCurrentFrameNumber;
853 layerSettings.bufferId = mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getId() : 0;
854
855 const bool useFiltering =
856 targetSettings.needsFiltering || mNeedsFiltering || bufferNeedsFiltering();
857
858 // Query the texture matrix given our current filtering mode.
859 float textureMatrix[16];
860 getDrawingTransformMatrix(useFiltering, textureMatrix);
861
862 if (getTransformToDisplayInverse()) {
863 /*
864 * the code below applies the primary display's inverse transform to
865 * the texture transform
866 */
867 uint32_t transform = DisplayDevice::getPrimaryDisplayRotationFlags();
868 mat4 tr = inverseOrientation(transform);
869
870 /**
871 * TODO(b/36727915): This is basically a hack.
872 *
873 * Ensure that regardless of the parent transformation,
874 * this buffer is always transformed from native display
875 * orientation to display orientation. For example, in the case
876 * of a camera where the buffer remains in native orientation,
877 * we want the pixels to always be upright.
878 */
879 sp<Layer> p = mDrawingParent.promote();
880 if (p != nullptr) {
881 const auto parentTransform = p->getTransform();
882 tr = tr * inverseOrientation(parentTransform.getOrientation());
883 }
884
885 // and finally apply it to the original texture matrix
886 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
887 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
888 }
889
890 const Rect win{getBounds()};
891 float bufferWidth = getBufferSize(s).getWidth();
892 float bufferHeight = getBufferSize(s).getHeight();
893
894 // BufferStateLayers can have a "buffer size" of [0, 0, -1, -1] when no display frame has
895 // been set and there is no parent layer bounds. In that case, the scale is meaningless so
896 // ignore them.
897 if (!getBufferSize(s).isValid()) {
898 bufferWidth = float(win.right) - float(win.left);
899 bufferHeight = float(win.bottom) - float(win.top);
900 }
901
902 const float scaleHeight = (float(win.bottom) - float(win.top)) / bufferHeight;
903 const float scaleWidth = (float(win.right) - float(win.left)) / bufferWidth;
904 const float translateY = float(win.top) / bufferHeight;
905 const float translateX = float(win.left) / bufferWidth;
906
907 // Flip y-coordinates because GLConsumer expects OpenGL convention.
908 mat4 tr = mat4::translate(vec4(.5f, .5f, 0.f, 1.f)) * mat4::scale(vec4(1.f, -1.f, 1.f, 1.f)) *
909 mat4::translate(vec4(-.5f, -.5f, 0.f, 1.f)) *
910 mat4::translate(vec4(translateX, translateY, 0.f, 1.f)) *
911 mat4::scale(vec4(scaleWidth, scaleHeight, 1.0f, 1.0f));
912
913 layerSettings.source.buffer.useTextureFiltering = useFiltering;
914 layerSettings.source.buffer.textureTransform =
915 mat4(static_cast<const float*>(textureMatrix)) * tr;
916
917 return;
918}
919
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500920aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
921 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700922 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800923 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500924 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800925 }
926 if (outputLayer->getState().hwc) {
927 return (*outputLayer->getState().hwc).hwcCompositionType;
928 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500929 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800930 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800931}
932
Mathias Agopian13127d82013-03-05 17:47:11 -0800933// ----------------------------------------------------------------------------
934// local state
935// ----------------------------------------------------------------------------
936
David Sodman41fdfc92017-11-06 16:09:56 -0800937bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800938 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700939 if (s.flags & layer_state_t::eLayerSecure) {
940 return true;
941 }
942
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000943 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700944 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700945}
946
Mathias Agopian13127d82013-03-05 17:47:11 -0800947// ----------------------------------------------------------------------------
948// transaction
949// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800950
Marissa Wall61c58622018-07-18 10:12:20 -0700951uint32_t Layer::doTransaction(uint32_t flags) {
952 ATRACE_CALL();
953
Robert Carr0758e5d2021-03-11 22:15:04 -0800954 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700955 mDrawingStateModified = mDrawingState.modified;
956 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700957
Alec Mourib416efd2018-09-06 21:01:59 +0000958 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700959
Robert Carr6a160312021-05-17 12:08:20 -0700960 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800961 // invalidate and recompute the visible regions if needed
962 flags |= Layer::eVisibleRegion;
963 }
964
Robert Carr6a160312021-05-17 12:08:20 -0700965 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800966 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000967 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800968 flags |= eVisibleRegion;
969 this->contentDirty = true;
970
971 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700972 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800973 }
974
Arthur Hung9ed43392022-05-27 06:31:57 +0000975 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
976 mFlinger->mUpdateInputInfo = true;
977 }
978
Robert Carr6a160312021-05-17 12:08:20 -0700979 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800980
Mathias Agopian13127d82013-03-05 17:47:11 -0800981 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800982}
983
Robert Carr6a160312021-05-17 12:08:20 -0700984void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000985 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
986 // bufferSurfaceFrameTX will be presented in latchBuffer.
987 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
988 if (surfaceFrame->getPresentState() != PresentState::Presented) {
989 // With applyPendingStates, we could end up having presented surfaceframes from previous
990 // states
991 surfaceFrame->setPresentState(PresentState::Presented);
992 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
993 }
994 }
Robert Carr6a160312021-05-17 12:08:20 -0700995 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700996}
997
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700998uint32_t Layer::clearTransactionFlags(uint32_t mask) {
999 const auto flags = mTransactionFlags & mask;
1000 mTransactionFlags &= ~mask;
1001 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -08001002}
1003
Dominik Laskowski9e168db2021-05-27 16:05:12 -07001004void Layer::setTransactionFlags(uint32_t mask) {
1005 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -08001006}
1007
Robert Carr1f0a16a2016-10-24 16:27:39 -07001008bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1009 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1010 if (idx < 0) {
1011 return false;
1012 }
1013 if (childLayer->setLayer(z)) {
1014 mCurrentChildren.removeAt(idx);
1015 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -08001016 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001017 }
Robert Carr503d2bd2017-12-04 15:49:47 -08001018 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001019}
1020
Robert Carr503c7042017-09-27 15:06:08 -07001021bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
1022 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
1023 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1024 if (idx < 0) {
1025 return false;
1026 }
1027 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
1028 mCurrentChildren.removeAt(idx);
1029 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -08001030 return true;
Robert Carr503c7042017-09-27 15:06:08 -07001031 }
Robert Carr503d2bd2017-12-04 15:49:47 -08001032 return false;
Robert Carr503c7042017-09-27 15:06:08 -07001033}
1034
Robert Carrae060832016-11-28 10:51:00 -08001035bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -07001036 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
1037 mDrawingState.sequence++;
1038 mDrawingState.z = z;
1039 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001040
Robert Carra70e91c2021-06-11 13:59:52 -07001041 mFlinger->mSomeChildrenChanged = true;
1042
Robert Carrdb66e622017-04-10 16:55:57 -07001043 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -07001044 if (mDrawingState.zOrderRelativeOf != nullptr) {
1045 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -07001046 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001047 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -07001048 }
chaviw606e5cf2019-03-01 10:12:10 -08001049 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -07001050 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001051 setTransactionFlags(eTransactionNeeded);
1052 return true;
1053}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001054
Robert Carrdb66e622017-04-10 16:55:57 -07001055void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -07001056 mDrawingState.zOrderRelatives.remove(relative);
1057 mDrawingState.sequence++;
1058 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001059 setTransactionFlags(eTransactionNeeded);
1060}
1061
1062void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -07001063 mDrawingState.zOrderRelatives.add(relative);
1064 mDrawingState.modified = true;
1065 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -07001066 setTransactionFlags(eTransactionNeeded);
1067}
1068
chaviw606e5cf2019-03-01 10:12:10 -08001069void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -07001070 mDrawingState.zOrderRelativeOf = relativeOf;
1071 mDrawingState.sequence++;
1072 mDrawingState.modified = true;
1073 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -07001074
chaviw606e5cf2019-03-01 10:12:10 -08001075 setTransactionFlags(eTransactionNeeded);
1076}
1077
Robert Carr503d2bd2017-12-04 15:49:47 -08001078bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nairf9096652021-07-20 18:49:42 -07001079 sp<Layer> relative = fromHandle(relativeToHandle).promote();
Robert Carrdb66e622017-04-10 16:55:57 -07001080 if (relative == nullptr) {
1081 return false;
1082 }
1083
Robert Carr6a160312021-05-17 12:08:20 -07001084 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
1085 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -08001086 return false;
1087 }
1088
Robert Carr88b85e12022-03-21 15:47:35 -07001089 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
1090 (relative->mDrawingState.zOrderRelativeOf == this)) {
1091 ALOGE("Detected relative layer loop between %s and %s",
1092 mName.c_str(), relative->mName.c_str());
1093 ALOGE("Ignoring new call to set relative layer");
1094 return false;
1095 }
1096
Robert Carra70e91c2021-06-11 13:59:52 -07001097 mFlinger->mSomeChildrenChanged = true;
1098
Robert Carr6a160312021-05-17 12:08:20 -07001099 mDrawingState.sequence++;
1100 mDrawingState.modified = true;
1101 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -07001102
Robert Carr6a160312021-05-17 12:08:20 -07001103 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -07001104 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001105 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -07001106 }
chaviw606e5cf2019-03-01 10:12:10 -08001107 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001108 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -07001109
1110 setTransactionFlags(eTransactionNeeded);
1111
1112 return true;
1113}
1114
Winson Chunga30f7c92021-06-29 15:42:56 -07001115bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
1116 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
1117 mDrawingState.isTrustedOverlay = isTrustedOverlay;
1118 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00001119 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -07001120 setTransactionFlags(eTransactionNeeded);
1121 return true;
1122}
1123
1124bool Layer::isTrustedOverlay() const {
1125 if (getDrawingState().isTrustedOverlay) {
1126 return true;
1127 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001128 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -07001129 return (p != nullptr) && p->isTrustedOverlay();
1130}
1131
Dan Stoza9e56aa02015-11-02 13:00:03 -08001132bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -07001133 if (mDrawingState.color.a == alpha) return false;
1134 mDrawingState.sequence++;
1135 mDrawingState.color.a = alpha;
1136 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001137 setTransactionFlags(eTransactionNeeded);
1138 return true;
1139}
chaviw13fdc492017-06-27 12:40:18 -07001140
Valerie Haudd0b7572019-01-29 14:59:27 -08001141bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -07001142 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -07001143 return false;
Valerie Hauaa194562019-02-05 16:21:38 -08001144 }
Robert Carr6a160312021-05-17 12:08:20 -07001145 mDrawingState.sequence++;
1146 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -08001147 setTransactionFlags(eTransactionNeeded);
1148
Robert Carr6a160312021-05-17 12:08:20 -07001149 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001150 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001151 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001152 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001153 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08001154 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001155 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001156
Valerie Haudd0b7572019-01-29 14:59:27 -08001157 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001158 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001159 mFlinger->mLayersAdded = true;
1160 // set up SF to handle added color layer
1161 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -07001162 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001163 }
1164 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001165 } else if (mDrawingState.bgColorLayer && alpha == 0) {
1166 mDrawingState.bgColorLayer->reparent(nullptr);
1167 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001168 return true;
1169 }
1170
Robert Carr6a160312021-05-17 12:08:20 -07001171 mDrawingState.bgColorLayer->setColor(color);
1172 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1173 mDrawingState.bgColorLayer->setAlpha(alpha);
1174 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001175
chaviw13fdc492017-06-27 12:40:18 -07001176 return true;
1177}
1178
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001179bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001180 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001181
Robert Carr6a160312021-05-17 12:08:20 -07001182 mDrawingState.sequence++;
1183 mDrawingState.cornerRadius = cornerRadius;
1184 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001185 setTransactionFlags(eTransactionNeeded);
1186 return true;
1187}
1188
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001189bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001190 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
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.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1194 mDrawingState.sequence++;
1195 }
Robert Carr6a160312021-05-17 12:08:20 -07001196 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1197 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001198 setTransactionFlags(eTransactionNeeded);
1199 return true;
1200}
Marissa Wall61c58622018-07-18 10:12:20 -07001201
Mathias Agopian13127d82013-03-05 17:47:11 -08001202bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001203 mDrawingState.sequence++;
1204 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001205 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001206 setTransactionFlags(eTransactionNeeded);
1207 return true;
1208}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001209
Lucas Dupinc3800b82020-10-02 16:24:48 -07001210bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001211 // If we start or stop drawing blur then the layer's visibility state may change so increment
1212 // the magic sequence number.
1213 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1214 mDrawingState.sequence++;
1215 }
Robert Carr6a160312021-05-17 12:08:20 -07001216 mDrawingState.blurRegions = blurRegions;
1217 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001218 setTransactionFlags(eTransactionNeeded);
1219 return true;
1220}
1221
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001222bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001223 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1224 if (mDrawingState.flags == newFlags) return false;
1225 mDrawingState.sequence++;
1226 mDrawingState.flags = newFlags;
1227 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001228 setTransactionFlags(eTransactionNeeded);
1229 return true;
1230}
Robert Carr99e27f02016-06-16 15:18:02 -07001231
chaviw25714502021-02-11 10:01:08 -08001232bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001233 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001234 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001235 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001236
Robert Carr6a160312021-05-17 12:08:20 -07001237 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001238 setTransactionFlags(eTransactionNeeded);
1239 return true;
1240}
Robert Carr8d5227b2017-03-16 15:41:03 -07001241
Evan Roskyef876c92019-01-25 17:46:06 -08001242bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001243 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1244 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001245 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001246 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001247}
1248
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001249bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001250 if (mDrawingState.layerStack == layerStack) return false;
1251 mDrawingState.sequence++;
1252 mDrawingState.layerStack = layerStack;
1253 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001254 setTransactionFlags(eTransactionNeeded);
1255 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001256}
1257
Peiyong Linc502cb72019-03-01 15:00:23 -08001258bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001259 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001260 return false;
1261 }
Robert Carr6a160312021-05-17 12:08:20 -07001262 mDrawingState.sequence++;
1263 mDrawingState.colorSpaceAgnostic = agnostic;
1264 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001265 setTransactionFlags(eTransactionNeeded);
1266 return true;
1267}
1268
Sally Qi81d95e62022-03-21 19:41:33 -07001269bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1270 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1271
1272 mDrawingState.sequence++;
1273 mDrawingState.dimmingEnabled = dimmingEnabled;
1274 mDrawingState.modified = true;
1275 setTransactionFlags(eTransactionNeeded);
1276 return true;
1277}
1278
Ana Krulecc84d09b2019-11-02 23:10:29 +01001279bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001280 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1281 mDrawingState.frameRateSelectionPriority = priority;
1282 mDrawingState.sequence++;
1283 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001284 setTransactionFlags(eTransactionNeeded);
1285 return true;
1286}
1287
1288int32_t Layer::getFrameRateSelectionPriority() const {
1289 // Check if layer has priority set.
1290 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1291 return mDrawingState.frameRateSelectionPriority;
1292 }
1293 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001294 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001295 if (parent != nullptr) {
1296 return parent->getFrameRateSelectionPriority();
1297 }
1298
1299 return Layer::PRIORITY_UNSET;
1300}
1301
Andy Labrada096227e2022-06-15 16:58:11 +00001302bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1303 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1304 mDrawingState.defaultFrameRateCompatibility = compatibility;
1305 mDrawingState.modified = true;
1306 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1307 setTransactionFlags(eTransactionNeeded);
1308 return true;
1309}
1310
1311scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1312 return mDrawingState.defaultFrameRateCompatibility;
1313}
1314
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001315bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1316 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1317};
1318
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001319ui::LayerStack Layer::getLayerStack() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001320 if (const auto parent = mDrawingParent.promote()) {
1321 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001322 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001323 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001324}
1325
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001326bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001327 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001328 return false;
1329 }
1330
Robert Carr6a160312021-05-17 12:08:20 -07001331 mDrawingState.sequence++;
1332 mDrawingState.shadowRadius = shadowRadius;
1333 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001334 setTransactionFlags(eTransactionNeeded);
1335 return true;
1336}
1337
Vishnu Nair6213bd92020-05-08 17:42:25 -07001338bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001339 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001340 return false;
1341 }
1342
Robert Carr6a160312021-05-17 12:08:20 -07001343 mDrawingState.sequence++;
1344 mDrawingState.fixedTransformHint = fixedTransformHint;
1345 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001346 setTransactionFlags(eTransactionNeeded);
1347 return true;
1348}
1349
John Reckcdb4ed72021-02-04 13:39:33 -05001350bool Layer::setStretchEffect(const StretchEffect& effect) {
1351 StretchEffect temp = effect;
1352 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001353 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001354 return false;
1355 }
Robert Carr6a160312021-05-17 12:08:20 -07001356 mDrawingState.sequence++;
1357 mDrawingState.stretchEffect = temp;
1358 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001359 setTransactionFlags(eTransactionNeeded);
1360 return true;
1361}
1362
John Reckc00c6692021-02-16 11:37:33 -05001363StretchEffect Layer::getStretchEffect() const {
1364 if (mDrawingState.stretchEffect.hasEffect()) {
1365 return mDrawingState.stretchEffect;
1366 }
1367
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001368 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001369 if (parent != nullptr) {
1370 auto effect = parent->getStretchEffect();
1371 if (effect.hasEffect()) {
1372 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1373 return effect;
1374 }
1375 }
1376 return StretchEffect{};
1377}
1378
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001379bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1380 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001381 return false;
1382 }
1383 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001384 mBorderWidth = width;
1385 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001386 return true;
1387}
1388
1389bool Layer::isBorderEnabled() {
1390 return mBorderEnabled;
1391}
1392
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001393float Layer::getBorderWidth() {
1394 return mBorderWidth;
1395}
1396
1397const half4& Layer::getBorderColor() {
1398 return mBorderColor;
1399}
1400
Ady Abrahama850c182021-08-04 13:04:37 -07001401bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1402 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1403 const auto frameRate = [&] {
1404 if (mDrawingState.frameRate.rate.isValid() ||
1405 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1406 return mDrawingState.frameRate;
1407 }
1408
1409 return parentFrameRate;
1410 }();
1411
1412 *transactionNeeded |= setFrameRateForLayerTree(frameRate);
1413
1414 // The frame rate is propagated to the children
1415 bool childrenHaveFrameRate = false;
1416 for (const sp<Layer>& child : mCurrentChildren) {
1417 childrenHaveFrameRate |=
1418 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1419 }
1420
1421 // If we don't have a valid frame rate, but the children do, we set this
1422 // layer as NoVote to allow the children to control the refresh rate
1423 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1424 childrenHaveFrameRate) {
1425 *transactionNeeded |=
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001426 setFrameRateForLayerTree(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001427 }
1428
1429 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1430 // the same reason we are allowing touch boost for those layers. See
1431 // RefreshRateConfigs::getBestRefreshRate for more details.
1432 const auto layerVotedWithDefaultCompatibility =
1433 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1434 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1435 const auto layerVotedWithExactCompatibility =
1436 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1437 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1438 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1439}
1440
Ady Abraham60e42ea2020-03-09 19:17:31 -07001441void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001442 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001443 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001444 while (auto parent = layer->getParent()) {
1445 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001446 }
Ady Abrahama850c182021-08-04 13:04:37 -07001447 return layer;
1448 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001449
Ady Abraham60e42ea2020-03-09 19:17:31 -07001450 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001451 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001452
Ady Abrahama850c182021-08-04 13:04:37 -07001453 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001454 if (transactionNeeded) {
1455 mFlinger->setTransactionFlags(eTraversalNeeded);
1456 }
1457}
1458
Ady Abraham71c437d2020-01-31 15:56:57 -08001459bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001460 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001461 return false;
1462 }
1463
Robert Carr6a160312021-05-17 12:08:20 -07001464 mDrawingState.sequence++;
1465 mDrawingState.frameRate = frameRate;
1466 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001467
1468 updateTreeHasFrameRateVote();
1469
Steven Thomas3172e202020-01-06 19:25:30 -08001470 setTransactionFlags(eTransactionNeeded);
1471 return true;
1472}
1473
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001474void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1475 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001476 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001477
1478 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1479 // there are two transactions with the same token, the first one without a buffer and the
1480 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1481 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001482 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1483 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001484 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001485 mDrawingState.bufferSurfaceFrameTX = it->second;
1486 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1487 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1488 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001489 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001490 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001491 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1492 }
1493}
1494
1495void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1496 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001497 mDrawingState.frameTimelineInfo = info;
1498 mDrawingState.postTime = postTime;
1499 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001500 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001501
Robert Carr6a160312021-05-17 12:08:20 -07001502 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001503 bufferSurfaceFrameTX != nullptr) {
1504 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1505 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1506 // being used for BufferSurfaceFrame, don't create a new one.
1507 return;
1508 }
1509 }
1510 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1511 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1512 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001513 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1514 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001515 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001516 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001517 } else {
1518 if (it->second->getPresentState() == PresentState::Presented) {
1519 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1520 // have been from previous vsync.
1521 it->second = createSurfaceFrameForTransaction(info, postTime);
1522 }
1523 }
1524}
1525
1526void Layer::addSurfaceFrameDroppedForBuffer(
1527 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001528 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001529 surfaceFrame->setPresentState(PresentState::Dropped);
1530 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1531}
1532
1533void Layer::addSurfaceFramePresentedForBuffer(
1534 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1535 nsecs_t currentLatchTime) {
1536 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1537 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1538 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1539 mLastLatchTime = currentLatchTime;
1540}
1541
1542std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1543 const FrameTimelineInfo& info, nsecs_t postTime) {
1544 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001545 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1546 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001547 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001548 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001549 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001550 // For Transactions, the post time is considered to be both queue and acquire fence time.
1551 surfaceFrame->setActualQueueTime(postTime);
1552 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001553 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1554 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001555 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001556 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001557 onSurfaceFrameCreated(surfaceFrame);
1558 return surfaceFrame;
1559}
1560
1561std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1562 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1563 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001564 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001565 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001566 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001567 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001568 // For buffers, acquire fence time will set during latch.
1569 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001570 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1571 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001572 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001573 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001574 // TODO(b/178542907): Implement onSurfaceFrameCreated for BQLayer as well.
1575 onSurfaceFrameCreated(surfaceFrame);
1576 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001577}
1578
Ady Abrahama850c182021-08-04 13:04:37 -07001579bool Layer::setFrameRateForLayerTree(FrameRate frameRate) {
1580 if (mDrawingState.frameRateForLayerTree == frameRate) {
1581 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001582 }
1583
Ady Abrahama850c182021-08-04 13:04:37 -07001584 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001585
Ady Abrahama850c182021-08-04 13:04:37 -07001586 // TODO(b/195668952): we probably don't need to dirty visible regions here
1587 // or even store frameRateForLayerTree in mDrawingState
1588 mDrawingState.sequence++;
1589 mDrawingState.modified = true;
1590 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001591
Dominik Laskowski068173d2021-08-11 17:22:59 -07001592 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
1593 mFlinger->mScheduler->recordLayerHistory(this, systemTime(), LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001594
1595 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001596}
1597
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001598Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1599 return getDrawingState().frameRateForLayerTree;
1600}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001601
Robert Carr1f0a16a2016-10-24 16:27:39 -07001602bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001603 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001604 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001605 if (parent != nullptr && parent->isHiddenByPolicy()) {
1606 return true;
1607 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001608 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1609 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1610 if (zOrderRelativeOf != nullptr) {
1611 if (zOrderRelativeOf->isHiddenByPolicy()) {
1612 return true;
1613 }
1614 }
1615 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001616 if (CC_UNLIKELY(!isTransformValid())) {
1617 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1618 return true;
1619 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001620 return s.flags & layer_state_t::eLayerHidden;
1621}
1622
David Sodman41fdfc92017-11-06 16:09:56 -08001623uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001624 // TODO: should we do something special if mSecure is set?
1625 if (mProtectedByApp) {
1626 // need a hardware-protected path to external video sink
1627 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001628 }
Riley Andrews03414a12014-07-01 14:22:59 -07001629 if (mPotentialCursor) {
1630 usage |= GraphicBuffer::USAGE_CURSOR;
1631 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001632 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001633 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001634}
1635
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001636void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1637 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1638 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001639 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001640
Vishnu Nair6213bd92020-05-08 17:42:25 -07001641 setTransformHint(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001642}
1643
Mathias Agopian13127d82013-03-05 17:47:11 -08001644// ----------------------------------------------------------------------------
1645// debugging
1646// ----------------------------------------------------------------------------
1647
Marissa Wall61c58622018-07-18 10:12:20 -07001648// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001649gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001650 using namespace std::string_literals;
1651
Huihong Luo05539a12022-02-23 10:29:40 -08001652 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001653 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001654 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001655 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001656 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001657 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001658
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001659 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001660 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001661 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001662 info.mX = ds.transform.tx();
1663 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001664 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001665 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001666 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001667 info.mFlags = ds.flags;
1668 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001669 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001670 info.mMatrix[0][0] = ds.transform[0][0];
1671 info.mMatrix[0][1] = ds.transform[0][1];
1672 info.mMatrix[1][0] = ds.transform[1][0];
1673 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001674 {
chaviwd62d3062019-09-04 14:48:02 -07001675 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001676 if (buffer != 0) {
1677 info.mActiveBufferWidth = buffer->getWidth();
1678 info.mActiveBufferHeight = buffer->getHeight();
1679 info.mActiveBufferStride = buffer->getStride();
1680 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001681 } else {
1682 info.mActiveBufferWidth = 0;
1683 info.mActiveBufferHeight = 0;
1684 info.mActiveBufferStride = 0;
1685 info.mActiveBufferFormat = 0;
1686 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001687 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001688 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001689 info.mIsOpaque = isOpaque(ds);
1690 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001691 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001692 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001693}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001694
Yiwei Zhang5434a782018-12-05 18:06:32 -08001695void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001696 result.append(kDumpTableRowLength, '-');
1697 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001698 result.append(" Layer name\n");
1699 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001700 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001701 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001702 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001703 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001704 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001705 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1706 result.append(kDumpTableRowLength, '-');
1707 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001708}
1709
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001710void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1711 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001712 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001713 return;
1714 }
1715
Yiwei Zhang5434a782018-12-05 18:06:32 -08001716 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001717 if (mName.length() > 77) {
1718 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001719 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001720 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001721 shortened.append(mName, mName.length() - 36);
1722 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001723 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001724 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001725 }
1726
Yiwei Zhang5434a782018-12-05 18:06:32 -08001727 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001728
Alec Mourib416efd2018-09-06 21:01:59 +00001729 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001730 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001731
Chia-I Wu1e043612018-03-01 09:45:09 -08001732 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001733 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001734 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001735 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001736 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001737 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001738 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001739 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1740 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001741 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001742 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001743 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001744 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001745 const auto frameRate = getFrameRateForLayerTree();
1746 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1747 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001748 ftl::enum_string(frameRate.type).c_str(),
1749 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001750 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001751 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001752 }
Dan Stozae22aec72016-08-01 13:20:59 -07001753
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001754 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1755 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1756
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001757 result.append(kDumpTableRowLength, '-');
1758 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001759}
Dan Stozae22aec72016-08-01 13:20:59 -07001760
Yiwei Zhang5434a782018-12-05 18:06:32 -08001761void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001762 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001763}
1764
Svetoslavd85084b2014-03-20 10:28:31 -07001765void Layer::clearFrameStats() {
1766 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001767}
1768
Jamie Gennis6547ff42013-07-16 20:12:42 -07001769void Layer::logFrameStats() {
1770 mFrameTracker.logAndResetStats(mName);
1771}
1772
Svetoslavd85084b2014-03-20 10:28:31 -07001773void Layer::getFrameStats(FrameStats* outStats) const {
1774 mFrameTracker.getStats(outStats);
1775}
1776
Vishnu Nair0f085c62019-08-30 08:49:12 -07001777void Layer::dumpCallingUidPid(std::string& result) const {
chaviw250bcbb2020-08-05 11:17:54 -07001778 StringAppendF(&result, "Layer %s (%s) callingPid:%d callingUid:%d ownerUid:%d\n",
1779 getName().c_str(), getType(), mCallingPid, mCallingUid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001780}
1781
Brian Anderson5ea5e592016-12-01 16:54:33 -08001782void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001783 const int32_t layerId = getSequence();
1784 mFlinger->mTimeStats->onDestroy(layerId);
1785 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001786}
1787
Chia-I Wu98f1c102017-05-30 14:54:08 -07001788size_t Layer::getChildrenCount() const {
1789 size_t count = 0;
1790 for (const sp<Layer>& child : mCurrentChildren) {
1791 count += 1 + child->getChildrenCount();
1792 }
1793 return count;
1794}
1795
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001796void Layer::setGameModeForTree(GameMode gameMode) {
1797 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001798 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1799 gameMode =
1800 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001801 }
1802 setGameMode(gameMode);
1803 for (const sp<Layer>& child : mCurrentChildren) {
1804 child->setGameModeForTree(gameMode);
1805 }
1806}
1807
Robert Carr1f0a16a2016-10-24 16:27:39 -07001808void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001809 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001810 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001811
Robert Carr1f0a16a2016-10-24 16:27:39 -07001812 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001813 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001814 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001815 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001816}
1817
1818ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001819 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001820 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001821
Robert Carr1323c952019-01-28 18:13:27 -08001822 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001823 const auto removeResult = mCurrentChildren.remove(layer);
1824
1825 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001826 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001827 layer->updateTreeHasFrameRateVote();
1828
1829 return removeResult;
1830}
1831
Robert Carr15eae092018-03-23 13:43:53 -07001832void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001833 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001834 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001835 const float parentShadowRadius =
1836 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001837 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001838 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001839 }
1840}
1841
chaviwf1961f72017-09-18 16:41:07 -07001842bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001843 sp<Layer> newParent;
1844 if (newParentHandle != nullptr) {
Vishnu Nairf9096652021-07-20 18:49:42 -07001845 newParent = fromHandle(newParentHandle).promote();
Robert Carr54cf5b12019-01-25 14:02:28 -08001846 if (newParent == nullptr) {
1847 ALOGE("Unable to promote Layer handle");
1848 return false;
1849 }
1850 if (newParent == this) {
1851 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1852 return false;
1853 }
1854 }
1855
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001856 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001857 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001858 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001859 }
1860
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001861 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001862 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001863 if (!newParent->isRemovedFromCurrentState()) {
1864 addToCurrentState();
1865 } else {
1866 onRemovedFromCurrentState();
1867 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001868 } else {
1869 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001870 }
1871
chaviw06178942017-07-27 10:25:59 -07001872 return true;
1873}
1874
Peiyong Lind3788632018-09-18 16:01:31 -07001875bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001876 static const mat4 identityMatrix = mat4();
1877
Robert Carr6a160312021-05-17 12:08:20 -07001878 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001879 return false;
1880 }
Robert Carr6a160312021-05-17 12:08:20 -07001881 ++mDrawingState.sequence;
1882 mDrawingState.colorTransform = matrix;
1883 mDrawingState.hasColorTransform = matrix != identityMatrix;
1884 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001885 setTransactionFlags(eTransactionNeeded);
1886 return true;
1887}
1888
chaviwf66724d2018-11-28 16:35:21 -08001889mat4 Layer::getColorTransform() const {
1890 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001891 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001892 colorTransform = parent->getColorTransform() * colorTransform;
1893 }
1894 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001895}
1896
1897bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001898 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001899 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001900 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1901 }
1902 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001903}
1904
Chia-I Wu11481472018-05-04 10:43:19 -07001905bool Layer::isLegacyDataSpace() const {
1906 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001907 return !(getDataSpace() &
1908 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1909 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001910}
1911
Robert Carr1f0a16a2016-10-24 16:27:39 -07001912void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001913 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001914}
1915
Robert Carr6a160312021-05-17 12:08:20 -07001916int32_t Layer::getZ(LayerVector::StateSet) const {
1917 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001918}
1919
Robert Carr1c5481e2019-07-01 14:42:27 -07001920bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001921 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001922 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001923 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001924}
1925
David Sodman41fdfc92017-11-06 16:09:56 -08001926__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001927 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001928 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1929 "makeTraversalList received invalid stateSet");
1930 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1931 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001932 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001933
Robert Carr29abff82017-12-04 13:51:20 -08001934 if (state.zOrderRelatives.size() == 0) {
1935 *outSkipRelativeZUsers = true;
1936 return children;
1937 }
1938
chaviwfd462612018-05-31 16:11:27 -07001939 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001940 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001941 sp<Layer> strongRelative = weakRelative.promote();
1942 if (strongRelative != nullptr) {
1943 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001944 }
1945 }
1946
Dan Stoza412903f2017-04-27 13:42:17 -07001947 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001948 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001949 continue;
1950 }
Robert Carrdb66e622017-04-10 16:55:57 -07001951 traverse.add(child);
1952 }
1953
1954 return traverse;
1955}
1956
Robert Carr1f0a16a2016-10-24 16:27:39 -07001957/**
Robert Carrdb66e622017-04-10 16:55:57 -07001958 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001959 */
Dan Stoza412903f2017-04-27 13:42:17 -07001960void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001961 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1962 // produce a new list for traversing, including our relatives, and not including our children
1963 // who are relatives of another surface. In the case that there are no relative Z,
1964 // makeTraversalList returns our children directly to avoid significant overhead.
1965 // However in this case we need to take the responsibility for filtering children which
1966 // are relatives of another surface here.
1967 bool skipRelativeZUsers = false;
1968 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001969
Robert Carr1f0a16a2016-10-24 16:27:39 -07001970 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001971 for (; i < list.size(); i++) {
1972 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001973 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1974 continue;
1975 }
1976
chaviw301b1d82019-11-06 13:15:09 -08001977 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001978 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001979 }
Dan Stoza412903f2017-04-27 13:42:17 -07001980 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001981 }
Robert Carr29abff82017-12-04 13:51:20 -08001982
Dan Stoza412903f2017-04-27 13:42:17 -07001983 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001984 for (; i < list.size(); i++) {
1985 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001986
Robert Carr29abff82017-12-04 13:51:20 -08001987 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1988 continue;
1989 }
Dan Stoza412903f2017-04-27 13:42:17 -07001990 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001991 }
1992}
1993
1994/**
Robert Carrdb66e622017-04-10 16:55:57 -07001995 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001996 */
Dan Stoza412903f2017-04-27 13:42:17 -07001997void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1998 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001999 // See traverseInZOrder for documentation.
2000 bool skipRelativeZUsers = false;
2001 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07002002
Robert Carr1f0a16a2016-10-24 16:27:39 -07002003 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08002004 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002005 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08002006
2007 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
2008 continue;
2009 }
2010
chaviw301b1d82019-11-06 13:15:09 -08002011 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002012 break;
2013 }
Dan Stoza412903f2017-04-27 13:42:17 -07002014 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002015 }
Dan Stoza412903f2017-04-27 13:42:17 -07002016 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08002017 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07002018 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08002019
2020 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
2021 continue;
2022 }
2023
Dan Stoza412903f2017-04-27 13:42:17 -07002024 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002025 }
2026}
2027
Edgar Arriaga844fa672020-01-16 14:21:42 -08002028void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
2029 visitor(this);
2030 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07002031 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002032 for (const sp<Layer>& child : children) {
2033 child->traverse(state, visitor);
2034 }
2035}
2036
chaviw4b129c22018-04-09 16:19:43 -07002037LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
2038 const std::vector<Layer*>& layersInTree) {
2039 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2040 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07002041 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2042 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002043 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002044
chaviwfd462612018-05-31 16:11:27 -07002045 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07002046 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2047 sp<Layer> strongRelative = weakRelative.promote();
2048 // Only add relative layers that are also descendents of the top most parent of the tree.
2049 // If a relative layer is not a descendent, then it should be ignored.
2050 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
2051 traverse.add(strongRelative);
2052 }
2053 }
2054
2055 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07002056 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002057 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
2058 // descendent of the top most parent of the tree. If it's not a descendent, then just add
2059 // the child here since it won't be added later as a relative.
2060 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
2061 childState.zOrderRelativeOf.promote().get())) {
2062 continue;
2063 }
2064 traverse.add(child);
2065 }
2066
2067 return traverse;
2068}
2069
2070void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
2071 LayerVector::StateSet stateSet,
2072 const LayerVector::Visitor& visitor) {
2073 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07002074
2075 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07002076 for (; i < list.size(); i++) {
2077 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08002078 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07002079 break;
2080 }
chaviw4b129c22018-04-09 16:19:43 -07002081 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002082 }
chaviw4b129c22018-04-09 16:19:43 -07002083
chaviwa76b2712017-09-20 12:02:26 -07002084 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07002085 for (; i < list.size(); i++) {
2086 const auto& relative = list[i];
2087 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002088 }
2089}
2090
chaviw4b129c22018-04-09 16:19:43 -07002091std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2092 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2093 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2094
2095 std::vector<Layer*> layersInTree = {this};
2096 for (size_t i = 0; i < children.size(); i++) {
2097 const auto& child = children[i];
2098 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2099 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2100 }
2101
2102 return layersInTree;
2103}
2104
2105void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2106 const LayerVector::Visitor& visitor) {
2107 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2108 std::sort(layersInTree.begin(), layersInTree.end());
2109 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2110}
2111
Peiyong Linefefaac2018-08-17 12:27:51 -07002112ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08002113 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002114}
2115
Garfield Tan2c1782c2022-02-16 15:25:05 -08002116bool Layer::isTransformValid() const {
2117 float transformDet = getTransform().det();
2118 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2119}
2120
chaviw13fdc492017-06-27 12:40:18 -07002121half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002122 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002123
chaviw13fdc492017-06-27 12:40:18 -07002124 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2125 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002126}
Robert Carr6452f122017-03-21 10:41:29 -07002127
Vishnu Nair6213bd92020-05-08 17:42:25 -07002128ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002129 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002130 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2131 return fixedTransformHint;
2132 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002133 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002134 if (!p) return fixedTransformHint;
2135 return p->getFixedTransformHint();
2136}
2137
chaviw13fdc492017-06-27 12:40:18 -07002138half4 Layer::getColor() const {
2139 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002140 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002141}
Robert Carr6452f122017-03-21 10:41:29 -07002142
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002143int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002144 if (getDrawingState().backgroundBlurRadius == 0) {
2145 return 0;
2146 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002147
Vishnu Nair29810f72022-07-01 16:38:41 +00002148 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002149 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2150 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002151}
2152
Galia Peychevae0acf382021-04-12 21:22:34 +02002153const std::vector<BlurRegion> Layer::getBlurRegions() const {
2154 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002155 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002156 for (auto& region : regionsCopy) {
2157 region.alpha = region.alpha * layerAlpha;
2158 }
2159 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002160}
2161
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002162Layer::RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002163 // Get parent settings
2164 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002165 const auto& parent = mDrawingParent.promote();
2166 if (parent != nullptr) {
2167 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002168 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002169 ui::Transform t = getActiveTransform(getDrawingState());
2170 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002171 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002172 parentSettings.radius.x *= t.getScaleX();
2173 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002174 }
2175 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002176
2177 // Get layer settings
2178 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002179 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002180 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002181 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002182
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002183 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002184 // If the parent and the layer have rounded corner settings, use the parent settings if the
2185 // parent crop is entirely inside the layer crop.
2186 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2187 if (parentSettings.cropRect.left > layerCropRect.left &&
2188 parentSettings.cropRect.top > layerCropRect.top &&
2189 parentSettings.cropRect.right < layerCropRect.right &&
2190 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2191 return parentSettings;
2192 } else {
2193 return layerSettings;
2194 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002195 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002196 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002197 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002198 return parentSettings;
2199 }
2200 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002201}
2202
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04002203void Layer::prepareShadowClientComposition(LayerFE::LayerSettings& caster,
Patrick Williams16d8b2c2022-08-08 17:29:05 +00002204 const Rect& layerStackRect) const {
Vishnu Nair08f6eae2019-11-26 14:01:39 -08002205 renderengine::ShadowSettings state = mFlinger->mDrawingState.globalShadowSettings;
2206
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04002207 // Note: this preserves existing behavior of shadowing the entire layer and not cropping it if
2208 // transparent regions are present. This may not be necessary since shadows are only cast by
2209 // SurfaceFlinger's EffectLayers, which do not typically use transparent regions.
2210 state.boundaries = mBounds;
2211
Vishnu Nair08f6eae2019-11-26 14:01:39 -08002212 // Shift the spot light x-position to the middle of the display and then
2213 // offset it by casting layer's screen pos.
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002214 state.lightPos.x = (layerStackRect.width() / 2.f) - mScreenBounds.left;
Vishnu Nair08f6eae2019-11-26 14:01:39 -08002215 state.lightPos.y -= mScreenBounds.top;
2216
2217 state.length = mEffectiveShadowRadius;
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04002218
2219 if (state.length > 0.f) {
2220 const float casterAlpha = caster.alpha;
2221 const bool casterIsOpaque =
2222 ((caster.source.buffer.buffer != nullptr) && caster.source.buffer.isOpaque);
2223
2224 // If the casting layer is translucent, we need to fill in the shadow underneath the layer.
2225 // Otherwise the generated shadow will only be shown around the casting layer.
2226 state.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
2227 state.ambientColor *= casterAlpha;
2228 state.spotColor *= casterAlpha;
2229
2230 if (state.ambientColor.a > 0.f && state.spotColor.a > 0.f) {
2231 caster.shadow = state;
2232 }
2233 }
Vishnu Nair08f6eae2019-11-26 14:01:39 -08002234}
2235
Robert Carr88b85e12022-03-21 15:47:35 -07002236bool Layer::findInHierarchy(const sp<Layer>& l) {
2237 if (l == this) {
2238 return true;
2239 }
2240 for (auto& child : mDrawingChildren) {
2241 if (child->findInHierarchy(l)) {
2242 return true;
2243 }
2244 }
2245 return false;
2246}
2247
Robert Carr1f0a16a2016-10-24 16:27:39 -07002248void Layer::commitChildList() {
2249 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2250 const auto& child = mCurrentChildren[i];
2251 child->commitChildList();
2252 }
2253 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002254 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002255 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2256 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2257 if (zOrderRelativeOf == nullptr) return;
2258 if (findInHierarchy(zOrderRelativeOf)) {
2259 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2260 zOrderRelativeOf->mName.c_str());
2261 ALOGE("Severing rel Z loop, potentially dangerous");
2262 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002263 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002264 }
2265 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002266}
2267
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002268
chaviw3277faf2021-05-19 16:45:23 -05002269void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002270 mDrawingState.inputInfo = info;
Vishnu Nairf9096652021-07-20 18:49:42 -07002271 mDrawingState.touchableRegionCrop = fromHandle(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002272 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002273 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002274 setTransactionFlags(eTransactionNeeded);
2275}
2276
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002277LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002278 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002279 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002280 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2281
Vishnu Nair00b90132021-11-05 14:03:40 -07002282 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002283 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2284
Vishnu Nair60db8c02020-04-02 11:55:16 -07002285 // Only populate for the primary display.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002286 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -05002287 const auto compositionType = getCompositionType(*display);
Vishnu Nair60db8c02020-04-02 11:55:16 -07002288 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002289 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2290 [&]() { return layerProto->mutable_visible_region(); });
Vishnu Nair60db8c02020-04-02 11:55:16 -07002291 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08002292 }
2293
chaviw08f3cb22020-01-13 13:17:21 -08002294 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002295 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002296 }
chaviw6d89e2d2020-01-14 14:42:01 -08002297
2298 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002299}
2300
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002301void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002302 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002303 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002304 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002305 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002306 [&]() { return layerInfo->mutable_active_buffer(); });
2307 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2308 layerInfo->mutable_buffer_transform());
2309 }
2310 layerInfo->set_invalidate(contentDirty);
2311 layerInfo->set_is_protected(isProtected());
2312 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2313 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002314 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002315 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002316 layerInfo->set_corner_radius(
2317 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002318 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2319 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2320 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2321 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2322 [&]() { return layerInfo->mutable_position(); });
2323 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002324 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2325 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002326
Vishnu Nair00b90132021-11-05 14:03:40 -07002327 if (hasColorTransform()) {
2328 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002329 }
2330
Vishnu Nair60db8c02020-04-02 11:55:16 -07002331 LayerProtoHelper::writeToProto(mSourceBounds,
2332 [&]() { return layerInfo->mutable_source_bounds(); });
2333 LayerProtoHelper::writeToProto(mScreenBounds,
2334 [&]() { return layerInfo->mutable_screen_bounds(); });
2335 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2336 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2337 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002338}
2339
2340void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002341 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002342 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2343 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002344 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002345
chaviw766c9c52021-02-10 17:36:47 -08002346 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002347
Vishnu Nair00b90132021-11-05 14:03:40 -07002348 layerInfo->set_id(sequence);
2349 layerInfo->set_name(getName().c_str());
2350 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002351
Vishnu Nair00b90132021-11-05 14:03:40 -07002352 for (const auto& child : children) {
2353 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002354 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002355
Vishnu Nair00b90132021-11-05 14:03:40 -07002356 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2357 sp<Layer> strongRelative = weakRelative.promote();
2358 if (strongRelative != nullptr) {
2359 layerInfo->add_relatives(strongRelative->sequence);
2360 }
2361 }
2362
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002363 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002364 [&]() { return layerInfo->mutable_transparent_region(); });
2365
2366 layerInfo->set_layer_stack(getLayerStack().id);
2367 layerInfo->set_z(state.z);
2368
2369 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2370 return layerInfo->mutable_requested_position();
2371 });
2372
Vishnu Nair00b90132021-11-05 14:03:40 -07002373 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2374
2375 layerInfo->set_is_opaque(isOpaque(state));
2376
2377 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2378 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2379 LayerProtoHelper::writeToProto(state.color,
2380 [&]() { return layerInfo->mutable_requested_color(); });
2381 layerInfo->set_flags(state.flags);
2382
2383 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2384 layerInfo->mutable_requested_transform());
2385
2386 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2387 if (parent != nullptr) {
2388 layerInfo->set_parent(parent->sequence);
2389 } else {
2390 layerInfo->set_parent(-1);
2391 }
2392
2393 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2394 if (zOrderRelativeOf != nullptr) {
2395 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2396 } else {
2397 layerInfo->set_z_order_relative_of(-1);
2398 }
2399
2400 layerInfo->set_is_relative_of(state.isRelativeOf);
2401
2402 layerInfo->set_owner_uid(mOwnerUid);
2403
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002404 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002405 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002406 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002407 info = fillInputInfo(
2408 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002409 } else {
2410 info = state.inputInfo;
2411 }
2412
2413 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002414 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002415 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002416
Vishnu Nair00b90132021-11-05 14:03:40 -07002417 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002418 auto protoMap = layerInfo->mutable_metadata();
2419 for (const auto& entry : state.metadata.mMap) {
2420 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2421 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002422 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002423
2424 LayerProtoHelper::writeToProto(state.destinationFrame,
2425 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002426}
2427
Robert Carr2e102c92018-10-23 12:11:15 -07002428bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002429 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002430}
2431
Prabir Pradhan33da9462022-06-14 14:55:57 +00002432// Applies the given transform to the region, while protecting against overflows caused by any
2433// offsets. If applying the offset in the transform to any of the Rects in the region would result
2434// in an overflow, they are not added to the output Region.
2435static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2436 const std::string& debugWindowName) {
2437 // Round the translation using the same rounding strategy used by ui::Transform.
2438 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2439 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2440
2441 ui::Transform transformWithoutOffset = t;
2442 transformWithoutOffset.set(0.f, 0.f);
2443
2444 const Region transformed = transformWithoutOffset.transform(r);
2445
2446 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2447 Region ret;
2448 for (const auto& rect : transformed) {
2449 Rect newRect;
2450 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2451 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2452 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2453 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2454 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2455 debugWindowName.c_str());
2456 continue;
2457 }
2458 ret.orSelf(newRect);
2459 }
2460 return ret;
2461}
2462
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002463void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
2464 Rect tmpBounds = getInputBounds();
2465 if (!tmpBounds.isValid()) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002466 info.touchableRegion.clear();
2467 // A layer could have invalid input bounds and still expect to receive touch input if it has
2468 // replaceTouchableRegionWithCrop. For that case, the input transform needs to be calculated
2469 // correctly to determine the coordinate space for input events. Use an empty rect so that
2470 // the layer will receive input in its own layer space.
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002471 tmpBounds = Rect::EMPTY_RECT;
chaviw7e72caf2020-12-02 16:50:43 -08002472 }
2473
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002474 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2475 // frame and transform used for the layer, which determines the bounds and the coordinate space
2476 // within which the layer will receive input.
2477 //
2478 // The coordinate space within which each of the bounds are specified is explicitly documented
2479 // in the variable name. For example "inputBoundsInLayer" is specified in layer space. A
2480 // Transform converts one coordinate space to another, which is apparent in its naming. For
2481 // example, "layerToDisplay" transforms layer space to display space.
2482 //
2483 // Coordinate space definitions:
2484 // - display: The display device's coordinate space. Correlates to pixels on the display.
2485 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2486 // - layer: The coordinate space of this layer.
2487 // - input: The coordinate space in which this layer will receive input events. This could be
2488 // different than layer space if a surfaceInset is used, which changes the origin
2489 // of the input space.
2490 const FloatRect inputBoundsInLayer = tmpBounds.toFloatRect();
chaviw7e72caf2020-12-02 16:50:43 -08002491
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002492 // Clamp surface inset to the input bounds.
2493 const auto surfaceInset = static_cast<float>(info.surfaceInset);
2494 const float xSurfaceInset =
2495 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getWidth() / 2.f));
2496 const float ySurfaceInset =
2497 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getHeight() / 2.f));
chaviw1ff3d1e2020-07-01 15:53:47 -07002498
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002499 // Apply the insets to the input bounds.
2500 const FloatRect insetBoundsInLayer(inputBoundsInLayer.left + xSurfaceInset,
2501 inputBoundsInLayer.top + ySurfaceInset,
2502 inputBoundsInLayer.right - xSurfaceInset,
2503 inputBoundsInLayer.bottom - ySurfaceInset);
Ady Abraham282f1d72019-07-24 18:05:56 -07002504
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002505 // Crop the input bounds to ensure it is within the parent's bounds.
2506 const FloatRect croppedInsetBoundsInLayer = mBounds.intersect(insetBoundsInLayer);
Ady Abraham282f1d72019-07-24 18:05:56 -07002507
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002508 const ui::Transform layerToScreen = getInputTransform();
2509 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
Vishnu Nair8033a492018-12-05 07:27:23 -08002510
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002511 const Rect roundedFrameInDisplay{layerToDisplay.transform(croppedInsetBoundsInLayer)};
2512 info.frameLeft = roundedFrameInDisplay.left;
2513 info.frameTop = roundedFrameInDisplay.top;
2514 info.frameRight = roundedFrameInDisplay.right;
2515 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002516
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002517 ui::Transform inputToLayer;
2518 inputToLayer.set(insetBoundsInLayer.left, insetBoundsInLayer.top);
2519 const ui::Transform inputToDisplay = layerToDisplay * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002520
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002521 // InputDispatcher expects a display-to-input transform.
2522 info.transform = inputToDisplay.inverse();
2523
2524 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002525 info.touchableRegion =
2526 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002527}
2528
chaviw3277faf2021-05-19 16:45:23 -05002529void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002530 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002531 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002532 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002533 }
2534 if (p != nullptr) {
2535 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2536 }
2537}
2538
Vishnu Naira066d902021-09-13 18:40:17 -07002539gui::DropInputMode Layer::getDropInputMode() const {
2540 gui::DropInputMode mode = mDrawingState.dropInputMode;
2541 if (mode == gui::DropInputMode::ALL) {
2542 return mode;
2543 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002544 sp<Layer> parent = mDrawingParent.promote();
2545 if (parent) {
2546 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002547 if (parentMode != gui::DropInputMode::NONE) {
2548 return parentMode;
2549 }
2550 }
2551 return mode;
2552}
2553
2554void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002555 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002556 return;
2557 }
2558
2559 // Check if we need to drop input unconditionally
2560 gui::DropInputMode dropInputMode = getDropInputMode();
2561 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002562 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002563 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2564 return;
2565 }
2566
2567 // Check if we need to check if the window is obscured by parent
2568 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2569 return;
2570 }
2571
2572 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002573 sp<Layer> parent = mDrawingParent.promote();
2574 if (parent && parent->getAlpha() != 1.0_hf) {
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 alpha=%f", getDebugName(),
2577 static_cast<float>(getAlpha()));
2578 }
2579
2580 // Check if the parent has cropped the buffer
2581 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2582 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002583 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002584 return;
2585 }
2586
2587 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2588 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2589 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2590 // match then the layer has not been cropped by its parents.
2591 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2592 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2593
2594 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002595 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002596 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2597 getDebugName());
2598 } else {
2599 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2600 // input if the window is obscured. This check should be done in surfaceflinger but the
2601 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2602 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002603 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002604 }
2605}
2606
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002607WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002608 if (!hasInputInfo()) {
2609 mDrawingState.inputInfo.name = getName();
2610 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2611 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002612 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002613 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002614 }
2615
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002616 const ui::Transform& displayTransform =
2617 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2618
chaviw3277faf2021-05-19 16:45:23 -05002619 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002620 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002621 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002622
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002623 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002624
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002625 if (displayArgs.transform == nullptr) {
2626 // Do not let the window receive touches if it is not associated with a valid display
2627 // transform. We still allow the window to receive keys and prevent ANRs.
2628 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2629 }
2630
Robert Carr5dc426e2020-06-10 14:29:14 -07002631 // For compatibility reasons we let layers which can receive input
2632 // receive input before they have actually submitted a buffer. Because
2633 // of this we use canReceiveInput instead of isVisible to check the
2634 // policy-visibility, ignoring the buffer state. However for layers with
2635 // hasInputInfo()==false we can use the real visibility state.
2636 // We are just using these layers for occlusion detection in
2637 // InputDispatcher, and obviously if they aren't visible they can't occlude
2638 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002639 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2640 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2641
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002642 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002643 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002644 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002645
Vishnu Nair16a938f2021-09-24 07:14:54 -07002646 // If the window will be blacked out on a display because the display does not have the secure
2647 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002648 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002649 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002650 }
2651
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002652 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2653 if (info.replaceTouchableRegionWithCrop) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002654 const Rect bounds(cropLayer ? cropLayer->mScreenBounds : mScreenBounds);
2655 info.touchableRegion = Region(displayTransform.transform(bounds));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002656 } else if (cropLayer != nullptr) {
[1;3C2b9fc252021-02-04 16:16:50 -08002657 info.touchableRegion = info.touchableRegion.intersect(
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002658 displayTransform.transform(Rect{cropLayer->mScreenBounds}));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002659 }
2660
Winson Chunga30f7c92021-06-29 15:42:56 -07002661 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2662 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002663 if (isTrustedOverlay()) {
2664 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2665 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002666
chaviwaf87b3e2019-10-01 16:59:28 -07002667 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2668 // touches from going outside the cloned area.
2669 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002670 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002671 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2672 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002673 info.touchableRegion = info.touchableRegion.intersect(rect);
2674 }
2675 }
2676
Robert Carr720e5062018-07-30 17:45:14 -07002677 return info;
2678}
2679
chaviwaf87b3e2019-10-01 16:59:28 -07002680sp<Layer> Layer::getClonedRoot() {
2681 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002682 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002683 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002684 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002685 return nullptr;
2686 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002687 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002688}
2689
Robert Carredd13602020-04-13 17:24:34 -07002690bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002691 return mDrawingState.inputInfo.token != nullptr ||
2692 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002693}
2694
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002695compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002696 const DisplayDevice* display) const {
2697 if (!display) return nullptr;
Lloyd Piquede196652020-01-22 17:29:58 -08002698 return display->getCompositionDisplay()->getOutputLayerForLayer(getCompositionEngineLayerFE());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002699}
2700
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002701Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2702 const auto outputLayer = findOutputLayerForDisplay(display);
2703 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002704}
2705
chaviwb4c6e582019-08-16 14:35:07 -07002706void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002707 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002708 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002709 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2710 mPotentialCursor = clonedFrom->mPotentialCursor;
2711 mProtectedByApp = clonedFrom->mProtectedByApp;
2712 updateCloneBufferInfo();
2713}
2714
2715void Layer::updateCloneBufferInfo() {
2716 if (!isClone() || !isClonedFromAlive()) {
2717 return;
2718 }
2719
2720 sp<Layer> clonedFrom = getClonedFrom();
2721 mBufferInfo = clonedFrom->mBufferInfo;
2722 mSidebandStream = clonedFrom->mSidebandStream;
2723 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2724 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2725 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2726
2727 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2728 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2729 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2730 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2731 // the cloned drawingState again.
2732 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2733 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2734 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2735 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2736
2737 cloneDrawingState(clonedFrom.get());
2738
2739 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2740 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2741 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2742 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002743}
chaviw74b03172019-08-19 11:09:03 -07002744
2745void Layer::updateMirrorInfo() {
2746 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2747 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2748 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2749 // that case, we want to delete the reference to the clone since we want it to get
2750 // destroyed. The root, this layer, will still be around since the client can continue
2751 // to hold a reference, but no cloned layers will be displayed.
2752 mClonedChild = nullptr;
2753 return;
2754 }
2755
2756 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2757 // If the real layer exists and is in current state, add the clone as a child of the root.
2758 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2759 // copied to drawingState for the root layer. So the clonedChild is always removed from
2760 // drawingState and then needs to be added back each traversal.
2761 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2762 addChildToDrawing(mClonedChild);
2763 }
2764
2765 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002766 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002767 mClonedChild->updateClonedRelatives(clonedLayersMap);
2768}
2769
2770void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2771 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2772 // to the clone. If the real layer is no longer alive, continue traversing the children
2773 // since we may be able to pull out other children that are still alive.
2774 if (isClonedFromAlive()) {
2775 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002776 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002777 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002778 }
2779
2780 // The clone layer may have children in drawingState since they may have been created and
2781 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2782 // that already exist, since we can just re-use them.
2783 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2784 // not updated in the regular traversal. They are skipped since the root will lose the
2785 // reference to them when it copies its currentChildren to drawing.
2786 for (sp<Layer>& child : mDrawingChildren) {
2787 child->updateClonedDrawingState(clonedLayersMap);
2788 }
2789}
2790
2791void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2792 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2793 mDrawingChildren.clear();
2794
2795 if (!isClonedFromAlive()) {
2796 return;
2797 }
2798
2799 sp<Layer> clonedFrom = getClonedFrom();
2800 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2801 if (child == mirrorRoot) {
2802 // This is to avoid cyclical mirroring.
2803 continue;
2804 }
2805 sp<Layer> clonedChild = clonedLayersMap[child];
2806 if (clonedChild == nullptr) {
2807 clonedChild = child->createClone();
2808 clonedLayersMap[child] = clonedChild;
2809 }
2810 addChildToDrawing(clonedChild);
2811 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2812 }
2813}
2814
chaviwaf87b3e2019-10-01 16:59:28 -07002815void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2816 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2817 if (cropLayer != nullptr) {
2818 if (clonedLayersMap.count(cropLayer) == 0) {
2819 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2820 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002821 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002822 } else {
2823 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2824 mDrawingState.touchableRegionCrop = clonedCropLayer;
2825 }
2826 }
2827 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2828 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002829 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002830}
2831
2832void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002833 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002834 mDrawingState.zOrderRelatives.clear();
2835
2836 if (!isClonedFromAlive()) {
2837 return;
2838 }
2839
chaviwaf87b3e2019-10-01 16:59:28 -07002840 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002841 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002842 const sp<Layer>& relative = relativeWeak.promote();
2843 if (clonedLayersMap.count(relative) > 0) {
2844 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002845 mDrawingState.zOrderRelatives.add(clonedRelative);
2846 }
2847 }
2848
2849 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2850 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2851 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2852 // still traverse the children, but the layer with the missing relativeOf will not be shown
2853 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002854 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2855 if (clonedLayersMap.count(relativeOf) > 0) {
2856 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002857 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2858 }
2859
chaviwaf87b3e2019-10-01 16:59:28 -07002860 updateClonedInputInfo(clonedLayersMap);
2861
chaviw74b03172019-08-19 11:09:03 -07002862 for (sp<Layer>& child : mDrawingChildren) {
2863 child->updateClonedRelatives(clonedLayersMap);
2864 }
2865}
2866
2867void Layer::addChildToDrawing(const sp<Layer>& layer) {
2868 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002869 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002870}
2871
Steven Thomas62a4cf82020-01-31 12:04:03 -08002872Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2873 switch (compatibility) {
2874 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2875 return FrameRateCompatibility::Default;
2876 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2877 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002878 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2879 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002880 case ANATIVEWINDOW_FRAME_RATE_MIN:
2881 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002882 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2883 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002884 default:
2885 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2886 return FrameRateCompatibility::Default;
2887 }
2888}
2889
Marin Shalamanovc5986772021-03-16 16:09:49 +01002890scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2891 switch (strategy) {
2892 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2893 return Seamlessness::OnlySeamless;
2894 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2895 return Seamlessness::SeamedAndSeamless;
2896 default:
2897 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2898 return Seamlessness::Default;
2899 }
2900}
2901
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002902bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002903 const State& s(mDrawingState);
2904 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2905 return true;
2906 }
2907
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002908 sp<Layer> parent = mDrawingParent.promote();
2909 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002910}
2911
Robert Carr6a0382d2021-07-01 15:57:17 -07002912void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2913 mClonedChild = clonedChild;
2914 mHadClonedChild = true;
2915 mFlinger->mNumClones++;
2916}
2917
Vishnu Nairf9096652021-07-20 18:49:42 -07002918const String16 Layer::Handle::kDescriptor = String16("android.Layer.Handle");
2919
2920wp<Layer> Layer::fromHandle(const sp<IBinder>& handleBinder) {
2921 if (handleBinder == nullptr) {
2922 return nullptr;
2923 }
2924
2925 BBinder* b = handleBinder->localBinder();
2926 if (b == nullptr || b->getInterfaceDescriptor() != Handle::kDescriptor) {
2927 return nullptr;
2928 }
2929
2930 // We can safely cast this binder since its local and we verified its interface descriptor.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002931 sp<Handle> handle = sp<Handle>::cast(handleBinder);
Vishnu Nairf9096652021-07-20 18:49:42 -07002932 return handle->owner;
2933}
2934
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002935bool Layer::setDropInputMode(gui::DropInputMode mode) {
2936 if (mDrawingState.dropInputMode == mode) {
2937 return false;
2938 }
2939 mDrawingState.dropInputMode = mode;
2940 return true;
2941}
2942
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002943void Layer::cloneDrawingState(const Layer* from) {
2944 mDrawingState = from->mDrawingState;
2945 // Skip callback info since they are not applicable for cloned layers.
2946 mDrawingState.releaseBufferListener = nullptr;
2947 mDrawingState.callbackHandles = {};
2948}
2949
Patrick Williamsbb25f802022-08-30 23:02:34 +00002950void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2951 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
2952 const sp<Fence>& releaseFence,
2953 uint32_t currentMaxAcquiredBufferCount) {
2954 if (!listener) {
2955 return;
2956 }
2957 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
2958 listener->onReleaseBuffer({buffer->getId(), framenumber},
2959 releaseFence ? releaseFence : Fence::NO_FENCE,
2960 currentMaxAcquiredBufferCount);
2961}
2962
2963void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2964 // If we are displayed on multiple displays in a single composition cycle then we would
2965 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2966 // For example we can only use it if all the displays are client comp, and we need
2967 // to merge all the client comp fences. We could do this, but for now we just
2968 // disable the optimization when a layer is composed on multiple displays.
2969 if (mClearClientCompositionFenceOnLayerDisplayed) {
2970 mLastClientCompositionFence = nullptr;
2971 } else {
2972 mClearClientCompositionFenceOnLayerDisplayed = true;
2973 }
2974
2975 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2976 // buffer that was presented on this layer. The first transaction that came in this frame that
2977 // replaced the previous buffer on this layer needs this release fence, because the fence will
2978 // let the client know when that previous buffer is removed from the screen.
2979 //
2980 // Every other transaction on this layer does not need a release fence because no other
2981 // Transactions that were set on this layer this frame are going to have their preceding buffer
2982 // removed from the display this frame.
2983 //
2984 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2985 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2986 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2987 // the previous buffer will be released this frame. The third transaction also contains a
2988 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2989 // transaction will now no longer be presented so it is released immediately and the third
2990 // transaction doesn't need a previous release fence.
2991 sp<CallbackHandle> ch;
2992 for (auto& handle : mDrawingState.callbackHandles) {
2993 if (handle->releasePreviousBuffer &&
2994 mDrawingState.releaseBufferEndpoint == handle->listener) {
2995 ch = handle;
2996 break;
2997 }
2998 }
2999
3000 // Prevent tracing the same release multiple times.
3001 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
3002 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
3003 }
3004
3005 if (ch != nullptr) {
3006 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
3007 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
3008 ch->name = mName;
3009 }
3010}
3011
3012void Layer::onSurfaceFrameCreated(
3013 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
3014 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
3015 // Too many SurfaceFrames pending classification. The front of the deque is probably not
3016 // tracked by FrameTimeline and will never be presented. This will only result in a memory
3017 // leak.
3018 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
3019 mName.c_str());
3020 std::string miniDump = mPendingJankClassifications.front()->miniDump();
3021 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
3022 mPendingJankClassifications.pop_front();
3023 }
3024 mPendingJankClassifications.emplace_back(surfaceFrame);
3025}
3026
3027void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
3028 for (const auto& handle : mDrawingState.callbackHandles) {
3029 handle->transformHint = mTransformHint;
3030 handle->dequeueReadyTime = dequeueReadyTime;
3031 handle->currentMaxAcquiredBufferCount =
3032 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
3033 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
3034 handle->previousReleaseCallbackId.framenumber);
3035 }
3036
3037 for (auto& handle : mDrawingState.callbackHandles) {
3038 if (handle->releasePreviousBuffer &&
3039 mDrawingState.releaseBufferEndpoint == handle->listener) {
3040 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
3041 break;
3042 }
3043 }
3044
3045 std::vector<JankData> jankData;
3046 jankData.reserve(mPendingJankClassifications.size());
3047 while (!mPendingJankClassifications.empty() &&
3048 mPendingJankClassifications.front()->getJankType()) {
3049 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
3050 mPendingJankClassifications.front();
3051 mPendingJankClassifications.pop_front();
3052 jankData.emplace_back(
3053 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
3054 }
3055
3056 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
3057 jankData);
3058
3059 sp<Fence> releaseFence = Fence::NO_FENCE;
3060 for (auto& handle : mDrawingState.callbackHandles) {
3061 if (handle->releasePreviousBuffer &&
3062 mDrawingState.releaseBufferEndpoint == handle->listener) {
3063 releaseFence =
3064 handle->previousReleaseFence ? handle->previousReleaseFence : Fence::NO_FENCE;
3065 break;
3066 }
3067 }
3068
3069 mDrawingState.callbackHandles = {};
3070}
3071
3072bool Layer::willPresentCurrentTransaction() const {
3073 // Returns true if the most recent Transaction applied to CurrentState will be presented.
3074 return (getSidebandStreamChanged() || getAutoRefresh() ||
3075 (mDrawingState.modified &&
3076 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
3077}
3078
3079bool Layer::setTransform(uint32_t transform) {
3080 if (mDrawingState.bufferTransform == transform) return false;
3081 mDrawingState.bufferTransform = transform;
3082 mDrawingState.modified = true;
3083 setTransactionFlags(eTransactionNeeded);
3084 return true;
3085}
3086
3087bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
3088 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
3089 mDrawingState.sequence++;
3090 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
3091 mDrawingState.modified = true;
3092 setTransactionFlags(eTransactionNeeded);
3093 return true;
3094}
3095
3096bool Layer::setBufferCrop(const Rect& bufferCrop) {
3097 if (mDrawingState.bufferCrop == bufferCrop) return false;
3098
3099 mDrawingState.sequence++;
3100 mDrawingState.bufferCrop = bufferCrop;
3101
3102 mDrawingState.modified = true;
3103 setTransactionFlags(eTransactionNeeded);
3104 return true;
3105}
3106
3107bool Layer::setDestinationFrame(const Rect& destinationFrame) {
3108 if (mDrawingState.destinationFrame == destinationFrame) return false;
3109
3110 mDrawingState.sequence++;
3111 mDrawingState.destinationFrame = destinationFrame;
3112
3113 mDrawingState.modified = true;
3114 setTransactionFlags(eTransactionNeeded);
3115 return true;
3116}
3117
3118// Translate destination frame into scale and position. If a destination frame is not set, use the
3119// provided scale and position
3120bool Layer::updateGeometry() {
3121 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
3122 mDrawingState.destinationFrame.isEmpty()) {
3123 // If destination frame is not set, use the requested transform set via
3124 // Layer::setPosition and Layer::setMatrix.
3125 return assignTransform(&mDrawingState.transform, mRequestedTransform);
3126 }
3127
3128 Rect destRect = mDrawingState.destinationFrame;
3129 int32_t destW = destRect.width();
3130 int32_t destH = destRect.height();
3131 if (destRect.left < 0) {
3132 destRect.left = 0;
3133 destRect.right = destW;
3134 }
3135 if (destRect.top < 0) {
3136 destRect.top = 0;
3137 destRect.bottom = destH;
3138 }
3139
3140 if (!mDrawingState.buffer) {
3141 ui::Transform t;
3142 t.set(destRect.left, destRect.top);
3143 return assignTransform(&mDrawingState.transform, t);
3144 }
3145
3146 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3147 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3148 // Undo any transformations on the buffer.
3149 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3150 std::swap(bufferWidth, bufferHeight);
3151 }
3152 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3153 if (mDrawingState.transformToDisplayInverse) {
3154 if (invTransform & ui::Transform::ROT_90) {
3155 std::swap(bufferWidth, bufferHeight);
3156 }
3157 }
3158
3159 float sx = destW / static_cast<float>(bufferWidth);
3160 float sy = destH / static_cast<float>(bufferHeight);
3161 ui::Transform t;
3162 t.set(sx, 0, 0, sy);
3163 t.set(destRect.left, destRect.top);
3164 return assignTransform(&mDrawingState.transform, t);
3165}
3166
3167bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3168 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3169 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3170 return false;
3171 }
3172
3173 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3174
3175 mDrawingState.sequence++;
3176 mDrawingState.modified = true;
3177 setTransactionFlags(eTransactionNeeded);
3178
3179 return true;
3180}
3181
3182bool Layer::setPosition(float x, float y) {
3183 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3184 return false;
3185 }
3186
3187 mRequestedTransform.set(x, y);
3188
3189 mDrawingState.sequence++;
3190 mDrawingState.modified = true;
3191 setTransactionFlags(eTransactionNeeded);
3192
3193 return true;
3194}
3195
3196bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3197 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3198 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
3199 const FrameTimelineInfo& info) {
3200 ATRACE_CALL();
3201
3202 if (!buffer) {
3203 return false;
3204 }
3205
3206 const bool frameNumberChanged =
3207 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3208 const uint64_t frameNumber =
3209 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
3210
3211 if (mDrawingState.buffer) {
3212 mReleasePreviousBuffer = true;
3213 if (!mBufferInfo.mBuffer ||
3214 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3215 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3216 // If mDrawingState has a buffer, and we are about to update again
3217 // before swapping to drawing state, then the first buffer will be
3218 // dropped and we should decrement the pending buffer count and
3219 // call any release buffer callbacks if set.
3220 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3221 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3222 mDrawingState.acquireFence,
3223 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
3224 mOwnerUid));
3225 decrementPendingBufferCount();
3226 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3227 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3228 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
3229 mDrawingState.bufferSurfaceFrameTX.reset();
3230 }
3231 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3232 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3233 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3234 mLastClientCompositionFence,
3235 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
3236 mOwnerUid));
3237 mLastClientCompositionFence = nullptr;
3238 }
3239 }
3240
3241 mDrawingState.frameNumber = frameNumber;
3242 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3243 mDrawingState.buffer = std::move(buffer);
3244 mDrawingState.clientCacheId = bufferData.cachedBuffer;
3245
3246 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3247 ? bufferData.acquireFence
3248 : Fence::NO_FENCE;
3249 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3250 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3251 // We latched this buffer unsiganled, so we need to pass the acquire fence
3252 // on the callback instead of just the acquire time, since it's unknown at
3253 // this point.
3254 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3255 } else {
3256 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3257 }
3258
3259 mDrawingState.modified = true;
3260 setTransactionFlags(eTransactionNeeded);
3261
3262 const int32_t layerId = getSequence();
3263 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3264 mOwnerUid, postTime, getGameMode());
3265 mDrawingState.desiredPresentTime = desiredPresentTime;
3266 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3267
3268 const nsecs_t presentTime = [&] {
3269 if (!isAutoTimestamp) return desiredPresentTime;
3270
3271 const auto prediction =
3272 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
3273 if (prediction.has_value()) return prediction->presentTime;
3274
3275 return static_cast<nsecs_t>(0);
3276 }();
3277
3278 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
3279 mFlinger->mScheduler->recordLayerHistory(this, presentTime, LayerUpdateType::Buffer);
3280
3281 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3282
3283 if (dequeueTime && *dequeueTime != 0) {
3284 const uint64_t bufferId = mDrawingState.buffer->getId();
3285 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3286 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3287 FrameTracer::FrameEvent::DEQUEUE);
3288 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3289 FrameTracer::FrameEvent::QUEUE);
3290 }
3291
3292 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3293 return true;
3294}
3295
3296bool Layer::setDataspace(ui::Dataspace dataspace) {
3297 mDrawingState.dataspaceRequested = true;
3298 if (mDrawingState.dataspace == dataspace) return false;
3299 mDrawingState.dataspace = dataspace;
3300 mDrawingState.modified = true;
3301 setTransactionFlags(eTransactionNeeded);
3302 return true;
3303}
3304
3305bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3306 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3307 mDrawingState.hdrMetadata = hdrMetadata;
3308 mDrawingState.modified = true;
3309 setTransactionFlags(eTransactionNeeded);
3310 return true;
3311}
3312
3313bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
3314 mDrawingState.surfaceDamageRegion = surfaceDamage;
3315 mDrawingState.modified = true;
3316 setTransactionFlags(eTransactionNeeded);
3317 return true;
3318}
3319
3320bool Layer::setApi(int32_t api) {
3321 if (mDrawingState.api == api) return false;
3322 mDrawingState.api = api;
3323 mDrawingState.modified = true;
3324 setTransactionFlags(eTransactionNeeded);
3325 return true;
3326}
3327
3328bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3329 if (mDrawingState.sidebandStream == sidebandStream) return false;
3330
3331 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3332 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3333 } else if (sidebandStream != nullptr) {
3334 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3335 }
3336
3337 mDrawingState.sidebandStream = sidebandStream;
3338 mDrawingState.modified = true;
3339 setTransactionFlags(eTransactionNeeded);
3340 if (!mSidebandStreamChanged.exchange(true)) {
3341 // mSidebandStreamChanged was false
3342 mFlinger->onLayerUpdate();
3343 }
3344 return true;
3345}
3346
3347bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles) {
3348 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3349 if (handles.empty()) {
3350 mReleasePreviousBuffer = false;
3351 return false;
3352 }
3353
3354 const bool willPresent = willPresentCurrentTransaction();
3355
3356 for (const auto& handle : handles) {
3357 // If this transaction set a buffer on this layer, release its previous buffer
3358 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3359
3360 // If this layer will be presented in this frame
3361 if (willPresent) {
3362 // If this transaction set an acquire fence on this layer, set its acquire time
3363 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3364 handle->frameNumber = mDrawingState.frameNumber;
3365
3366 // Store so latched time and release fence can be set
3367 mDrawingState.callbackHandles.push_back(handle);
3368
3369 } else { // If this layer will NOT need to be relatched and presented this frame
3370 // Notify the transaction completed thread this handle is done
3371 mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
3372 }
3373 }
3374
3375 mReleasePreviousBuffer = false;
3376 mCallbackHandleAcquireTimeOrFence = -1;
3377
3378 return willPresent;
3379}
3380
3381Rect Layer::getBufferSize(const State& /*s*/) const {
3382 // for buffer state layers we use the display frame size as the buffer size.
3383
3384 if (mBufferInfo.mBuffer == nullptr) {
3385 return Rect::INVALID_RECT;
3386 }
3387
3388 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3389 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3390
3391 // Undo any transformations on the buffer and return the result.
3392 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3393 std::swap(bufWidth, bufHeight);
3394 }
3395
3396 if (getTransformToDisplayInverse()) {
3397 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3398 if (invTransform & ui::Transform::ROT_90) {
3399 std::swap(bufWidth, bufHeight);
3400 }
3401 }
3402
3403 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3404}
3405
3406FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3407 if (mBufferInfo.mBuffer == nullptr) {
3408 return parentBounds;
3409 }
3410
3411 return getBufferSize(getDrawingState()).toFloatRect();
3412}
3413
3414bool Layer::fenceHasSignaled() const {
3415 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3416 return true;
3417 }
3418
3419 const bool fenceSignaled =
3420 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3421 if (!fenceSignaled) {
3422 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3423 TimeStats::LatchSkipReason::LateAcquire);
3424 }
3425
3426 return fenceSignaled;
3427}
3428
3429bool Layer::onPreComposition(nsecs_t refreshStartTime) {
3430 for (const auto& handle : mDrawingState.callbackHandles) {
3431 handle->refreshStartTime = refreshStartTime;
3432 }
3433 return hasReadyFrame();
3434}
3435
3436void Layer::setAutoRefresh(bool autoRefresh) {
3437 mDrawingState.autoRefresh = autoRefresh;
3438}
3439
3440bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3441 // We need to update the sideband stream if the layer has both a buffer and a sideband stream.
3442 editCompositionState()->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
3443
3444 if (mSidebandStreamChanged.exchange(false)) {
3445 const State& s(getDrawingState());
3446 // mSidebandStreamChanged was true
3447 mSidebandStream = s.sidebandStream;
3448 editCompositionState()->sidebandStream = mSidebandStream;
3449 if (mSidebandStream != nullptr) {
3450 setTransactionFlags(eTransactionNeeded);
3451 mFlinger->setTransactionFlags(eTraversalNeeded);
3452 }
3453 recomputeVisibleRegions = true;
3454
3455 return true;
3456 }
3457 return false;
3458}
3459
3460bool Layer::hasFrameUpdate() const {
3461 const State& c(getDrawingState());
3462 return (mDrawingStateModified || mDrawingState.modified) &&
3463 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3464}
3465
3466void Layer::updateTexImage(nsecs_t latchTime) {
3467 const State& s(getDrawingState());
3468
3469 if (!s.buffer) {
3470 if (s.bgColorLayer) {
3471 for (auto& handle : mDrawingState.callbackHandles) {
3472 handle->latchTime = latchTime;
3473 }
3474 }
3475 return;
3476 }
3477
3478 for (auto& handle : mDrawingState.callbackHandles) {
3479 if (handle->frameNumber == mDrawingState.frameNumber) {
3480 handle->latchTime = latchTime;
3481 }
3482 }
3483
3484 const int32_t layerId = getSequence();
3485 const uint64_t bufferId = mDrawingState.buffer->getId();
3486 const uint64_t frameNumber = mDrawingState.frameNumber;
3487 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3488 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3489 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3490
3491 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3492 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3493 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3494 FrameTracer::FrameEvent::LATCH);
3495
3496 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3497 if (bufferSurfaceFrame != nullptr &&
3498 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3499 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3500 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3501 // are processing the next state.
3502 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3503 mDrawingState.acquireFenceTime->getSignalTime(),
3504 latchTime);
3505 mDrawingState.bufferSurfaceFrameTX.reset();
3506 }
3507
3508 std::deque<sp<CallbackHandle>> remainingHandles;
3509 mFlinger->getTransactionCallbackInvoker()
3510 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3511 mDrawingState.callbackHandles = remainingHandles;
3512
3513 mDrawingStateModified = false;
3514}
3515
3516void Layer::gatherBufferInfo() {
3517 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3518 decrementPendingBufferCount();
3519 }
3520
3521 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3522 mBufferInfo.mBuffer = mDrawingState.buffer;
3523 mBufferInfo.mFence = mDrawingState.acquireFence;
3524 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3525 mBufferInfo.mPixelFormat =
3526 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3527 mBufferInfo.mFrameLatencyNeeded = true;
3528 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3529 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3530 mBufferInfo.mFence = mDrawingState.acquireFence;
3531 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3532 auto lastDataspace = mBufferInfo.mDataspace;
3533 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3534 if (lastDataspace != mBufferInfo.mDataspace) {
3535 mFlinger->mSomeDataspaceChanged = true;
3536 }
3537 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3538 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3539 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3540 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3541 mBufferInfo.mApi = mDrawingState.api;
3542 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
3543 mBufferInfo.mBufferSlot = mHwcSlotGenerator->getHwcCacheSlot(mDrawingState.clientCacheId);
3544}
3545
3546Rect Layer::computeBufferCrop(const State& s) {
3547 if (s.buffer && !s.bufferCrop.isEmpty()) {
3548 Rect bufferCrop;
3549 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3550 return bufferCrop;
3551 } else if (s.buffer) {
3552 return s.buffer->getBounds();
3553 } else {
3554 return s.bufferCrop;
3555 }
3556}
3557
3558sp<Layer> Layer::createClone() {
3559 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3560 args.textureName = mTextureName;
3561 sp<BufferStateLayer> layer = mFlinger->getFactory().createBufferStateLayer(args);
3562 layer->mHwcSlotGenerator = mHwcSlotGenerator;
3563 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3564 return layer;
3565}
3566
3567bool Layer::bufferNeedsFiltering() const {
3568 const State& s(getDrawingState());
3569 if (!s.buffer) {
3570 return false;
3571 }
3572
3573 int32_t bufferWidth = static_cast<int32_t>(s.buffer->getWidth());
3574 int32_t bufferHeight = static_cast<int32_t>(s.buffer->getHeight());
3575
3576 // Undo any transformations on the buffer and return the result.
3577 if (s.bufferTransform & ui::Transform::ROT_90) {
3578 std::swap(bufferWidth, bufferHeight);
3579 }
3580
3581 if (s.transformToDisplayInverse) {
3582 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3583 if (invTransform & ui::Transform::ROT_90) {
3584 std::swap(bufferWidth, bufferHeight);
3585 }
3586 }
3587
3588 const Rect layerSize{getBounds()};
3589 int32_t layerWidth = layerSize.getWidth();
3590 int32_t layerHeight = layerSize.getHeight();
3591
3592 // Align the layer orientation with the buffer before comparism
3593 if (mTransformHint & ui::Transform::ROT_90) {
3594 std::swap(layerWidth, layerHeight);
3595 }
3596
3597 return layerWidth != bufferWidth || layerHeight != bufferHeight;
3598}
3599
3600void Layer::decrementPendingBufferCount() {
3601 int32_t pendingBuffers = --mPendingBufferTransactions;
3602 tracePendingBufferCount(pendingBuffers);
3603}
3604
3605void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3606 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3607}
3608
3609/*
3610 * We don't want to send the layer's transform to input, but rather the
3611 * parent's transform. This is because Layer's transform is
3612 * information about how the buffer is placed on screen. The parent's
3613 * transform makes more sense to send since it's information about how the
3614 * layer is placed on screen. This transform is used by input to determine
3615 * how to go from screen space back to window space.
3616 */
3617ui::Transform Layer::getInputTransform() const {
3618 if (!hasBufferOrSidebandStream()) {
3619 return getTransform();
3620 }
3621 sp<Layer> parent = mDrawingParent.promote();
3622 if (parent == nullptr) {
3623 return ui::Transform();
3624 }
3625
3626 return parent->getTransform();
3627}
3628
3629/**
3630 * Similar to getInputTransform, we need to update the bounds to include the transform.
3631 * This is because bounds don't include the buffer transform, where the input assumes
3632 * that's already included.
3633 */
3634Rect Layer::getInputBounds() const {
3635 if (!hasBufferOrSidebandStream()) {
3636 return getCroppedBufferSize(getDrawingState());
3637 }
3638
3639 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
3640 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
3641 return bufferBounds;
3642 }
3643 return mDrawingState.transform.transform(bufferBounds);
3644}
3645
3646bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3647 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3648
3649 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3650 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3651 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3652 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3653 layer_state_t::eReparent;
3654
3655 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3656 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3657 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3658 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3659 layer_state_t::eInputInfoChanged;
3660
3661 if ((s.what & requiredFlags) != requiredFlags) {
3662 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3663 (s.what | requiredFlags) & ~s.what);
3664 return false;
3665 }
3666
3667 if (s.what & deniedFlags) {
3668 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3669 return false;
3670 }
3671
3672 if (s.what & allowedFlags) {
3673 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3674 }
3675
3676 if (s.what & layer_state_t::ePositionChanged) {
3677 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3678 ALOGV("%s: false [ePositionChanged changed]", __func__);
3679 return false;
3680 }
3681 }
3682
3683 if (s.what & layer_state_t::eAlphaChanged) {
3684 if (mDrawingState.color.a != s.alpha) {
3685 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3686 return false;
3687 }
3688 }
3689
3690 if (s.what & layer_state_t::eColorTransformChanged) {
3691 if (mDrawingState.colorTransform != s.colorTransform) {
3692 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3693 return false;
3694 }
3695 }
3696
3697 if (s.what & layer_state_t::eBackgroundColorChanged) {
3698 if (mDrawingState.bgColorLayer || s.bgColorAlpha != 0) {
3699 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3700 return false;
3701 }
3702 }
3703
3704 if (s.what & layer_state_t::eMatrixChanged) {
3705 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3706 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3707 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3708 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3709 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3710 return false;
3711 }
3712 }
3713
3714 if (s.what & layer_state_t::eCornerRadiusChanged) {
3715 if (mDrawingState.cornerRadius != s.cornerRadius) {
3716 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3717 return false;
3718 }
3719 }
3720
3721 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3722 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3723 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3724 return false;
3725 }
3726 }
3727
3728 if (s.what & layer_state_t::eTransformChanged) {
3729 if (mDrawingState.bufferTransform != s.transform) {
3730 ALOGV("%s: false [eTransformChanged changed]", __func__);
3731 return false;
3732 }
3733 }
3734
3735 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3736 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3737 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3738 return false;
3739 }
3740 }
3741
3742 if (s.what & layer_state_t::eCropChanged) {
3743 if (mDrawingState.crop != s.crop) {
3744 ALOGV("%s: false [eCropChanged changed]", __func__);
3745 return false;
3746 }
3747 }
3748
3749 if (s.what & layer_state_t::eDataspaceChanged) {
3750 if (mDrawingState.dataspace != s.dataspace) {
3751 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3752 return false;
3753 }
3754 }
3755
3756 if (s.what & layer_state_t::eHdrMetadataChanged) {
3757 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3758 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3759 return false;
3760 }
3761 }
3762
3763 if (s.what & layer_state_t::eSidebandStreamChanged) {
3764 if (mDrawingState.sidebandStream != s.sidebandStream) {
3765 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3766 return false;
3767 }
3768 }
3769
3770 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3771 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3772 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3773 return false;
3774 }
3775 }
3776
3777 if (s.what & layer_state_t::eShadowRadiusChanged) {
3778 if (mDrawingState.shadowRadius != s.shadowRadius) {
3779 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3780 return false;
3781 }
3782 }
3783
3784 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3785 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3786 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3787 return false;
3788 }
3789 }
3790
3791 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3792 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3793 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3794 return false;
3795 }
3796 }
3797
3798 if (s.what & layer_state_t::eStretchChanged) {
3799 StretchEffect temp = s.stretchEffect;
3800 temp.sanitize();
3801 if (mDrawingState.stretchEffect != temp) {
3802 ALOGV("%s: false [eStretchChanged changed]", __func__);
3803 return false;
3804 }
3805 }
3806
3807 if (s.what & layer_state_t::eBufferCropChanged) {
3808 if (mDrawingState.bufferCrop != s.bufferCrop) {
3809 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3810 return false;
3811 }
3812 }
3813
3814 if (s.what & layer_state_t::eDestinationFrameChanged) {
3815 if (mDrawingState.destinationFrame != s.destinationFrame) {
3816 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3817 return false;
3818 }
3819 }
3820
3821 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3822 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3823 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3824 return false;
3825 }
3826 }
3827
3828 ALOGV("%s: true", __func__);
3829 return true;
3830}
3831
3832bool Layer::isHdrY410() const {
3833 // pixel format is HDR Y410 masquerading as RGBA_1010102
3834 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3835 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3836 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3837}
3838
3839sp<compositionengine::LayerFE> Layer::getCompositionEngineLayerFE() const {
3840 // There's no need to get a CE Layer if the layer isn't going to draw anything.
3841 if (hasSomethingToDraw()) {
3842 return asLayerFE();
3843 } else {
3844 return nullptr;
3845 }
3846}
3847
3848compositionengine::LayerFECompositionState* Layer::editCompositionState() {
3849 return mCompositionState.get();
3850}
3851
3852const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
3853 return mCompositionState.get();
3854}
3855
3856void Layer::useSurfaceDamage() {
3857 if (mFlinger->mForceFullDamage) {
3858 surfaceDamageRegion = Region::INVALID_REGION;
3859 } else {
3860 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3861 }
3862}
3863
3864void Layer::useEmptyDamage() {
3865 surfaceDamageRegion.clear();
3866}
3867
3868bool Layer::isOpaque(const Layer::State& s) const {
3869 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3870 // layer's opaque flag.
3871 if (!hasSomethingToDraw()) {
3872 return false;
3873 }
3874
3875 // if the layer has the opaque flag, then we're always opaque
3876 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3877 return true;
3878 }
3879
3880 // If the buffer has no alpha channel, then we are opaque
3881 if (hasBufferOrSidebandStream() && isOpaqueFormat(getPixelFormat())) {
3882 return true;
3883 }
3884
3885 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3886 return fillsColor() && getAlpha() == 1.0_hf;
3887}
3888
3889bool Layer::canReceiveInput() const {
3890 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3891}
3892
3893bool Layer::isVisible() const {
3894 if (!hasSomethingToDraw()) {
3895 return false;
3896 }
3897
3898 if (isHiddenByPolicy()) {
3899 return false;
3900 }
3901
3902 return getAlpha() > 0.0f || hasBlur();
3903}
3904
3905void Layer::onPostComposition(const DisplayDevice* display,
3906 const std::shared_ptr<FenceTime>& glDoneFence,
3907 const std::shared_ptr<FenceTime>& presentFence,
3908 const CompositorTiming& compositorTiming) {
3909 // mFrameLatencyNeeded is true when a new frame was latched for the
3910 // composition.
3911 if (!mBufferInfo.mFrameLatencyNeeded) return;
3912
3913 for (const auto& handle : mDrawingState.callbackHandles) {
3914 handle->gpuCompositionDoneFence = glDoneFence;
3915 handle->compositorTiming = compositorTiming;
3916 }
3917
3918 // Update mFrameTracker.
3919 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3920 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3921
3922 const int32_t layerId = getSequence();
3923 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3924
3925 const auto outputLayer = findOutputLayerForDisplay(display);
3926 if (outputLayer && outputLayer->requiresClientComposition()) {
3927 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3928 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3929 clientCompositionTimestamp,
3930 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3931 // Update the SurfaceFrames in the drawing state
3932 if (mDrawingState.bufferSurfaceFrameTX) {
3933 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3934 }
3935 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3936 surfaceFrame->setGpuComposition();
3937 }
3938 }
3939
3940 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3941 if (frameReadyFence->isValid()) {
3942 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3943 } else {
3944 // There was no fence for this frame, so assume that it was ready
3945 // to be presented at the desired present time.
3946 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3947 }
3948
3949 if (display) {
3950 const Fps refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
3951 const std::optional<Fps> renderRate =
3952 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3953
3954 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3955 const auto gameMode = getGameMode();
3956
3957 if (presentFence->isValid()) {
3958 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3959 refreshRate, renderRate, vote, gameMode);
3960 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3961 presentFence,
3962 FrameTracer::FrameEvent::PRESENT_FENCE);
3963 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3964 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3965 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
3966 // The HWC doesn't support present fences, so use the refresh
3967 // timestamp instead.
3968 const nsecs_t actualPresentTime = display->getRefreshTimestamp();
3969 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3970 refreshRate, renderRate, vote, gameMode);
3971 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3972 mCurrentFrameNumber, actualPresentTime,
3973 FrameTracer::FrameEvent::PRESENT_FENCE);
3974 mFrameTracker.setActualPresentTime(actualPresentTime);
3975 }
3976 }
3977
3978 mFrameTracker.advanceFrame();
3979 mBufferInfo.mFrameLatencyNeeded = false;
3980}
3981
3982bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
3983 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3984 getDrawingState().frameNumber);
3985
3986 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3987
3988 if (refreshRequired) {
3989 return refreshRequired;
3990 }
3991
3992 // If the head buffer's acquire fence hasn't signaled yet, return and
3993 // try again later
3994 if (!fenceHasSignaled()) {
3995 ATRACE_NAME("!fenceHasSignaled()");
3996 mFlinger->onLayerUpdate();
3997 return false;
3998 }
3999
4000 updateTexImage(latchTime);
4001 if (mDrawingState.buffer == nullptr) {
4002 return false;
4003 }
4004
4005 // Capture the old state of the layer for comparisons later
4006 BufferInfo oldBufferInfo = mBufferInfo;
4007 const bool oldOpacity = isOpaque(mDrawingState);
4008 mPreviousFrameNumber = mCurrentFrameNumber;
4009 mCurrentFrameNumber = mDrawingState.frameNumber;
4010 gatherBufferInfo();
4011
4012 if (oldBufferInfo.mBuffer == nullptr) {
4013 // the first time we receive a buffer, we need to trigger a
4014 // geometry invalidation.
4015 recomputeVisibleRegions = true;
4016 }
4017
4018 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
4019 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
4020 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
4021 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
4022 recomputeVisibleRegions = true;
4023 }
4024
4025 if (oldBufferInfo.mBuffer != nullptr) {
4026 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
4027 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
4028 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
4029 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
4030 recomputeVisibleRegions = true;
4031 }
4032 }
4033
4034 if (oldOpacity != isOpaque(mDrawingState)) {
4035 recomputeVisibleRegions = true;
4036 }
4037
4038 return true;
4039}
4040
4041bool Layer::hasReadyFrame() const {
4042 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4043}
4044
4045bool Layer::isProtected() const {
4046 return (mBufferInfo.mBuffer != nullptr) &&
4047 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4048}
4049
4050// As documented in libhardware header, formats in the range
4051// 0x100 - 0x1FF are specific to the HAL implementation, and
4052// are known to have no alpha channel
4053// TODO: move definition for device-specific range into
4054// hardware.h, instead of using hard-coded values here.
4055#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
4056
4057bool Layer::isOpaqueFormat(PixelFormat format) {
4058 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
4059 return true;
4060 }
4061 switch (format) {
4062 case PIXEL_FORMAT_RGBA_8888:
4063 case PIXEL_FORMAT_BGRA_8888:
4064 case PIXEL_FORMAT_RGBA_FP16:
4065 case PIXEL_FORMAT_RGBA_1010102:
4066 case PIXEL_FORMAT_R_8:
4067 return false;
4068 }
4069 // in all other case, we have no blending (also for unknown formats)
4070 return true;
4071}
4072
4073bool Layer::needsFiltering(const DisplayDevice* display) const {
4074 if (!hasBufferOrSidebandStream()) {
4075 return false;
4076 }
4077 const auto outputLayer = findOutputLayerForDisplay(display);
4078 if (outputLayer == nullptr) {
4079 return false;
4080 }
4081
4082 // We need filtering if the sourceCrop rectangle size does not match the
4083 // displayframe rectangle size (not a 1:1 render)
4084 const auto& compositionState = outputLayer->getState();
4085 const auto displayFrame = compositionState.displayFrame;
4086 const auto sourceCrop = compositionState.sourceCrop;
4087 return sourceCrop.getHeight() != displayFrame.getHeight() ||
4088 sourceCrop.getWidth() != displayFrame.getWidth();
4089}
4090
4091bool Layer::needsFilteringForScreenshots(const DisplayDevice* display,
4092 const ui::Transform& inverseParentTransform) const {
4093 if (!hasBufferOrSidebandStream()) {
4094 return false;
4095 }
4096 const auto outputLayer = findOutputLayerForDisplay(display);
4097 if (outputLayer == nullptr) {
4098 return false;
4099 }
4100
4101 // We need filtering if the sourceCrop rectangle size does not match the
4102 // viewport rectangle size (not a 1:1 render)
4103 const auto& compositionState = outputLayer->getState();
4104 const ui::Transform& displayTransform = display->getTransform();
4105 const ui::Transform inverseTransform = inverseParentTransform * displayTransform.inverse();
4106 // Undo the transformation of the displayFrame so that we're back into
4107 // layer-stack space.
4108 const Rect frame = inverseTransform.transform(compositionState.displayFrame);
4109 const FloatRect sourceCrop = compositionState.sourceCrop;
4110
4111 int32_t frameHeight = frame.getHeight();
4112 int32_t frameWidth = frame.getWidth();
4113 // If the display transform had a rotational component then undo the
4114 // rotation so that the orientation matches the source crop.
4115 if (displayTransform.getOrientation() & ui::Transform::ROT_90) {
4116 std::swap(frameHeight, frameWidth);
4117 }
4118 return sourceCrop.getHeight() != frameHeight || sourceCrop.getWidth() != frameWidth;
4119}
4120
4121void Layer::latchAndReleaseBuffer() {
4122 if (hasReadyFrame()) {
4123 bool ignored = false;
4124 latchBuffer(ignored, systemTime());
4125 }
4126 releasePendingBuffer(systemTime());
4127}
4128
4129PixelFormat Layer::getPixelFormat() const {
4130 return mBufferInfo.mPixelFormat;
4131}
4132
4133bool Layer::getTransformToDisplayInverse() const {
4134 return mBufferInfo.mTransformToDisplayInverse;
4135}
4136
4137Rect Layer::getBufferCrop() const {
4138 // this is the crop rectangle that applies to the buffer
4139 // itself (as opposed to the window)
4140 if (!mBufferInfo.mCrop.isEmpty()) {
4141 // if the buffer crop is defined, we use that
4142 return mBufferInfo.mCrop;
4143 } else if (mBufferInfo.mBuffer != nullptr) {
4144 // otherwise we use the whole buffer
4145 return mBufferInfo.mBuffer->getBounds();
4146 } else {
4147 // if we don't have a buffer yet, we use an empty/invalid crop
4148 return Rect();
4149 }
4150}
4151
4152uint32_t Layer::getBufferTransform() const {
4153 return mBufferInfo.mTransform;
4154}
4155
4156ui::Dataspace Layer::getDataSpace() const {
4157 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
4158}
4159
4160ui::Dataspace Layer::getRequestedDataSpace() const {
4161 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4162}
4163
4164ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4165 ui::Dataspace updatedDataspace = dataspace;
4166 // translate legacy dataspaces to modern dataspaces
4167 switch (dataspace) {
4168 case ui::Dataspace::SRGB:
4169 updatedDataspace = ui::Dataspace::V0_SRGB;
4170 break;
4171 case ui::Dataspace::SRGB_LINEAR:
4172 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4173 break;
4174 case ui::Dataspace::JFIF:
4175 updatedDataspace = ui::Dataspace::V0_JFIF;
4176 break;
4177 case ui::Dataspace::BT601_625:
4178 updatedDataspace = ui::Dataspace::V0_BT601_625;
4179 break;
4180 case ui::Dataspace::BT601_525:
4181 updatedDataspace = ui::Dataspace::V0_BT601_525;
4182 break;
4183 case ui::Dataspace::BT709:
4184 updatedDataspace = ui::Dataspace::V0_BT709;
4185 break;
4186 default:
4187 break;
4188 }
4189
4190 return updatedDataspace;
4191}
4192
4193sp<GraphicBuffer> Layer::getBuffer() const {
4194 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4195}
4196
4197void Layer::getDrawingTransformMatrix(bool filteringEnabled, float outMatrix[16]) const {
4198 sp<GraphicBuffer> buffer = getBuffer();
4199 if (!buffer) {
4200 ALOGE("Buffer should not be null!");
4201 return;
4202 }
4203 GLConsumer::computeTransformMatrix(outMatrix, buffer->getWidth(), buffer->getHeight(),
4204 buffer->getPixelFormat(), mBufferInfo.mCrop,
4205 mBufferInfo.mTransform, filteringEnabled);
4206}
4207
4208void Layer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
4209 mTransformHint = getFixedTransformHint();
4210 if (mTransformHint == ui::Transform::ROT_INVALID) {
4211 mTransformHint = displayTransformHint;
4212 }
4213}
4214
4215const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4216 return mBufferInfo.mBuffer;
4217}
4218
4219bool Layer::setColor(const half3& color) {
4220 if (mDrawingState.color.r == color.r && mDrawingState.color.g == color.g &&
4221 mDrawingState.color.b == color.b) {
4222 return false;
4223 }
4224
4225 mDrawingState.sequence++;
4226 mDrawingState.color.r = color.r;
4227 mDrawingState.color.g = color.g;
4228 mDrawingState.color.b = color.b;
4229 mDrawingState.modified = true;
4230 setTransactionFlags(eTransactionNeeded);
4231 return true;
4232}
4233
4234bool Layer::fillsColor() const {
4235 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4236 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4237}
4238
4239bool Layer::hasBlur() const {
4240 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4241}
4242
Mathias Agopian13127d82013-03-05 17:47:11 -08004243// ---------------------------------------------------------------------------
4244
Marin Shalamanov46084422020-10-13 12:33:42 +02004245std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004246 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4247 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004248}
4249
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004250} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004251
4252#if defined(__gl_h_)
4253#error "don't include gl/gl.h in this file"
4254#endif
4255
4256#if defined(__gl2_h_)
4257#error "don't include gl2/gl2.h in this file"
4258#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004259
4260// TODO(b/129481165): remove the #pragma below and fix conversion issues
4261#pragma clang diagnostic pop // ignored "-Wconversion"