blob: 420fd5651f9541e2992916265880e419f14ce752 [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"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070070#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070071#include "FrameTracer/FrameTracer.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080072#include "LayerProtoHelper.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080074#include "TimeStats/TimeStats.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070075#include "TunnelModeEnabledReporter.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070076
David Sodman41fdfc92017-11-06 16:09:56 -080077#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000078#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080namespace android {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010081namespace {
82constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000083
84static constexpr float defaultMaxLuminance = 1000.0;
85
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000086const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000087
88constexpr mat4 inverseOrientation(uint32_t transform) {
89 const mat4 flipH(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
90 const mat4 flipV(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1);
91 const mat4 rot90(0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
92 mat4 tr;
93
94 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
95 tr = tr * rot90;
96 }
97 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
98 tr = tr * flipH;
99 }
100 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
101 tr = tr * flipV;
102 }
103 return inverse(tr);
104}
105
106bool assignTransform(ui::Transform* dst, ui::Transform& from) {
107 if (*dst == from) {
108 return false;
109 }
110 *dst = from;
111 return true;
112}
113
114TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
115 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
116 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
117 const auto frameRateCompatibility = [frameRate] {
118 switch (frameRate.type) {
119 case Layer::FrameRateCompatibility::Default:
120 return FrameRateCompatibility::Default;
121 case Layer::FrameRateCompatibility::ExactOrMultiple:
122 return FrameRateCompatibility::ExactOrMultiple;
123 default:
124 return FrameRateCompatibility::Undefined;
125 }
126 }();
127
128 const auto seamlessness = [frameRate] {
129 switch (frameRate.seamlessness) {
130 case scheduler::Seamlessness::OnlySeamless:
131 return Seamlessness::ShouldBeSeamless;
132 case scheduler::Seamlessness::SeamedAndSeamless:
133 return Seamlessness::NotRequired;
134 default:
135 return Seamlessness::Undefined;
136 }
137 }();
138
139 return TimeStats::SetFrameRateVote{.frameRate = frameRate.rate.getValue(),
140 .frameRateCompatibility = frameRateCompatibility,
141 .seamlessness = seamlessness};
142}
143
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100144} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800145
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700146using namespace ftl::flag_operators;
147
Yiwei Zhang5434a782018-12-05 18:06:32 -0800148using base::StringAppendF;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800149using gui::GameMode;
150using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500151using gui::WindowInfo;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800152
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700153using PresentState = frametimeline::SurfaceFrame::PresentState;
154
Lloyd Piquef1c675b2018-09-12 20:45:39 -0700155std::atomic<int32_t> Layer::sSequence{1};
Mathias Agopian13127d82013-03-05 17:47:11 -0800156
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700157Layer::Layer(const LayerCreationArgs& args)
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800158 : sequence(args.sequence.value_or(sSequence++)),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700159 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000160 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700161 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800162 mWindowType(static_cast<WindowInfo::Type>(
163 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000164 mLayerCreationFlags(args.flags),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000165 mBorderEnabled(false),
166 mTextureName(args.textureName),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000167 mHwcSlotGenerator(sp<HwcSlotGenerator>::make()) {
168 ALOGV("Creating Layer %s", getDebugName());
169
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700170 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700171 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
172 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
173 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700174 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
175 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Vishnu Naira84a2202022-01-12 20:12:55 -0800176 if (args.sequence) {
177 sSequence = *args.sequence + 1;
178 }
Robert Carr6a160312021-05-17 12:08:20 -0700179 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700180 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700181 mDrawingState.z = 0;
182 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700183 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700184 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700185 mDrawingState.transform.set(0, 0);
186 mDrawingState.frameNumber = 0;
187 mDrawingState.bufferTransform = 0;
188 mDrawingState.transformToDisplayInverse = false;
189 mDrawingState.crop.makeInvalid();
190 mDrawingState.acquireFence = sp<Fence>::make(-1);
191 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
192 mDrawingState.dataspace = ui::Dataspace::UNKNOWN;
Vishnu Nairbc4ee5c2022-08-16 03:19:37 +0000193 mDrawingState.dataspaceRequested = false;
Robert Carr6a160312021-05-17 12:08:20 -0700194 mDrawingState.hdrMetadata.validTypes = 0;
195 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
196 mDrawingState.cornerRadius = 0.0f;
197 mDrawingState.backgroundBlurRadius = 0;
198 mDrawingState.api = -1;
199 mDrawingState.hasColorTransform = false;
200 mDrawingState.colorSpaceAgnostic = false;
201 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
202 mDrawingState.metadata = args.metadata;
203 mDrawingState.shadowRadius = 0.f;
204 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
205 mDrawingState.frameTimelineInfo = {};
206 mDrawingState.postTime = -1;
207 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000208 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700209 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700210 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000211 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700212
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700213 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
214 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700215 mDrawingState.color.r = -1.0_hf;
216 mDrawingState.color.g = -1.0_hf;
217 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700218 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700219
220 mFrameTracker.setDisplayRefreshPeriod(
221 args.flinger->mScheduler->getVsyncPeriodFromRefreshRateConfigs());
Robert Carr2e102c92018-10-23 12:11:15 -0700222
Vishnu Nair0f085c62019-08-30 08:49:12 -0700223 mCallingPid = args.callingPid;
224 mCallingUid = args.callingUid;
chaviw250bcbb2020-08-05 11:17:54 -0700225
226 if (mCallingUid == AID_GRAPHICS || mCallingUid == AID_SYSTEM) {
227 // If the system didn't send an ownerUid, use the callingUid for the ownerUid.
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800228 mOwnerUid = args.metadata.getInt32(gui::METADATA_OWNER_UID, mCallingUid);
229 mOwnerPid = args.metadata.getInt32(gui::METADATA_OWNER_PID, mCallingPid);
chaviw250bcbb2020-08-05 11:17:54 -0700230 } else {
231 // A create layer request from a non system request cannot specify the owner uid
232 mOwnerUid = mCallingUid;
Adithya Srinivasan9febda82020-10-19 10:49:41 -0700233 mOwnerPid = mCallingPid;
chaviw250bcbb2020-08-05 11:17:54 -0700234 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000235
236 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
237 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
238 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
239 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000240
241 mSnapshot->sequence = sequence;
242 mSnapshot->name = getDebugName();
243 mSnapshot->textureName = mTextureName;
244 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
245 mSnapshot->transform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800246}
247
248void Layer::onFirstRef() {
249 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700250}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700251
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700252Layer::~Layer() {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000253 // The original layer and the clone layer share the same texture and buffer. Therefore, only
254 // one of the layers, in this case the original layer, needs to handle the deletion. The
255 // original layer and the clone should be removed at the same time so there shouldn't be any
256 // issue with the clone layer trying to use the texture.
257 if (mBufferInfo.mBuffer != nullptr) {
258 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
259 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
260 mBufferInfo.mFence,
261 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
262 mOwnerUid));
263 }
264 if (!isClone()) {
265 // The original layer and the clone layer share the same texture. Therefore, only one of
266 // the layers, in this case the original layer, needs to handle the deletion. The original
267 // layer and the clone should be removed at the same time so there shouldn't be any issue
268 // with the clone layer trying to use the deleted texture.
269 mFlinger->deleteTextureAsync(mTextureName);
270 }
271 const int32_t layerId = getSequence();
272 mFlinger->mTimeStats->onDestroy(layerId);
273 mFlinger->mFrameTracer->onDestroy(layerId);
274
David Sodman577c8962017-12-08 14:50:53 -0800275 sp<Client> c(mClientRef.promote());
276 if (c != 0) {
277 c->detachLayer(this);
278 }
279
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000280 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700281 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700282
283 if (mDrawingState.sidebandStream != nullptr) {
284 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
285 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700286 if (mHadClonedChild) {
287 mFlinger->mNumClones--;
288 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700289}
290
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700291LayerCreationArgs::LayerCreationArgs(SurfaceFlinger* flinger, sp<Client> client, std::string name,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800292 uint32_t flags, LayerMetadata metadata)
Vishnu Nair0f085c62019-08-30 08:49:12 -0700293 : flinger(flinger),
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700294 client(std::move(client)),
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700295 name(std::move(name)),
Vishnu Nair0f085c62019-08-30 08:49:12 -0700296 flags(flags),
297 metadata(std::move(metadata)) {
298 IPCThreadState* ipc = IPCThreadState::self();
299 callingPid = ipc->getCallingPid();
300 callingUid = ipc->getCallingUid();
301}
302
Mathias Agopian13127d82013-03-05 17:47:11 -0800303// ---------------------------------------------------------------------------
304// callbacks
305// ---------------------------------------------------------------------------
306
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700307void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700308 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700309 return;
310 }
Robert Carr2e102c92018-10-23 12:11:15 -0700311
Robert Carr6a160312021-05-17 12:08:20 -0700312 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700313 if (strongRelative == nullptr) {
314 setZOrderRelativeOf(nullptr);
315 return;
316 }
317
318 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700319 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700320 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800321 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700322 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700323}
324
325void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700326 if (!mRemovedFromDrawingState) {
327 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700328 mFlinger->mScheduler->deregisterLayer(this);
329 }
Rob Carr4bba3702018-10-08 21:53:30 +0000330
Ady Abrahamd11bade2022-08-01 16:18:03 -0700331 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700332}
Chia-I Wu38512252017-05-17 14:36:16 -0700333
chaviw68d4dab2020-06-08 15:07:32 -0700334sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000335 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700336 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700337 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700338 }
339 return parent->getRootLayer();
340}
341
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700342void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700343 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
344 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700345 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700346
347 traverse(LayerVector::StateSet::Current, [&](Layer* layer) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700348 layer->removeFromCurrentState();
349 layer->removeRelativeZ(layersInTree);
chaviw68d4dab2020-06-08 15:07:32 -0700350 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700351}
352
chaviw61626f22018-11-15 16:26:27 -0800353void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700354 if (mRemovedFromDrawingState) {
355 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700356 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700357 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700358 }
chaviw61626f22018-11-15 16:26:27 -0800359
360 for (const auto& child : mCurrentChildren) {
361 child->addToCurrentState();
362 }
363}
364
Mathias Agopian13127d82013-03-05 17:47:11 -0800365// ---------------------------------------------------------------------------
366// set-up
367// ---------------------------------------------------------------------------
368
chaviw13fdc492017-06-27 12:40:18 -0700369bool Layer::getPremultipledAlpha() const {
370 return mPremultipliedAlpha;
371}
372
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700373sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800374 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700375 if (mGetHandleCalled) {
376 ALOGE("Get handle called twice" );
377 return nullptr;
378 }
379 mGetHandleCalled = true;
Ady Abrahamd11bade2022-08-01 16:18:03 -0700380 return sp<Handle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800381}
382
383// ---------------------------------------------------------------------------
384// h/w composer set-up
385// ---------------------------------------------------------------------------
386
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700387static Rect reduce(const Rect& win, const Region& exclude) {
388 if (CC_LIKELY(exclude.isEmpty())) {
389 return win;
390 }
391 if (exclude.isRect()) {
392 return win.reduce(exclude.getBounds());
393 }
394 return Region(win).subtract(exclude).getBounds();
395}
396
Dan Stoza80d61162017-12-20 15:57:52 -0800397static FloatRect reduce(const FloatRect& win, const Region& exclude) {
398 if (CC_LIKELY(exclude.isEmpty())) {
399 return win;
400 }
401 // Convert through Rect (by rounding) for lack of FloatRegion
402 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
403}
404
Vishnu Nair4351ad52019-02-11 14:13:02 -0800405Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800406 if (!reduceTransparentRegion) {
407 return Rect{mScreenBounds};
408 }
409
410 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800411 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800412 // Transform to screen space.
413 bounds = t.transform(bounds);
414 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700415}
416
Vishnu Nair4351ad52019-02-11 14:13:02 -0800417FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000418 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800419 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700420}
421
Vishnu Nairf0c28512019-02-08 12:40:28 -0800422FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
423 // Subtract the transparent region and snap to the bounds.
424 return reduce(mBounds, activeTransparentRegion);
425}
426
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700427void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
428 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800429 const State& s(getDrawingState());
430
431 // Calculate effective layer transform
432 mEffectiveTransform = parentTransform * getActiveTransform(s);
433
Garfield Tan2c1782c2022-02-16 15:25:05 -0800434 if (CC_UNLIKELY(!isTransformValid())) {
435 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
436 getDebugName());
437 return;
438 }
439
Vishnu Nair4351ad52019-02-11 14:13:02 -0800440 // Transform parent bounds to layer space
441 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
442
Vishnu Nairc652ff82019-03-15 12:48:54 -0700443 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800444 mSourceBounds = computeSourceBounds(parentBounds);
445
446 // Calculate bounds by croping diplay frame with layer crop and parent bounds
447 FloatRect bounds = mSourceBounds;
448 const Rect layerCrop = getCrop(s);
449 if (!layerCrop.isEmpty()) {
450 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
451 }
452 bounds = bounds.intersect(parentBounds);
453
454 mBounds = bounds;
455 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700456
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700457 // Use the layer's own shadow radius if set. Otherwise get the radius from
458 // parent.
459 if (s.shadowRadius > 0.f) {
460 mEffectiveShadowRadius = s.shadowRadius;
461 } else {
462 mEffectiveShadowRadius = parentShadowRadius;
463 }
464
465 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
466 // don't pass it to its children.
467 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
468
Vishnu Nair4351ad52019-02-11 14:13:02 -0800469 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700470 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800471 }
Vishnu Nairba354102022-08-01 00:14:18 +0000472
473 if (mPotentialCursor) {
474 prepareCursorCompositionState();
475 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800476}
477
Vishnu Nair60356342018-11-13 13:00:45 -0800478Rect Layer::getCroppedBufferSize(const State& s) const {
479 Rect size = getBufferSize(s);
480 Rect crop = getCrop(s);
481 if (!crop.isEmpty() && size.isValid()) {
482 size.intersect(crop, &size);
483 } else if (!crop.isEmpty()) {
484 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700485 }
Vishnu Nair60356342018-11-13 13:00:45 -0800486 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800487}
488
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700489void Layer::setupRoundedCornersCropCoordinates(Rect win,
490 const FloatRect& roundedCornersCrop) const {
491 // Translate win by the rounded corners rect coordinates, to have all values in
492 // layer coordinate space.
493 win.left -= roundedCornersCrop.left;
494 win.right -= roundedCornersCrop.left;
495 win.top -= roundedCornersCrop.top;
496 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700497}
498
Lloyd Piquede196652020-01-22 17:29:58 -0800499void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800500 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800501 const auto alpha = static_cast<float>(getAlpha());
502 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700503 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800504
505 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
506 if (!opaque || alpha != 1.0f) {
507 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
508 : Hwc2::IComposerClient::BlendMode::COVERAGE;
509 }
510
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000511 auto* snapshot = editLayerSnapshot();
512 snapshot->outputFilter = getOutputFilter();
513 snapshot->isVisible = isVisible();
514 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
515 snapshot->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800516
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000517 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800518 contentDirty = false;
519
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000520 snapshot->geomLayerBounds = mBounds;
521 snapshot->geomLayerTransform = getTransform();
522 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
523 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Lloyd Piquec6687342019-03-07 21:34:57 -0800524
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000525 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
526 snapshot->alpha = alpha;
527 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
528 snapshot->blurRegions = drawingState.blurRegions;
529 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800530}
531
Lloyd Piquede196652020-01-22 17:29:58 -0800532void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800533 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000534 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700535
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000536 snapshot->geomBufferSize = getBufferSize(drawingState);
537 snapshot->geomContentCrop = getBufferCrop();
538 snapshot->geomCrop = getCrop(drawingState);
539 snapshot->geomBufferTransform = getBufferTransform();
540 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
541 snapshot->geomUsesSourceCrop = usesSourceCrop();
542 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800543
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000544 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800545 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
546 for (const auto& [key, mandatory] : supportedMetadata) {
547 const auto& genericLayerMetadataCompatibilityMap =
548 mFlinger->getGenericLayerMetadataKeyMap();
549 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
550 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
551 continue;
552 }
553 const uint32_t id = compatIter->second;
554
555 auto it = drawingState.metadata.mMap.find(id);
556 if (it == std::end(drawingState.metadata.mMap)) {
557 continue;
558 }
559
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000560 snapshot->metadata.emplace(key,
561 compositionengine::GenericLayerMetadataEntry{mandatory,
562 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800563 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800564}
David Sodmanba340492018-08-05 21:51:33 -0700565
Lloyd Piquede196652020-01-22 17:29:58 -0800566void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800567 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000568 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800569
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000570 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800571
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000572 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
573 snapshot->dataspace = getDataSpace();
574 snapshot->colorTransform = getColorTransform();
575 snapshot->colorTransformIsIdentity = !hasColorTransform();
576 snapshot->surfaceDamage = surfaceDamageRegion;
577 snapshot->hasProtectedContent = isProtected();
578 snapshot->dimmingEnabled = isDimmingEnabled();
Lloyd Pique688abd42019-02-15 15:42:24 -0800579
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700580 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700581
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000582 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800583
584 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400585 // Rounded corners no longer force client composition, since we may use a
586 // hole punch so that the layer will appear to have rounded corners.
587 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000588 snapshot->stretchEffect.hasEffect()) {
589 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800590 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700591 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000592 snapshot->blurRegions = drawingState.blurRegions;
593 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400594
595 // Layer framerate is used in caching decisions.
596 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
597 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000598 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000599
600 if (hasBufferOrSidebandStream()) {
601 preparePerFrameBufferCompositionState();
602 } else {
603 preparePerFrameEffectsCompositionState();
604 }
605}
606
607void Layer::preparePerFrameBufferCompositionState() {
608 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000609 auto* snapshot = editLayerSnapshot();
610 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
611 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000612 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
613 return;
614 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000615 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000616 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
617 } else {
618 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000619 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
620 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000621 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
622 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
623 }
624
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000625 snapshot->buffer = getBuffer();
626 snapshot->bufferSlot = (mBufferInfo.mBufferSlot == BufferQueue::INVALID_BUFFER_SLOT)
Patrick Williamsbb25f802022-08-30 23:02:34 +0000627 ? 0
628 : mBufferInfo.mBufferSlot;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000629 snapshot->acquireFence = mBufferInfo.mFence;
630 snapshot->frameNumber = mBufferInfo.mFrameNumber;
631 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000632}
633
634void Layer::preparePerFrameEffectsCompositionState() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000635 auto* snapshot = editLayerSnapshot();
636 snapshot->color = getColor();
637 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000638 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800639}
640
Lloyd Piquede196652020-01-22 17:29:58 -0800641void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800642 const State& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000643 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800644
645 // Apply the layer's transform, followed by the display's global transform
646 // Here we're guaranteed that the layer's transform preserves rects
647 Rect win = getCroppedBufferSize(drawingState);
648 // Subtract the transparent region and snap to the bounds
649 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
650 Rect frame(getTransform().transform(bounds));
651
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000652 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800653}
654
655sp<compositionengine::LayerFE> Layer::asLayerFE() const {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700656 compositionengine::LayerFE* layerFE = const_cast<compositionengine::LayerFE*>(
Lloyd Piquede196652020-01-22 17:29:58 -0800657 static_cast<const compositionengine::LayerFE*>(this));
Ady Abrahamd11bade2022-08-01 16:18:03 -0700658 return sp<compositionengine::LayerFE>::fromExisting(layerFE);
Lloyd Piquede196652020-01-22 17:29:58 -0800659}
660
Lloyd Piquea83776c2019-01-29 18:42:32 -0800661const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700662 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800663}
664
Mathias Agopian13127d82013-03-05 17:47:11 -0800665// ---------------------------------------------------------------------------
666// drawing...
667// ---------------------------------------------------------------------------
668
Vishnu Nair9b079a22020-01-21 14:36:08 -0800669std::optional<compositionengine::LayerFE::LayerSettings> Layer::prepareClientComposition(
Patrick Williams16d8b2c2022-08-08 17:29:05 +0000670 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000671 std::optional<compositionengine::LayerFE::LayerSettings> layerSettings =
672 prepareClientCompositionInternal(targetSettings);
673 // Nothing to render.
674 if (!layerSettings) {
675 return {};
676 }
677
678 // HWC requests to clear this layer.
679 if (targetSettings.clearContent) {
680 prepareClearClientComposition(*layerSettings, false /* blackout */);
681 return layerSettings;
682 }
683
684 // set the shadow for the layer if needed
685 prepareShadowClientComposition(*layerSettings, targetSettings.viewport);
686
687 return layerSettings;
688}
689
690std::optional<compositionengine::LayerFE::LayerSettings> Layer::prepareClientCompositionInternal(
691 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
692 ATRACE_CALL();
693
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000694 const auto* snapshot = getLayerSnapshot();
695 if (!snapshot) {
Lloyd Piquef16688f2019-02-19 17:47:57 -0800696 return {};
697 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800698
Vishnu Nair9b079a22020-01-21 14:36:08 -0800699 compositionengine::LayerFE::LayerSettings layerSettings;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000700 layerSettings.geometry.boundaries =
701 reduce(snapshot->geomLayerBounds, snapshot->transparentRegionHint);
702 layerSettings.geometry.positionTransform = snapshot->geomLayerTransform.asMatrix4();
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000703
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400704 // skip drawing content if the targetSettings indicate the content will be occluded
Ady Abrahambaa6cf52021-07-13 14:02:19 -0700705 const bool drawContent = targetSettings.realContentIsVisible || targetSettings.clearContent;
706 layerSettings.skipContentDraw = !drawContent;
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400707
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000708 if (hasColorTransform()) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000709 layerSettings.colorTransform = snapshot->colorTransform;
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000710 }
711
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000712 const auto& roundedCornerState = snapshot->roundedCorner;
Lloyd Piquef16688f2019-02-19 17:47:57 -0800713 layerSettings.geometry.roundedCornersRadius = roundedCornerState.radius;
714 layerSettings.geometry.roundedCornersCrop = roundedCornerState.cropRect;
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000715
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000716 layerSettings.alpha = snapshot->alpha;
717 layerSettings.sourceDataspace = snapshot->dataspace;
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700718
Alec Mouridda07d92022-04-25 22:39:25 +0000719 // Override the dataspace transfer from 170M to sRGB if the device configuration requests this.
720 // We do this here instead of in buffer info so that dumpsys can still report layers that are
721 // using the 170M transfer.
722 if (mFlinger->mTreat170mAsSrgb &&
723 (layerSettings.sourceDataspace & HAL_DATASPACE_TRANSFER_MASK) ==
724 HAL_DATASPACE_TRANSFER_SMPTE_170M) {
725 layerSettings.sourceDataspace = static_cast<ui::Dataspace>(
726 (layerSettings.sourceDataspace & HAL_DATASPACE_STANDARD_MASK) |
727 (layerSettings.sourceDataspace & HAL_DATASPACE_RANGE_MASK) |
728 HAL_DATASPACE_TRANSFER_SRGB);
729 }
730
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700731 layerSettings.whitePointNits = targetSettings.whitePointNits;
Alec Mourif54453c2021-05-13 16:28:28 -0700732 switch (targetSettings.blurSetting) {
733 case LayerFE::ClientCompositionTargetSettings::BlurSetting::Enabled:
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000734 layerSettings.backgroundBlurRadius = snapshot->backgroundBlurRadius;
735 layerSettings.blurRegions = snapshot->blurRegions;
736 layerSettings.blurRegionTransform = snapshot->geomInverseLayerTransform.asMatrix4();
Alec Mourif54453c2021-05-13 16:28:28 -0700737 break;
738 case LayerFE::ClientCompositionTargetSettings::BlurSetting::BackgroundBlurOnly:
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000739 layerSettings.backgroundBlurRadius = snapshot->backgroundBlurRadius;
Alec Mourif54453c2021-05-13 16:28:28 -0700740 break;
741 case LayerFE::ClientCompositionTargetSettings::BlurSetting::BlurRegionsOnly:
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000742 layerSettings.blurRegions = snapshot->blurRegions;
743 layerSettings.blurRegionTransform = snapshot->geomInverseLayerTransform.asMatrix4();
Alec Mourif54453c2021-05-13 16:28:28 -0700744 break;
745 case LayerFE::ClientCompositionTargetSettings::BlurSetting::Disabled:
746 default:
747 break;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +0100748 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000749 layerSettings.stretchEffect = snapshot->stretchEffect;
Ana Krulec6eab17a2020-12-09 15:52:36 -0800750 // Record the name of the layer for debugging further down the stack.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000751 layerSettings.name = snapshot->name;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000752
Vishnu Nairf115db82022-09-06 16:59:33 -0700753 if (hasEffect() && !hasBufferOrSidebandStream()) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000754 prepareEffectsClientComposition(layerSettings, targetSettings);
755 return layerSettings;
756 }
757
758 prepareBufferStateClientComposition(layerSettings, targetSettings);
Lloyd Piquef16688f2019-02-19 17:47:57 -0800759 return layerSettings;
Mathias Agopian13127d82013-03-05 17:47:11 -0800760}
761
Vishnu Nairb87d94f2020-02-13 09:17:36 -0800762void Layer::prepareClearClientComposition(LayerFE::LayerSettings& layerSettings,
763 bool blackout) const {
764 layerSettings.source.buffer.buffer = nullptr;
765 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
766 layerSettings.disableBlending = true;
Vishnu Nair3b653e72020-02-24 16:40:50 -0800767 layerSettings.bufferId = 0;
Vishnu Nairb87d94f2020-02-13 09:17:36 -0800768 layerSettings.frameNumber = 0;
769
770 // If layer is blacked out, force alpha to 1 so that we draw a black color layer.
771 layerSettings.alpha = blackout ? 1.0f : 0.0f;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000772 layerSettings.name = getLayerSnapshot()->name;
Vishnu Nairb87d94f2020-02-13 09:17:36 -0800773}
774
Patrick Williamsbb25f802022-08-30 23:02:34 +0000775void Layer::prepareEffectsClientComposition(
776 compositionengine::LayerFE::LayerSettings& layerSettings,
777 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
778 // If fill bounds are occluded or the fill color is invalid skip the fill settings.
779 if (targetSettings.realContentIsVisible && fillsColor()) {
780 // Set color for color fill settings.
781 layerSettings.source.solidColor = getColor().rgb;
782 } else if (hasBlur() || drawShadows()) {
783 layerSettings.skipContentDraw = true;
784 }
785}
786
787void Layer::prepareBufferStateClientComposition(
788 compositionengine::LayerFE::LayerSettings& layerSettings,
789 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000790 ATRACE_CALL();
791 const auto* snapshot = getLayerSnapshot();
792 if (CC_UNLIKELY(!snapshot->externalTexture)) {
793 // If there is no buffer for the layer or we have sidebandstream where there is no
794 // activeBuffer, then we need to return LayerSettings.
Patrick Williamsbb25f802022-08-30 23:02:34 +0000795 return;
796 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000797 const bool blackOutLayer =
798 (snapshot->hasProtectedContent && !targetSettings.supportsProtectedContent) ||
799 ((snapshot->isSecure || snapshot->hasProtectedContent) && !targetSettings.isSecure);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000800 const bool bufferCanBeUsedAsHwTexture =
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000801 snapshot->externalTexture->getUsage() & GraphicBuffer::USAGE_HW_TEXTURE;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000802 if (blackOutLayer || !bufferCanBeUsedAsHwTexture) {
803 ALOGE_IF(!bufferCanBeUsedAsHwTexture, "%s is blacked out as buffer is not gpu readable",
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000804 snapshot->name.c_str());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000805 prepareClearClientComposition(layerSettings, true /* blackout */);
806 return;
807 }
808
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000809 layerSettings.source.buffer.buffer = snapshot->externalTexture;
810 layerSettings.source.buffer.isOpaque = snapshot->contentOpaque;
811 layerSettings.source.buffer.fence = snapshot->acquireFence;
812 layerSettings.source.buffer.textureName = snapshot->textureName;
813 layerSettings.source.buffer.usePremultipliedAlpha = snapshot->premultipliedAlpha;
814 layerSettings.source.buffer.isY410BT2020 = snapshot->isHdrY410;
815 bool hasSmpte2086 = snapshot->hdrMetadata.validTypes & HdrMetadata::SMPTE2086;
816 bool hasCta861_3 = snapshot->hdrMetadata.validTypes & HdrMetadata::CTA861_3;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000817 float maxLuminance = 0.f;
818 if (hasSmpte2086 && hasCta861_3) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000819 maxLuminance = std::min(snapshot->hdrMetadata.smpte2086.maxLuminance,
820 snapshot->hdrMetadata.cta8613.maxContentLightLevel);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000821 } else if (hasSmpte2086) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000822 maxLuminance = snapshot->hdrMetadata.smpte2086.maxLuminance;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000823 } else if (hasCta861_3) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000824 maxLuminance = snapshot->hdrMetadata.cta8613.maxContentLightLevel;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000825 } else {
826 switch (layerSettings.sourceDataspace & HAL_DATASPACE_TRANSFER_MASK) {
827 case HAL_DATASPACE_TRANSFER_ST2084:
828 case HAL_DATASPACE_TRANSFER_HLG:
829 // Behavior-match previous releases for HDR content
830 maxLuminance = defaultMaxLuminance;
831 break;
832 }
833 }
834 layerSettings.source.buffer.maxLuminanceNits = maxLuminance;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000835 layerSettings.frameNumber = snapshot->frameNumber;
836 layerSettings.bufferId = snapshot->externalTexture->getId();
Patrick Williamsbb25f802022-08-30 23:02:34 +0000837
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000838 const bool useFiltering = targetSettings.needsFiltering ||
839 snapshot->geomLayerTransform.needsBilinearFiltering() || snapshot->bufferNeedsFiltering;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000840
841 // Query the texture matrix given our current filtering mode.
842 float textureMatrix[16];
843 getDrawingTransformMatrix(useFiltering, textureMatrix);
844
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000845 if (snapshot->geomBufferUsesDisplayInverseTransform) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000846 /*
847 * the code below applies the primary display's inverse transform to
848 * the texture transform
849 */
850 uint32_t transform = DisplayDevice::getPrimaryDisplayRotationFlags();
851 mat4 tr = inverseOrientation(transform);
852
853 /**
854 * TODO(b/36727915): This is basically a hack.
855 *
856 * Ensure that regardless of the parent transformation,
857 * this buffer is always transformed from native display
858 * orientation to display orientation. For example, in the case
859 * of a camera where the buffer remains in native orientation,
860 * we want the pixels to always be upright.
861 */
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000862 const auto parentTransform = snapshot->transform;
863 tr = tr * inverseOrientation(parentTransform.getOrientation());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000864
865 // and finally apply it to the original texture matrix
866 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
867 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
868 }
869
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000870 const Rect win{layerSettings.geometry.boundaries};
871 float bufferWidth = snapshot->bufferSize.getWidth();
872 float bufferHeight = snapshot->bufferSize.getHeight();
Patrick Williamsbb25f802022-08-30 23:02:34 +0000873
Patrick Williams83f36b22022-09-14 17:57:35 +0000874 // Layers can have a "buffer size" of [0, 0, -1, -1] when no display frame has
Patrick Williamsbb25f802022-08-30 23:02:34 +0000875 // been set and there is no parent layer bounds. In that case, the scale is meaningless so
876 // ignore them.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000877 if (!snapshot->bufferSize.isValid()) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000878 bufferWidth = float(win.right) - float(win.left);
879 bufferHeight = float(win.bottom) - float(win.top);
880 }
881
882 const float scaleHeight = (float(win.bottom) - float(win.top)) / bufferHeight;
883 const float scaleWidth = (float(win.right) - float(win.left)) / bufferWidth;
884 const float translateY = float(win.top) / bufferHeight;
885 const float translateX = float(win.left) / bufferWidth;
886
887 // Flip y-coordinates because GLConsumer expects OpenGL convention.
888 mat4 tr = mat4::translate(vec4(.5f, .5f, 0.f, 1.f)) * mat4::scale(vec4(1.f, -1.f, 1.f, 1.f)) *
889 mat4::translate(vec4(-.5f, -.5f, 0.f, 1.f)) *
890 mat4::translate(vec4(translateX, translateY, 0.f, 1.f)) *
891 mat4::scale(vec4(scaleWidth, scaleHeight, 1.0f, 1.0f));
892
893 layerSettings.source.buffer.useTextureFiltering = useFiltering;
894 layerSettings.source.buffer.textureTransform =
895 mat4(static_cast<const float*>(textureMatrix)) * tr;
896
897 return;
898}
899
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500900aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
901 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700902 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800903 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500904 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800905 }
906 if (outputLayer->getState().hwc) {
907 return (*outputLayer->getState().hwc).hwcCompositionType;
908 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500909 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800910 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800911}
912
Mathias Agopian13127d82013-03-05 17:47:11 -0800913// ----------------------------------------------------------------------------
914// local state
915// ----------------------------------------------------------------------------
916
David Sodman41fdfc92017-11-06 16:09:56 -0800917bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800918 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700919 if (s.flags & layer_state_t::eLayerSecure) {
920 return true;
921 }
922
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000923 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700924 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700925}
926
Mathias Agopian13127d82013-03-05 17:47:11 -0800927// ----------------------------------------------------------------------------
928// transaction
929// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800930
Marissa Wall61c58622018-07-18 10:12:20 -0700931uint32_t Layer::doTransaction(uint32_t flags) {
932 ATRACE_CALL();
933
Robert Carr0758e5d2021-03-11 22:15:04 -0800934 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700935 mDrawingStateModified = mDrawingState.modified;
936 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700937
Alec Mourib416efd2018-09-06 21:01:59 +0000938 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700939
Robert Carr6a160312021-05-17 12:08:20 -0700940 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800941 // invalidate and recompute the visible regions if needed
942 flags |= Layer::eVisibleRegion;
943 }
944
Robert Carr6a160312021-05-17 12:08:20 -0700945 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800946 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000947 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800948 flags |= eVisibleRegion;
949 this->contentDirty = true;
950
951 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700952 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800953 }
954
Arthur Hung9ed43392022-05-27 06:31:57 +0000955 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
956 mFlinger->mUpdateInputInfo = true;
957 }
958
Robert Carr6a160312021-05-17 12:08:20 -0700959 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800960
Mathias Agopian13127d82013-03-05 17:47:11 -0800961 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800962}
963
Robert Carr6a160312021-05-17 12:08:20 -0700964void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000965 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
966 // bufferSurfaceFrameTX will be presented in latchBuffer.
967 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
968 if (surfaceFrame->getPresentState() != PresentState::Presented) {
969 // With applyPendingStates, we could end up having presented surfaceframes from previous
970 // states
971 surfaceFrame->setPresentState(PresentState::Presented);
972 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
973 }
974 }
Robert Carr6a160312021-05-17 12:08:20 -0700975 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700976}
977
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700978uint32_t Layer::clearTransactionFlags(uint32_t mask) {
979 const auto flags = mTransactionFlags & mask;
980 mTransactionFlags &= ~mask;
981 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800982}
983
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700984void Layer::setTransactionFlags(uint32_t mask) {
985 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800986}
987
Robert Carr1f0a16a2016-10-24 16:27:39 -0700988bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
989 ssize_t idx = mCurrentChildren.indexOf(childLayer);
990 if (idx < 0) {
991 return false;
992 }
993 if (childLayer->setLayer(z)) {
994 mCurrentChildren.removeAt(idx);
995 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800996 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700997 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800998 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700999}
1000
Robert Carr503c7042017-09-27 15:06:08 -07001001bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
1002 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
1003 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1004 if (idx < 0) {
1005 return false;
1006 }
1007 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
1008 mCurrentChildren.removeAt(idx);
1009 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -08001010 return true;
Robert Carr503c7042017-09-27 15:06:08 -07001011 }
Robert Carr503d2bd2017-12-04 15:49:47 -08001012 return false;
Robert Carr503c7042017-09-27 15:06:08 -07001013}
1014
Robert Carrae060832016-11-28 10:51:00 -08001015bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -07001016 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
1017 mDrawingState.sequence++;
1018 mDrawingState.z = z;
1019 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001020
Robert Carra70e91c2021-06-11 13:59:52 -07001021 mFlinger->mSomeChildrenChanged = true;
1022
Robert Carrdb66e622017-04-10 16:55:57 -07001023 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -07001024 if (mDrawingState.zOrderRelativeOf != nullptr) {
1025 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -07001026 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001027 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -07001028 }
chaviw606e5cf2019-03-01 10:12:10 -08001029 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -07001030 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001031 setTransactionFlags(eTransactionNeeded);
1032 return true;
1033}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001034
Robert Carrdb66e622017-04-10 16:55:57 -07001035void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -07001036 mDrawingState.zOrderRelatives.remove(relative);
1037 mDrawingState.sequence++;
1038 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001039 setTransactionFlags(eTransactionNeeded);
1040}
1041
1042void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -07001043 mDrawingState.zOrderRelatives.add(relative);
1044 mDrawingState.modified = true;
1045 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -07001046 setTransactionFlags(eTransactionNeeded);
1047}
1048
chaviw606e5cf2019-03-01 10:12:10 -08001049void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -07001050 mDrawingState.zOrderRelativeOf = relativeOf;
1051 mDrawingState.sequence++;
1052 mDrawingState.modified = true;
1053 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -07001054
chaviw606e5cf2019-03-01 10:12:10 -08001055 setTransactionFlags(eTransactionNeeded);
1056}
1057
Robert Carr503d2bd2017-12-04 15:49:47 -08001058bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nairf9096652021-07-20 18:49:42 -07001059 sp<Layer> relative = fromHandle(relativeToHandle).promote();
Robert Carrdb66e622017-04-10 16:55:57 -07001060 if (relative == nullptr) {
1061 return false;
1062 }
1063
Robert Carr6a160312021-05-17 12:08:20 -07001064 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
1065 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -08001066 return false;
1067 }
1068
Robert Carr88b85e12022-03-21 15:47:35 -07001069 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
1070 (relative->mDrawingState.zOrderRelativeOf == this)) {
1071 ALOGE("Detected relative layer loop between %s and %s",
1072 mName.c_str(), relative->mName.c_str());
1073 ALOGE("Ignoring new call to set relative layer");
1074 return false;
1075 }
1076
Robert Carra70e91c2021-06-11 13:59:52 -07001077 mFlinger->mSomeChildrenChanged = true;
1078
Robert Carr6a160312021-05-17 12:08:20 -07001079 mDrawingState.sequence++;
1080 mDrawingState.modified = true;
1081 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -07001082
Robert Carr6a160312021-05-17 12:08:20 -07001083 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -07001084 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001085 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -07001086 }
chaviw606e5cf2019-03-01 10:12:10 -08001087 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001088 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -07001089
1090 setTransactionFlags(eTransactionNeeded);
1091
1092 return true;
1093}
1094
Winson Chunga30f7c92021-06-29 15:42:56 -07001095bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
1096 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
1097 mDrawingState.isTrustedOverlay = isTrustedOverlay;
1098 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00001099 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -07001100 setTransactionFlags(eTransactionNeeded);
1101 return true;
1102}
1103
1104bool Layer::isTrustedOverlay() const {
1105 if (getDrawingState().isTrustedOverlay) {
1106 return true;
1107 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001108 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -07001109 return (p != nullptr) && p->isTrustedOverlay();
1110}
1111
Dan Stoza9e56aa02015-11-02 13:00:03 -08001112bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -07001113 if (mDrawingState.color.a == alpha) return false;
1114 mDrawingState.sequence++;
1115 mDrawingState.color.a = alpha;
1116 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001117 setTransactionFlags(eTransactionNeeded);
1118 return true;
1119}
chaviw13fdc492017-06-27 12:40:18 -07001120
Valerie Haudd0b7572019-01-29 14:59:27 -08001121bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -07001122 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -07001123 return false;
Valerie Hauaa194562019-02-05 16:21:38 -08001124 }
Robert Carr6a160312021-05-17 12:08:20 -07001125 mDrawingState.sequence++;
1126 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -08001127 setTransactionFlags(eTransactionNeeded);
1128
Robert Carr6a160312021-05-17 12:08:20 -07001129 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001130 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001131 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001132 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001133 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08001134 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001135 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001136
Valerie Haudd0b7572019-01-29 14:59:27 -08001137 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001138 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001139 mFlinger->mLayersAdded = true;
1140 // set up SF to handle added color layer
1141 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -07001142 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001143 }
1144 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001145 } else if (mDrawingState.bgColorLayer && alpha == 0) {
1146 mDrawingState.bgColorLayer->reparent(nullptr);
1147 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001148 return true;
1149 }
1150
Robert Carr6a160312021-05-17 12:08:20 -07001151 mDrawingState.bgColorLayer->setColor(color);
1152 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1153 mDrawingState.bgColorLayer->setAlpha(alpha);
1154 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001155
chaviw13fdc492017-06-27 12:40:18 -07001156 return true;
1157}
1158
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001159bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001160 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001161
Robert Carr6a160312021-05-17 12:08:20 -07001162 mDrawingState.sequence++;
1163 mDrawingState.cornerRadius = cornerRadius;
1164 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001165 setTransactionFlags(eTransactionNeeded);
1166 return true;
1167}
1168
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001169bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001170 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001171 // If we start or stop drawing blur then the layer's visibility state may change so increment
1172 // the magic sequence number.
1173 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1174 mDrawingState.sequence++;
1175 }
Robert Carr6a160312021-05-17 12:08:20 -07001176 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1177 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001178 setTransactionFlags(eTransactionNeeded);
1179 return true;
1180}
Marissa Wall61c58622018-07-18 10:12:20 -07001181
Mathias Agopian13127d82013-03-05 17:47:11 -08001182bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001183 mDrawingState.sequence++;
1184 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001185 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001186 setTransactionFlags(eTransactionNeeded);
1187 return true;
1188}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001189
Lucas Dupinc3800b82020-10-02 16:24:48 -07001190bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001191 // If we start or stop drawing blur then the layer's visibility state may change so increment
1192 // the magic sequence number.
1193 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1194 mDrawingState.sequence++;
1195 }
Robert Carr6a160312021-05-17 12:08:20 -07001196 mDrawingState.blurRegions = blurRegions;
1197 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001198 setTransactionFlags(eTransactionNeeded);
1199 return true;
1200}
1201
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001202bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001203 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1204 if (mDrawingState.flags == newFlags) return false;
1205 mDrawingState.sequence++;
1206 mDrawingState.flags = newFlags;
1207 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001208 setTransactionFlags(eTransactionNeeded);
1209 return true;
1210}
Robert Carr99e27f02016-06-16 15:18:02 -07001211
chaviw25714502021-02-11 10:01:08 -08001212bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001213 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001214 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001215 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001216
Robert Carr6a160312021-05-17 12:08:20 -07001217 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001218 setTransactionFlags(eTransactionNeeded);
1219 return true;
1220}
Robert Carr8d5227b2017-03-16 15:41:03 -07001221
Evan Roskyef876c92019-01-25 17:46:06 -08001222bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001223 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1224 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001225 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001226 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001227}
1228
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001229bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001230 if (mDrawingState.layerStack == layerStack) return false;
1231 mDrawingState.sequence++;
1232 mDrawingState.layerStack = layerStack;
1233 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001234 setTransactionFlags(eTransactionNeeded);
1235 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001236}
1237
Peiyong Linc502cb72019-03-01 15:00:23 -08001238bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001239 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001240 return false;
1241 }
Robert Carr6a160312021-05-17 12:08:20 -07001242 mDrawingState.sequence++;
1243 mDrawingState.colorSpaceAgnostic = agnostic;
1244 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001245 setTransactionFlags(eTransactionNeeded);
1246 return true;
1247}
1248
Sally Qi81d95e62022-03-21 19:41:33 -07001249bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1250 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1251
1252 mDrawingState.sequence++;
1253 mDrawingState.dimmingEnabled = dimmingEnabled;
1254 mDrawingState.modified = true;
1255 setTransactionFlags(eTransactionNeeded);
1256 return true;
1257}
1258
Ana Krulecc84d09b2019-11-02 23:10:29 +01001259bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001260 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1261 mDrawingState.frameRateSelectionPriority = priority;
1262 mDrawingState.sequence++;
1263 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001264 setTransactionFlags(eTransactionNeeded);
1265 return true;
1266}
1267
1268int32_t Layer::getFrameRateSelectionPriority() const {
1269 // Check if layer has priority set.
1270 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1271 return mDrawingState.frameRateSelectionPriority;
1272 }
1273 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001274 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001275 if (parent != nullptr) {
1276 return parent->getFrameRateSelectionPriority();
1277 }
1278
1279 return Layer::PRIORITY_UNSET;
1280}
1281
Andy Labrada096227e2022-06-15 16:58:11 +00001282bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1283 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1284 mDrawingState.defaultFrameRateCompatibility = compatibility;
1285 mDrawingState.modified = true;
1286 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1287 setTransactionFlags(eTransactionNeeded);
1288 return true;
1289}
1290
1291scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1292 return mDrawingState.defaultFrameRateCompatibility;
1293}
1294
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001295bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1296 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1297};
1298
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001299ui::LayerStack Layer::getLayerStack() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001300 if (const auto parent = mDrawingParent.promote()) {
1301 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001302 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001303 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001304}
1305
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001306bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001307 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001308 return false;
1309 }
1310
Robert Carr6a160312021-05-17 12:08:20 -07001311 mDrawingState.sequence++;
1312 mDrawingState.shadowRadius = shadowRadius;
1313 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001314 setTransactionFlags(eTransactionNeeded);
1315 return true;
1316}
1317
Vishnu Nair6213bd92020-05-08 17:42:25 -07001318bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001319 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001320 return false;
1321 }
1322
Robert Carr6a160312021-05-17 12:08:20 -07001323 mDrawingState.sequence++;
1324 mDrawingState.fixedTransformHint = fixedTransformHint;
1325 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001326 setTransactionFlags(eTransactionNeeded);
1327 return true;
1328}
1329
John Reckcdb4ed72021-02-04 13:39:33 -05001330bool Layer::setStretchEffect(const StretchEffect& effect) {
1331 StretchEffect temp = effect;
1332 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001333 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001334 return false;
1335 }
Robert Carr6a160312021-05-17 12:08:20 -07001336 mDrawingState.sequence++;
1337 mDrawingState.stretchEffect = temp;
1338 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001339 setTransactionFlags(eTransactionNeeded);
1340 return true;
1341}
1342
John Reckc00c6692021-02-16 11:37:33 -05001343StretchEffect Layer::getStretchEffect() const {
1344 if (mDrawingState.stretchEffect.hasEffect()) {
1345 return mDrawingState.stretchEffect;
1346 }
1347
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001348 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001349 if (parent != nullptr) {
1350 auto effect = parent->getStretchEffect();
1351 if (effect.hasEffect()) {
1352 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1353 return effect;
1354 }
1355 }
1356 return StretchEffect{};
1357}
1358
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001359bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1360 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001361 return false;
1362 }
1363 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001364 mBorderWidth = width;
1365 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001366 return true;
1367}
1368
1369bool Layer::isBorderEnabled() {
1370 return mBorderEnabled;
1371}
1372
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001373float Layer::getBorderWidth() {
1374 return mBorderWidth;
1375}
1376
1377const half4& Layer::getBorderColor() {
1378 return mBorderColor;
1379}
1380
Ady Abrahama850c182021-08-04 13:04:37 -07001381bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1382 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1383 const auto frameRate = [&] {
1384 if (mDrawingState.frameRate.rate.isValid() ||
1385 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1386 return mDrawingState.frameRate;
1387 }
1388
1389 return parentFrameRate;
1390 }();
1391
1392 *transactionNeeded |= setFrameRateForLayerTree(frameRate);
1393
1394 // The frame rate is propagated to the children
1395 bool childrenHaveFrameRate = false;
1396 for (const sp<Layer>& child : mCurrentChildren) {
1397 childrenHaveFrameRate |=
1398 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1399 }
1400
1401 // If we don't have a valid frame rate, but the children do, we set this
1402 // layer as NoVote to allow the children to control the refresh rate
1403 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1404 childrenHaveFrameRate) {
1405 *transactionNeeded |=
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001406 setFrameRateForLayerTree(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001407 }
1408
1409 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1410 // the same reason we are allowing touch boost for those layers. See
1411 // RefreshRateConfigs::getBestRefreshRate for more details.
1412 const auto layerVotedWithDefaultCompatibility =
1413 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1414 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1415 const auto layerVotedWithExactCompatibility =
1416 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1417 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1418 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1419}
1420
Ady Abraham60e42ea2020-03-09 19:17:31 -07001421void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001422 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001423 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001424 while (auto parent = layer->getParent()) {
1425 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001426 }
Ady Abrahama850c182021-08-04 13:04:37 -07001427 return layer;
1428 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001429
Ady Abraham60e42ea2020-03-09 19:17:31 -07001430 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001431 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001432
Ady Abrahama850c182021-08-04 13:04:37 -07001433 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001434 if (transactionNeeded) {
1435 mFlinger->setTransactionFlags(eTraversalNeeded);
1436 }
1437}
1438
Ady Abraham71c437d2020-01-31 15:56:57 -08001439bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001440 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001441 return false;
1442 }
1443
Robert Carr6a160312021-05-17 12:08:20 -07001444 mDrawingState.sequence++;
1445 mDrawingState.frameRate = frameRate;
1446 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001447
1448 updateTreeHasFrameRateVote();
1449
Steven Thomas3172e202020-01-06 19:25:30 -08001450 setTransactionFlags(eTransactionNeeded);
1451 return true;
1452}
1453
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001454void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1455 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001456 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001457
1458 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1459 // there are two transactions with the same token, the first one without a buffer and the
1460 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1461 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001462 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1463 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001464 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001465 mDrawingState.bufferSurfaceFrameTX = it->second;
1466 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1467 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1468 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001469 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001470 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001471 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1472 }
1473}
1474
1475void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1476 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001477 mDrawingState.frameTimelineInfo = info;
1478 mDrawingState.postTime = postTime;
1479 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001480 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001481
Robert Carr6a160312021-05-17 12:08:20 -07001482 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001483 bufferSurfaceFrameTX != nullptr) {
1484 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1485 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1486 // being used for BufferSurfaceFrame, don't create a new one.
1487 return;
1488 }
1489 }
1490 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1491 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1492 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001493 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1494 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001495 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001496 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001497 } else {
1498 if (it->second->getPresentState() == PresentState::Presented) {
1499 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1500 // have been from previous vsync.
1501 it->second = createSurfaceFrameForTransaction(info, postTime);
1502 }
1503 }
1504}
1505
1506void Layer::addSurfaceFrameDroppedForBuffer(
1507 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001508 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001509 surfaceFrame->setPresentState(PresentState::Dropped);
1510 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1511}
1512
1513void Layer::addSurfaceFramePresentedForBuffer(
1514 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1515 nsecs_t currentLatchTime) {
1516 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1517 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1518 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1519 mLastLatchTime = currentLatchTime;
1520}
1521
1522std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1523 const FrameTimelineInfo& info, nsecs_t postTime) {
1524 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001525 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1526 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001527 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001528 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001529 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001530 // For Transactions, the post time is considered to be both queue and acquire fence time.
1531 surfaceFrame->setActualQueueTime(postTime);
1532 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001533 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1534 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001535 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001536 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001537 onSurfaceFrameCreated(surfaceFrame);
1538 return surfaceFrame;
1539}
1540
1541std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1542 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1543 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001544 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001545 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001546 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001547 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001548 // For buffers, acquire fence time will set during latch.
1549 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001550 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1551 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001552 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001553 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001554 onSurfaceFrameCreated(surfaceFrame);
1555 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001556}
1557
Ady Abrahama850c182021-08-04 13:04:37 -07001558bool Layer::setFrameRateForLayerTree(FrameRate frameRate) {
1559 if (mDrawingState.frameRateForLayerTree == frameRate) {
1560 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001561 }
1562
Ady Abrahama850c182021-08-04 13:04:37 -07001563 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001564
Ady Abrahama850c182021-08-04 13:04:37 -07001565 // TODO(b/195668952): we probably don't need to dirty visible regions here
1566 // or even store frameRateForLayerTree in mDrawingState
1567 mDrawingState.sequence++;
1568 mDrawingState.modified = true;
1569 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001570
Dominik Laskowski068173d2021-08-11 17:22:59 -07001571 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
1572 mFlinger->mScheduler->recordLayerHistory(this, systemTime(), LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001573
1574 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001575}
1576
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001577Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1578 return getDrawingState().frameRateForLayerTree;
1579}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001580
Robert Carr1f0a16a2016-10-24 16:27:39 -07001581bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001582 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001583 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001584 if (parent != nullptr && parent->isHiddenByPolicy()) {
1585 return true;
1586 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001587 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1588 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1589 if (zOrderRelativeOf != nullptr) {
1590 if (zOrderRelativeOf->isHiddenByPolicy()) {
1591 return true;
1592 }
1593 }
1594 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001595 if (CC_UNLIKELY(!isTransformValid())) {
1596 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1597 return true;
1598 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001599 return s.flags & layer_state_t::eLayerHidden;
1600}
1601
David Sodman41fdfc92017-11-06 16:09:56 -08001602uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001603 // TODO: should we do something special if mSecure is set?
1604 if (mProtectedByApp) {
1605 // need a hardware-protected path to external video sink
1606 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001607 }
Riley Andrews03414a12014-07-01 14:22:59 -07001608 if (mPotentialCursor) {
1609 usage |= GraphicBuffer::USAGE_CURSOR;
1610 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001611 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001612 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001613}
1614
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001615void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1616 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1617 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001618 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001619
Vishnu Nair6213bd92020-05-08 17:42:25 -07001620 setTransformHint(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001621}
1622
Mathias Agopian13127d82013-03-05 17:47:11 -08001623// ----------------------------------------------------------------------------
1624// debugging
1625// ----------------------------------------------------------------------------
1626
Marissa Wall61c58622018-07-18 10:12:20 -07001627// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001628gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001629 using namespace std::string_literals;
1630
Huihong Luo05539a12022-02-23 10:29:40 -08001631 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001632 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001633 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001634 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001635 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001636 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001637
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001638 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001639 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001640 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001641 info.mX = ds.transform.tx();
1642 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001643 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001644 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001645 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001646 info.mFlags = ds.flags;
1647 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001648 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001649 info.mMatrix[0][0] = ds.transform[0][0];
1650 info.mMatrix[0][1] = ds.transform[0][1];
1651 info.mMatrix[1][0] = ds.transform[1][0];
1652 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001653 {
chaviwd62d3062019-09-04 14:48:02 -07001654 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001655 if (buffer != 0) {
1656 info.mActiveBufferWidth = buffer->getWidth();
1657 info.mActiveBufferHeight = buffer->getHeight();
1658 info.mActiveBufferStride = buffer->getStride();
1659 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001660 } else {
1661 info.mActiveBufferWidth = 0;
1662 info.mActiveBufferHeight = 0;
1663 info.mActiveBufferStride = 0;
1664 info.mActiveBufferFormat = 0;
1665 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001666 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001667 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001668 info.mIsOpaque = isOpaque(ds);
1669 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001670 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001671 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001672}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001673
Yiwei Zhang5434a782018-12-05 18:06:32 -08001674void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001675 result.append(kDumpTableRowLength, '-');
1676 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001677 result.append(" Layer name\n");
1678 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001679 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001680 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001681 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001682 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001683 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001684 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1685 result.append(kDumpTableRowLength, '-');
1686 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001687}
1688
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001689void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1690 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001691 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001692 return;
1693 }
1694
Yiwei Zhang5434a782018-12-05 18:06:32 -08001695 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001696 if (mName.length() > 77) {
1697 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001698 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001699 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001700 shortened.append(mName, mName.length() - 36);
1701 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001702 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001703 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001704 }
1705
Yiwei Zhang5434a782018-12-05 18:06:32 -08001706 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001707
Alec Mourib416efd2018-09-06 21:01:59 +00001708 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001709 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001710
Chia-I Wu1e043612018-03-01 09:45:09 -08001711 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001712 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001713 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001714 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001715 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001716 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001717 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001718 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1719 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001720 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001721 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001722 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001723 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001724 const auto frameRate = getFrameRateForLayerTree();
1725 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1726 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001727 ftl::enum_string(frameRate.type).c_str(),
1728 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001729 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001730 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001731 }
Dan Stozae22aec72016-08-01 13:20:59 -07001732
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001733 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1734 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1735
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001736 result.append(kDumpTableRowLength, '-');
1737 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001738}
Dan Stozae22aec72016-08-01 13:20:59 -07001739
Yiwei Zhang5434a782018-12-05 18:06:32 -08001740void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001741 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001742}
1743
Svetoslavd85084b2014-03-20 10:28:31 -07001744void Layer::clearFrameStats() {
1745 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001746}
1747
Jamie Gennis6547ff42013-07-16 20:12:42 -07001748void Layer::logFrameStats() {
1749 mFrameTracker.logAndResetStats(mName);
1750}
1751
Svetoslavd85084b2014-03-20 10:28:31 -07001752void Layer::getFrameStats(FrameStats* outStats) const {
1753 mFrameTracker.getStats(outStats);
1754}
1755
Vishnu Nair0f085c62019-08-30 08:49:12 -07001756void Layer::dumpCallingUidPid(std::string& result) const {
chaviw250bcbb2020-08-05 11:17:54 -07001757 StringAppendF(&result, "Layer %s (%s) callingPid:%d callingUid:%d ownerUid:%d\n",
1758 getName().c_str(), getType(), mCallingPid, mCallingUid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001759}
1760
Brian Anderson5ea5e592016-12-01 16:54:33 -08001761void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001762 const int32_t layerId = getSequence();
1763 mFlinger->mTimeStats->onDestroy(layerId);
1764 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001765}
1766
Chia-I Wu98f1c102017-05-30 14:54:08 -07001767size_t Layer::getChildrenCount() const {
1768 size_t count = 0;
1769 for (const sp<Layer>& child : mCurrentChildren) {
1770 count += 1 + child->getChildrenCount();
1771 }
1772 return count;
1773}
1774
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001775void Layer::setGameModeForTree(GameMode gameMode) {
1776 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001777 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1778 gameMode =
1779 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001780 }
1781 setGameMode(gameMode);
1782 for (const sp<Layer>& child : mCurrentChildren) {
1783 child->setGameModeForTree(gameMode);
1784 }
1785}
1786
Robert Carr1f0a16a2016-10-24 16:27:39 -07001787void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001788 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001789 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001790
Robert Carr1f0a16a2016-10-24 16:27:39 -07001791 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001792 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001793 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001794 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001795}
1796
1797ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001798 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001799 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001800
Robert Carr1323c952019-01-28 18:13:27 -08001801 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001802 const auto removeResult = mCurrentChildren.remove(layer);
1803
1804 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001805 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001806 layer->updateTreeHasFrameRateVote();
1807
1808 return removeResult;
1809}
1810
Robert Carr15eae092018-03-23 13:43:53 -07001811void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001812 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001813 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001814 const float parentShadowRadius =
1815 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001816 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001817 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001818 }
1819}
1820
chaviwf1961f72017-09-18 16:41:07 -07001821bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001822 sp<Layer> newParent;
1823 if (newParentHandle != nullptr) {
Vishnu Nairf9096652021-07-20 18:49:42 -07001824 newParent = fromHandle(newParentHandle).promote();
Robert Carr54cf5b12019-01-25 14:02:28 -08001825 if (newParent == nullptr) {
1826 ALOGE("Unable to promote Layer handle");
1827 return false;
1828 }
1829 if (newParent == this) {
1830 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1831 return false;
1832 }
1833 }
1834
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001835 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001836 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001837 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001838 }
1839
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001840 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001841 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001842 if (!newParent->isRemovedFromCurrentState()) {
1843 addToCurrentState();
1844 } else {
1845 onRemovedFromCurrentState();
1846 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001847 } else {
1848 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001849 }
1850
chaviw06178942017-07-27 10:25:59 -07001851 return true;
1852}
1853
Peiyong Lind3788632018-09-18 16:01:31 -07001854bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001855 static const mat4 identityMatrix = mat4();
1856
Robert Carr6a160312021-05-17 12:08:20 -07001857 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001858 return false;
1859 }
Robert Carr6a160312021-05-17 12:08:20 -07001860 ++mDrawingState.sequence;
1861 mDrawingState.colorTransform = matrix;
1862 mDrawingState.hasColorTransform = matrix != identityMatrix;
1863 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001864 setTransactionFlags(eTransactionNeeded);
1865 return true;
1866}
1867
chaviwf66724d2018-11-28 16:35:21 -08001868mat4 Layer::getColorTransform() const {
1869 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001870 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001871 colorTransform = parent->getColorTransform() * colorTransform;
1872 }
1873 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001874}
1875
1876bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001877 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001878 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001879 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1880 }
1881 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001882}
1883
Chia-I Wu11481472018-05-04 10:43:19 -07001884bool Layer::isLegacyDataSpace() const {
1885 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001886 return !(getDataSpace() &
1887 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1888 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001889}
1890
Robert Carr1f0a16a2016-10-24 16:27:39 -07001891void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001892 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001893}
1894
Robert Carr6a160312021-05-17 12:08:20 -07001895int32_t Layer::getZ(LayerVector::StateSet) const {
1896 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001897}
1898
Robert Carr1c5481e2019-07-01 14:42:27 -07001899bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001900 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001901 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001902 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001903}
1904
David Sodman41fdfc92017-11-06 16:09:56 -08001905__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001906 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001907 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1908 "makeTraversalList received invalid stateSet");
1909 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1910 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001911 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001912
Robert Carr29abff82017-12-04 13:51:20 -08001913 if (state.zOrderRelatives.size() == 0) {
1914 *outSkipRelativeZUsers = true;
1915 return children;
1916 }
1917
chaviwfd462612018-05-31 16:11:27 -07001918 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001919 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001920 sp<Layer> strongRelative = weakRelative.promote();
1921 if (strongRelative != nullptr) {
1922 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001923 }
1924 }
1925
Dan Stoza412903f2017-04-27 13:42:17 -07001926 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001927 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001928 continue;
1929 }
Robert Carrdb66e622017-04-10 16:55:57 -07001930 traverse.add(child);
1931 }
1932
1933 return traverse;
1934}
1935
Robert Carr1f0a16a2016-10-24 16:27:39 -07001936/**
Robert Carrdb66e622017-04-10 16:55:57 -07001937 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001938 */
Dan Stoza412903f2017-04-27 13:42:17 -07001939void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001940 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1941 // produce a new list for traversing, including our relatives, and not including our children
1942 // who are relatives of another surface. In the case that there are no relative Z,
1943 // makeTraversalList returns our children directly to avoid significant overhead.
1944 // However in this case we need to take the responsibility for filtering children which
1945 // are relatives of another surface here.
1946 bool skipRelativeZUsers = false;
1947 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001948
Robert Carr1f0a16a2016-10-24 16:27:39 -07001949 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001950 for (; i < list.size(); i++) {
1951 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001952 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1953 continue;
1954 }
1955
chaviw301b1d82019-11-06 13:15:09 -08001956 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001957 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001958 }
Dan Stoza412903f2017-04-27 13:42:17 -07001959 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001960 }
Robert Carr29abff82017-12-04 13:51:20 -08001961
Dan Stoza412903f2017-04-27 13:42:17 -07001962 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001963 for (; i < list.size(); i++) {
1964 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001965
Robert Carr29abff82017-12-04 13:51:20 -08001966 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1967 continue;
1968 }
Dan Stoza412903f2017-04-27 13:42:17 -07001969 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001970 }
1971}
1972
1973/**
Robert Carrdb66e622017-04-10 16:55:57 -07001974 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001975 */
Dan Stoza412903f2017-04-27 13:42:17 -07001976void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1977 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001978 // See traverseInZOrder for documentation.
1979 bool skipRelativeZUsers = false;
1980 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001981
Robert Carr1f0a16a2016-10-24 16:27:39 -07001982 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001983 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001984 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001985
1986 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1987 continue;
1988 }
1989
chaviw301b1d82019-11-06 13:15:09 -08001990 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001991 break;
1992 }
Dan Stoza412903f2017-04-27 13:42:17 -07001993 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001994 }
Dan Stoza412903f2017-04-27 13:42:17 -07001995 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001996 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001997 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001998
1999 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
2000 continue;
2001 }
2002
Dan Stoza412903f2017-04-27 13:42:17 -07002003 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002004 }
2005}
2006
Edgar Arriaga844fa672020-01-16 14:21:42 -08002007void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
2008 visitor(this);
2009 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07002010 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002011 for (const sp<Layer>& child : children) {
2012 child->traverse(state, visitor);
2013 }
2014}
2015
chaviw4b129c22018-04-09 16:19:43 -07002016LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
2017 const std::vector<Layer*>& layersInTree) {
2018 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2019 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07002020 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2021 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002022 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002023
chaviwfd462612018-05-31 16:11:27 -07002024 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07002025 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2026 sp<Layer> strongRelative = weakRelative.promote();
2027 // Only add relative layers that are also descendents of the top most parent of the tree.
2028 // If a relative layer is not a descendent, then it should be ignored.
2029 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
2030 traverse.add(strongRelative);
2031 }
2032 }
2033
2034 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07002035 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002036 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
2037 // descendent of the top most parent of the tree. If it's not a descendent, then just add
2038 // the child here since it won't be added later as a relative.
2039 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
2040 childState.zOrderRelativeOf.promote().get())) {
2041 continue;
2042 }
2043 traverse.add(child);
2044 }
2045
2046 return traverse;
2047}
2048
2049void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
2050 LayerVector::StateSet stateSet,
2051 const LayerVector::Visitor& visitor) {
2052 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07002053
2054 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07002055 for (; i < list.size(); i++) {
2056 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08002057 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07002058 break;
2059 }
chaviw4b129c22018-04-09 16:19:43 -07002060 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002061 }
chaviw4b129c22018-04-09 16:19:43 -07002062
chaviwa76b2712017-09-20 12:02:26 -07002063 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07002064 for (; i < list.size(); i++) {
2065 const auto& relative = list[i];
2066 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002067 }
2068}
2069
chaviw4b129c22018-04-09 16:19:43 -07002070std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2071 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2072 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2073
2074 std::vector<Layer*> layersInTree = {this};
2075 for (size_t i = 0; i < children.size(); i++) {
2076 const auto& child = children[i];
2077 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2078 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2079 }
2080
2081 return layersInTree;
2082}
2083
2084void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2085 const LayerVector::Visitor& visitor) {
2086 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2087 std::sort(layersInTree.begin(), layersInTree.end());
2088 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2089}
2090
Peiyong Linefefaac2018-08-17 12:27:51 -07002091ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08002092 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002093}
2094
Garfield Tan2c1782c2022-02-16 15:25:05 -08002095bool Layer::isTransformValid() const {
2096 float transformDet = getTransform().det();
2097 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2098}
2099
chaviw13fdc492017-06-27 12:40:18 -07002100half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002101 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002102
chaviw13fdc492017-06-27 12:40:18 -07002103 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2104 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002105}
Robert Carr6452f122017-03-21 10:41:29 -07002106
Vishnu Nair6213bd92020-05-08 17:42:25 -07002107ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002108 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002109 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2110 return fixedTransformHint;
2111 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002112 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002113 if (!p) return fixedTransformHint;
2114 return p->getFixedTransformHint();
2115}
2116
chaviw13fdc492017-06-27 12:40:18 -07002117half4 Layer::getColor() const {
2118 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002119 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002120}
Robert Carr6452f122017-03-21 10:41:29 -07002121
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002122int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002123 if (getDrawingState().backgroundBlurRadius == 0) {
2124 return 0;
2125 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002126
Vishnu Nair29810f72022-07-01 16:38:41 +00002127 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002128 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2129 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002130}
2131
Galia Peychevae0acf382021-04-12 21:22:34 +02002132const std::vector<BlurRegion> Layer::getBlurRegions() const {
2133 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002134 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002135 for (auto& region : regionsCopy) {
2136 region.alpha = region.alpha * layerAlpha;
2137 }
2138 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002139}
2140
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002141Layer::RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002142 // Get parent settings
2143 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002144 const auto& parent = mDrawingParent.promote();
2145 if (parent != nullptr) {
2146 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002147 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002148 ui::Transform t = getActiveTransform(getDrawingState());
2149 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002150 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002151 parentSettings.radius.x *= t.getScaleX();
2152 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002153 }
2154 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002155
2156 // Get layer settings
2157 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002158 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002159 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002160 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002161
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002162 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002163 // If the parent and the layer have rounded corner settings, use the parent settings if the
2164 // parent crop is entirely inside the layer crop.
2165 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2166 if (parentSettings.cropRect.left > layerCropRect.left &&
2167 parentSettings.cropRect.top > layerCropRect.top &&
2168 parentSettings.cropRect.right < layerCropRect.right &&
2169 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2170 return parentSettings;
2171 } else {
2172 return layerSettings;
2173 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002174 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002175 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002176 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002177 return parentSettings;
2178 }
2179 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002180}
2181
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04002182void Layer::prepareShadowClientComposition(LayerFE::LayerSettings& caster,
Patrick Williams16d8b2c2022-08-08 17:29:05 +00002183 const Rect& layerStackRect) const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00002184 const auto* snapshot = getLayerSnapshot();
2185 renderengine::ShadowSettings state = snapshot->shadowSettings;
2186 if (state.length <= 0.f || (state.ambientColor.a <= 0.f && state.spotColor.a <= 0.f)) {
2187 return;
2188 }
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04002189
Vishnu Nair08f6eae2019-11-26 14:01:39 -08002190 // Shift the spot light x-position to the middle of the display and then
2191 // offset it by casting layer's screen pos.
Vishnu Nairbedb44b2022-08-02 21:47:40 +00002192 state.lightPos.x = (layerStackRect.width() / 2.f) - snapshot->transformedBounds.left;
2193 state.lightPos.y -= snapshot->transformedBounds.top;
2194 caster.shadow = state;
Vishnu Nair08f6eae2019-11-26 14:01:39 -08002195}
2196
Robert Carr88b85e12022-03-21 15:47:35 -07002197bool Layer::findInHierarchy(const sp<Layer>& l) {
2198 if (l == this) {
2199 return true;
2200 }
2201 for (auto& child : mDrawingChildren) {
2202 if (child->findInHierarchy(l)) {
2203 return true;
2204 }
2205 }
2206 return false;
2207}
2208
Robert Carr1f0a16a2016-10-24 16:27:39 -07002209void Layer::commitChildList() {
2210 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2211 const auto& child = mCurrentChildren[i];
2212 child->commitChildList();
2213 }
2214 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002215 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002216 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2217 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2218 if (zOrderRelativeOf == nullptr) return;
2219 if (findInHierarchy(zOrderRelativeOf)) {
2220 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2221 zOrderRelativeOf->mName.c_str());
2222 ALOGE("Severing rel Z loop, potentially dangerous");
2223 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002224 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002225 }
2226 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002227}
2228
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002229
chaviw3277faf2021-05-19 16:45:23 -05002230void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002231 mDrawingState.inputInfo = info;
Vishnu Nairf9096652021-07-20 18:49:42 -07002232 mDrawingState.touchableRegionCrop = fromHandle(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002233 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002234 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002235 setTransactionFlags(eTransactionNeeded);
2236}
2237
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002238LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002239 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002240 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002241 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2242
Vishnu Nair00b90132021-11-05 14:03:40 -07002243 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002244 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2245
Vishnu Nair60db8c02020-04-02 11:55:16 -07002246 // Only populate for the primary display.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002247 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -05002248 const auto compositionType = getCompositionType(*display);
Vishnu Nair60db8c02020-04-02 11:55:16 -07002249 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002250 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2251 [&]() { return layerProto->mutable_visible_region(); });
Vishnu Nair60db8c02020-04-02 11:55:16 -07002252 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08002253 }
2254
chaviw08f3cb22020-01-13 13:17:21 -08002255 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002256 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002257 }
chaviw6d89e2d2020-01-14 14:42:01 -08002258
2259 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002260}
2261
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002262void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002263 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002264 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002265 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002266 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002267 [&]() { return layerInfo->mutable_active_buffer(); });
2268 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2269 layerInfo->mutable_buffer_transform());
2270 }
2271 layerInfo->set_invalidate(contentDirty);
2272 layerInfo->set_is_protected(isProtected());
2273 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2274 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002275 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002276 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002277 layerInfo->set_corner_radius(
2278 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002279 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2280 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2281 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2282 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2283 [&]() { return layerInfo->mutable_position(); });
2284 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002285 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2286 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002287
Vishnu Nair00b90132021-11-05 14:03:40 -07002288 if (hasColorTransform()) {
2289 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002290 }
2291
Vishnu Nair60db8c02020-04-02 11:55:16 -07002292 LayerProtoHelper::writeToProto(mSourceBounds,
2293 [&]() { return layerInfo->mutable_source_bounds(); });
2294 LayerProtoHelper::writeToProto(mScreenBounds,
2295 [&]() { return layerInfo->mutable_screen_bounds(); });
2296 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2297 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2298 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002299}
2300
2301void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002302 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002303 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2304 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002305 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002306
chaviw766c9c52021-02-10 17:36:47 -08002307 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002308
Vishnu Nair00b90132021-11-05 14:03:40 -07002309 layerInfo->set_id(sequence);
2310 layerInfo->set_name(getName().c_str());
2311 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002312
Vishnu Nair00b90132021-11-05 14:03:40 -07002313 for (const auto& child : children) {
2314 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002315 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002316
Vishnu Nair00b90132021-11-05 14:03:40 -07002317 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2318 sp<Layer> strongRelative = weakRelative.promote();
2319 if (strongRelative != nullptr) {
2320 layerInfo->add_relatives(strongRelative->sequence);
2321 }
2322 }
2323
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002324 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002325 [&]() { return layerInfo->mutable_transparent_region(); });
2326
2327 layerInfo->set_layer_stack(getLayerStack().id);
2328 layerInfo->set_z(state.z);
2329
2330 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2331 return layerInfo->mutable_requested_position();
2332 });
2333
Vishnu Nair00b90132021-11-05 14:03:40 -07002334 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2335
2336 layerInfo->set_is_opaque(isOpaque(state));
2337
2338 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2339 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2340 LayerProtoHelper::writeToProto(state.color,
2341 [&]() { return layerInfo->mutable_requested_color(); });
2342 layerInfo->set_flags(state.flags);
2343
2344 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2345 layerInfo->mutable_requested_transform());
2346
2347 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2348 if (parent != nullptr) {
2349 layerInfo->set_parent(parent->sequence);
2350 } else {
2351 layerInfo->set_parent(-1);
2352 }
2353
2354 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2355 if (zOrderRelativeOf != nullptr) {
2356 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2357 } else {
2358 layerInfo->set_z_order_relative_of(-1);
2359 }
2360
2361 layerInfo->set_is_relative_of(state.isRelativeOf);
2362
2363 layerInfo->set_owner_uid(mOwnerUid);
2364
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002365 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002366 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002367 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002368 info = fillInputInfo(
2369 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002370 } else {
2371 info = state.inputInfo;
2372 }
2373
2374 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002375 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002376 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002377
Vishnu Nair00b90132021-11-05 14:03:40 -07002378 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002379 auto protoMap = layerInfo->mutable_metadata();
2380 for (const auto& entry : state.metadata.mMap) {
2381 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2382 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002383 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002384
2385 LayerProtoHelper::writeToProto(state.destinationFrame,
2386 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002387}
2388
Robert Carr2e102c92018-10-23 12:11:15 -07002389bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002390 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002391}
2392
Prabir Pradhan33da9462022-06-14 14:55:57 +00002393// Applies the given transform to the region, while protecting against overflows caused by any
2394// offsets. If applying the offset in the transform to any of the Rects in the region would result
2395// in an overflow, they are not added to the output Region.
2396static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2397 const std::string& debugWindowName) {
2398 // Round the translation using the same rounding strategy used by ui::Transform.
2399 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2400 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2401
2402 ui::Transform transformWithoutOffset = t;
2403 transformWithoutOffset.set(0.f, 0.f);
2404
2405 const Region transformed = transformWithoutOffset.transform(r);
2406
2407 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2408 Region ret;
2409 for (const auto& rect : transformed) {
2410 Rect newRect;
2411 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2412 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2413 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2414 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2415 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2416 debugWindowName.c_str());
2417 continue;
2418 }
2419 ret.orSelf(newRect);
2420 }
2421 return ret;
2422}
2423
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002424void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
2425 Rect tmpBounds = getInputBounds();
2426 if (!tmpBounds.isValid()) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002427 info.touchableRegion.clear();
2428 // A layer could have invalid input bounds and still expect to receive touch input if it has
2429 // replaceTouchableRegionWithCrop. For that case, the input transform needs to be calculated
2430 // correctly to determine the coordinate space for input events. Use an empty rect so that
2431 // the layer will receive input in its own layer space.
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002432 tmpBounds = Rect::EMPTY_RECT;
chaviw7e72caf2020-12-02 16:50:43 -08002433 }
2434
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002435 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2436 // frame and transform used for the layer, which determines the bounds and the coordinate space
2437 // within which the layer will receive input.
2438 //
2439 // The coordinate space within which each of the bounds are specified is explicitly documented
2440 // in the variable name. For example "inputBoundsInLayer" is specified in layer space. A
2441 // Transform converts one coordinate space to another, which is apparent in its naming. For
2442 // example, "layerToDisplay" transforms layer space to display space.
2443 //
2444 // Coordinate space definitions:
2445 // - display: The display device's coordinate space. Correlates to pixels on the display.
2446 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2447 // - layer: The coordinate space of this layer.
2448 // - input: The coordinate space in which this layer will receive input events. This could be
2449 // different than layer space if a surfaceInset is used, which changes the origin
2450 // of the input space.
2451 const FloatRect inputBoundsInLayer = tmpBounds.toFloatRect();
chaviw7e72caf2020-12-02 16:50:43 -08002452
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002453 // Clamp surface inset to the input bounds.
2454 const auto surfaceInset = static_cast<float>(info.surfaceInset);
2455 const float xSurfaceInset =
2456 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getWidth() / 2.f));
2457 const float ySurfaceInset =
2458 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getHeight() / 2.f));
chaviw1ff3d1e2020-07-01 15:53:47 -07002459
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002460 // Apply the insets to the input bounds.
2461 const FloatRect insetBoundsInLayer(inputBoundsInLayer.left + xSurfaceInset,
2462 inputBoundsInLayer.top + ySurfaceInset,
2463 inputBoundsInLayer.right - xSurfaceInset,
2464 inputBoundsInLayer.bottom - ySurfaceInset);
Ady Abraham282f1d72019-07-24 18:05:56 -07002465
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002466 // Crop the input bounds to ensure it is within the parent's bounds.
2467 const FloatRect croppedInsetBoundsInLayer = mBounds.intersect(insetBoundsInLayer);
Ady Abraham282f1d72019-07-24 18:05:56 -07002468
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002469 const ui::Transform layerToScreen = getInputTransform();
2470 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
Vishnu Nair8033a492018-12-05 07:27:23 -08002471
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002472 const Rect roundedFrameInDisplay{layerToDisplay.transform(croppedInsetBoundsInLayer)};
2473 info.frameLeft = roundedFrameInDisplay.left;
2474 info.frameTop = roundedFrameInDisplay.top;
2475 info.frameRight = roundedFrameInDisplay.right;
2476 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002477
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002478 ui::Transform inputToLayer;
2479 inputToLayer.set(insetBoundsInLayer.left, insetBoundsInLayer.top);
2480 const ui::Transform inputToDisplay = layerToDisplay * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002481
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002482 // InputDispatcher expects a display-to-input transform.
2483 info.transform = inputToDisplay.inverse();
2484
2485 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002486 info.touchableRegion =
2487 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002488}
2489
chaviw3277faf2021-05-19 16:45:23 -05002490void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002491 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002492 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002493 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002494 }
2495 if (p != nullptr) {
2496 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2497 }
2498}
2499
Vishnu Naira066d902021-09-13 18:40:17 -07002500gui::DropInputMode Layer::getDropInputMode() const {
2501 gui::DropInputMode mode = mDrawingState.dropInputMode;
2502 if (mode == gui::DropInputMode::ALL) {
2503 return mode;
2504 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002505 sp<Layer> parent = mDrawingParent.promote();
2506 if (parent) {
2507 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002508 if (parentMode != gui::DropInputMode::NONE) {
2509 return parentMode;
2510 }
2511 }
2512 return mode;
2513}
2514
2515void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002516 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002517 return;
2518 }
2519
2520 // Check if we need to drop input unconditionally
2521 gui::DropInputMode dropInputMode = getDropInputMode();
2522 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002523 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002524 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2525 return;
2526 }
2527
2528 // Check if we need to check if the window is obscured by parent
2529 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2530 return;
2531 }
2532
2533 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002534 sp<Layer> parent = mDrawingParent.promote();
2535 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002536 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002537 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2538 static_cast<float>(getAlpha()));
2539 }
2540
2541 // Check if the parent has cropped the buffer
2542 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2543 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002544 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002545 return;
2546 }
2547
2548 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2549 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2550 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2551 // match then the layer has not been cropped by its parents.
2552 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2553 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2554
2555 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002556 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002557 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2558 getDebugName());
2559 } else {
2560 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2561 // input if the window is obscured. This check should be done in surfaceflinger but the
2562 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2563 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002564 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002565 }
2566}
2567
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002568WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002569 if (!hasInputInfo()) {
2570 mDrawingState.inputInfo.name = getName();
2571 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2572 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002573 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002574 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002575 }
2576
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002577 const ui::Transform& displayTransform =
2578 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2579
chaviw3277faf2021-05-19 16:45:23 -05002580 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002581 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002582 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002583
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002584 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002585
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002586 if (displayArgs.transform == nullptr) {
2587 // Do not let the window receive touches if it is not associated with a valid display
2588 // transform. We still allow the window to receive keys and prevent ANRs.
2589 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2590 }
2591
Robert Carr5dc426e2020-06-10 14:29:14 -07002592 // For compatibility reasons we let layers which can receive input
2593 // receive input before they have actually submitted a buffer. Because
2594 // of this we use canReceiveInput instead of isVisible to check the
2595 // policy-visibility, ignoring the buffer state. However for layers with
2596 // hasInputInfo()==false we can use the real visibility state.
2597 // We are just using these layers for occlusion detection in
2598 // InputDispatcher, and obviously if they aren't visible they can't occlude
2599 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002600 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2601 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2602
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002603 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002604 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002605 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002606
Vishnu Nair16a938f2021-09-24 07:14:54 -07002607 // If the window will be blacked out on a display because the display does not have the secure
2608 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002609 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002610 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002611 }
2612
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002613 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2614 if (info.replaceTouchableRegionWithCrop) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002615 const Rect bounds(cropLayer ? cropLayer->mScreenBounds : mScreenBounds);
2616 info.touchableRegion = Region(displayTransform.transform(bounds));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002617 } else if (cropLayer != nullptr) {
[1;3C2b9fc252021-02-04 16:16:50 -08002618 info.touchableRegion = info.touchableRegion.intersect(
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002619 displayTransform.transform(Rect{cropLayer->mScreenBounds}));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002620 }
2621
Winson Chunga30f7c92021-06-29 15:42:56 -07002622 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2623 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002624 if (isTrustedOverlay()) {
2625 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2626 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002627
chaviwaf87b3e2019-10-01 16:59:28 -07002628 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2629 // touches from going outside the cloned area.
2630 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002631 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002632 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2633 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002634 info.touchableRegion = info.touchableRegion.intersect(rect);
2635 }
2636 }
2637
Robert Carr720e5062018-07-30 17:45:14 -07002638 return info;
2639}
2640
chaviwaf87b3e2019-10-01 16:59:28 -07002641sp<Layer> Layer::getClonedRoot() {
2642 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002643 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002644 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002645 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002646 return nullptr;
2647 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002648 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002649}
2650
Robert Carredd13602020-04-13 17:24:34 -07002651bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002652 return mDrawingState.inputInfo.token != nullptr ||
2653 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002654}
2655
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002656compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002657 const DisplayDevice* display) const {
2658 if (!display) return nullptr;
Lloyd Piquede196652020-01-22 17:29:58 -08002659 return display->getCompositionDisplay()->getOutputLayerForLayer(getCompositionEngineLayerFE());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002660}
2661
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002662Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2663 const auto outputLayer = findOutputLayerForDisplay(display);
2664 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002665}
2666
chaviwb4c6e582019-08-16 14:35:07 -07002667void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002668 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002669 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002670 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2671 mPotentialCursor = clonedFrom->mPotentialCursor;
2672 mProtectedByApp = clonedFrom->mProtectedByApp;
2673 updateCloneBufferInfo();
2674}
2675
2676void Layer::updateCloneBufferInfo() {
2677 if (!isClone() || !isClonedFromAlive()) {
2678 return;
2679 }
2680
2681 sp<Layer> clonedFrom = getClonedFrom();
2682 mBufferInfo = clonedFrom->mBufferInfo;
2683 mSidebandStream = clonedFrom->mSidebandStream;
2684 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2685 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2686 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2687
2688 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2689 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2690 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2691 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2692 // the cloned drawingState again.
2693 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2694 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2695 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2696 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2697
2698 cloneDrawingState(clonedFrom.get());
2699
2700 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2701 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2702 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2703 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002704}
chaviw74b03172019-08-19 11:09:03 -07002705
2706void Layer::updateMirrorInfo() {
2707 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2708 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2709 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2710 // that case, we want to delete the reference to the clone since we want it to get
2711 // destroyed. The root, this layer, will still be around since the client can continue
2712 // to hold a reference, but no cloned layers will be displayed.
2713 mClonedChild = nullptr;
2714 return;
2715 }
2716
2717 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2718 // If the real layer exists and is in current state, add the clone as a child of the root.
2719 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2720 // copied to drawingState for the root layer. So the clonedChild is always removed from
2721 // drawingState and then needs to be added back each traversal.
2722 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2723 addChildToDrawing(mClonedChild);
2724 }
2725
2726 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002727 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002728 mClonedChild->updateClonedRelatives(clonedLayersMap);
2729}
2730
2731void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2732 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2733 // to the clone. If the real layer is no longer alive, continue traversing the children
2734 // since we may be able to pull out other children that are still alive.
2735 if (isClonedFromAlive()) {
2736 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002737 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002738 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002739 }
2740
2741 // The clone layer may have children in drawingState since they may have been created and
2742 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2743 // that already exist, since we can just re-use them.
2744 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2745 // not updated in the regular traversal. They are skipped since the root will lose the
2746 // reference to them when it copies its currentChildren to drawing.
2747 for (sp<Layer>& child : mDrawingChildren) {
2748 child->updateClonedDrawingState(clonedLayersMap);
2749 }
2750}
2751
2752void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2753 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2754 mDrawingChildren.clear();
2755
2756 if (!isClonedFromAlive()) {
2757 return;
2758 }
2759
2760 sp<Layer> clonedFrom = getClonedFrom();
2761 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2762 if (child == mirrorRoot) {
2763 // This is to avoid cyclical mirroring.
2764 continue;
2765 }
2766 sp<Layer> clonedChild = clonedLayersMap[child];
2767 if (clonedChild == nullptr) {
2768 clonedChild = child->createClone();
2769 clonedLayersMap[child] = clonedChild;
2770 }
2771 addChildToDrawing(clonedChild);
2772 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2773 }
2774}
2775
chaviwaf87b3e2019-10-01 16:59:28 -07002776void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2777 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2778 if (cropLayer != nullptr) {
2779 if (clonedLayersMap.count(cropLayer) == 0) {
2780 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2781 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002782 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002783 } else {
2784 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2785 mDrawingState.touchableRegionCrop = clonedCropLayer;
2786 }
2787 }
2788 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2789 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002790 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002791}
2792
2793void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002794 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002795 mDrawingState.zOrderRelatives.clear();
2796
2797 if (!isClonedFromAlive()) {
2798 return;
2799 }
2800
chaviwaf87b3e2019-10-01 16:59:28 -07002801 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002802 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002803 const sp<Layer>& relative = relativeWeak.promote();
2804 if (clonedLayersMap.count(relative) > 0) {
2805 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002806 mDrawingState.zOrderRelatives.add(clonedRelative);
2807 }
2808 }
2809
2810 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2811 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2812 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2813 // still traverse the children, but the layer with the missing relativeOf will not be shown
2814 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002815 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2816 if (clonedLayersMap.count(relativeOf) > 0) {
2817 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002818 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2819 }
2820
chaviwaf87b3e2019-10-01 16:59:28 -07002821 updateClonedInputInfo(clonedLayersMap);
2822
chaviw74b03172019-08-19 11:09:03 -07002823 for (sp<Layer>& child : mDrawingChildren) {
2824 child->updateClonedRelatives(clonedLayersMap);
2825 }
2826}
2827
2828void Layer::addChildToDrawing(const sp<Layer>& layer) {
2829 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002830 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002831}
2832
Steven Thomas62a4cf82020-01-31 12:04:03 -08002833Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2834 switch (compatibility) {
2835 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2836 return FrameRateCompatibility::Default;
2837 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2838 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002839 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2840 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002841 case ANATIVEWINDOW_FRAME_RATE_MIN:
2842 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002843 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2844 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002845 default:
2846 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2847 return FrameRateCompatibility::Default;
2848 }
2849}
2850
Marin Shalamanovc5986772021-03-16 16:09:49 +01002851scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2852 switch (strategy) {
2853 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2854 return Seamlessness::OnlySeamless;
2855 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2856 return Seamlessness::SeamedAndSeamless;
2857 default:
2858 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2859 return Seamlessness::Default;
2860 }
2861}
2862
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002863bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002864 const State& s(mDrawingState);
2865 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2866 return true;
2867 }
2868
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002869 sp<Layer> parent = mDrawingParent.promote();
2870 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002871}
2872
Robert Carr6a0382d2021-07-01 15:57:17 -07002873void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2874 mClonedChild = clonedChild;
2875 mHadClonedChild = true;
2876 mFlinger->mNumClones++;
2877}
2878
Vishnu Nairf9096652021-07-20 18:49:42 -07002879const String16 Layer::Handle::kDescriptor = String16("android.Layer.Handle");
2880
2881wp<Layer> Layer::fromHandle(const sp<IBinder>& handleBinder) {
2882 if (handleBinder == nullptr) {
2883 return nullptr;
2884 }
2885
2886 BBinder* b = handleBinder->localBinder();
2887 if (b == nullptr || b->getInterfaceDescriptor() != Handle::kDescriptor) {
2888 return nullptr;
2889 }
2890
2891 // We can safely cast this binder since its local and we verified its interface descriptor.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002892 sp<Handle> handle = sp<Handle>::cast(handleBinder);
Vishnu Nairf9096652021-07-20 18:49:42 -07002893 return handle->owner;
2894}
2895
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002896bool Layer::setDropInputMode(gui::DropInputMode mode) {
2897 if (mDrawingState.dropInputMode == mode) {
2898 return false;
2899 }
2900 mDrawingState.dropInputMode = mode;
2901 return true;
2902}
2903
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002904void Layer::cloneDrawingState(const Layer* from) {
2905 mDrawingState = from->mDrawingState;
2906 // Skip callback info since they are not applicable for cloned layers.
2907 mDrawingState.releaseBufferListener = nullptr;
2908 mDrawingState.callbackHandles = {};
2909}
2910
Patrick Williamsbb25f802022-08-30 23:02:34 +00002911void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2912 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
2913 const sp<Fence>& releaseFence,
2914 uint32_t currentMaxAcquiredBufferCount) {
2915 if (!listener) {
2916 return;
2917 }
2918 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
2919 listener->onReleaseBuffer({buffer->getId(), framenumber},
2920 releaseFence ? releaseFence : Fence::NO_FENCE,
2921 currentMaxAcquiredBufferCount);
2922}
2923
2924void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2925 // If we are displayed on multiple displays in a single composition cycle then we would
2926 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2927 // For example we can only use it if all the displays are client comp, and we need
2928 // to merge all the client comp fences. We could do this, but for now we just
2929 // disable the optimization when a layer is composed on multiple displays.
2930 if (mClearClientCompositionFenceOnLayerDisplayed) {
2931 mLastClientCompositionFence = nullptr;
2932 } else {
2933 mClearClientCompositionFenceOnLayerDisplayed = true;
2934 }
2935
2936 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2937 // buffer that was presented on this layer. The first transaction that came in this frame that
2938 // replaced the previous buffer on this layer needs this release fence, because the fence will
2939 // let the client know when that previous buffer is removed from the screen.
2940 //
2941 // Every other transaction on this layer does not need a release fence because no other
2942 // Transactions that were set on this layer this frame are going to have their preceding buffer
2943 // removed from the display this frame.
2944 //
2945 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2946 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2947 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2948 // the previous buffer will be released this frame. The third transaction also contains a
2949 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2950 // transaction will now no longer be presented so it is released immediately and the third
2951 // transaction doesn't need a previous release fence.
2952 sp<CallbackHandle> ch;
2953 for (auto& handle : mDrawingState.callbackHandles) {
2954 if (handle->releasePreviousBuffer &&
2955 mDrawingState.releaseBufferEndpoint == handle->listener) {
2956 ch = handle;
2957 break;
2958 }
2959 }
2960
2961 // Prevent tracing the same release multiple times.
2962 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2963 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2964 }
2965
2966 if (ch != nullptr) {
2967 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2968 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2969 ch->name = mName;
2970 }
2971}
2972
2973void Layer::onSurfaceFrameCreated(
2974 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Vishnu Nair22491b82022-10-18 14:59:14 -07002975 if (!hasBufferOrSidebandStreamInDrawing()) {
2976 return;
2977 }
2978
Patrick Williamsbb25f802022-08-30 23:02:34 +00002979 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2980 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2981 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2982 // leak.
2983 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2984 mName.c_str());
2985 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2986 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2987 mPendingJankClassifications.pop_front();
2988 }
2989 mPendingJankClassifications.emplace_back(surfaceFrame);
2990}
2991
2992void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2993 for (const auto& handle : mDrawingState.callbackHandles) {
2994 handle->transformHint = mTransformHint;
2995 handle->dequeueReadyTime = dequeueReadyTime;
2996 handle->currentMaxAcquiredBufferCount =
2997 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2998 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2999 handle->previousReleaseCallbackId.framenumber);
3000 }
3001
3002 for (auto& handle : mDrawingState.callbackHandles) {
3003 if (handle->releasePreviousBuffer &&
3004 mDrawingState.releaseBufferEndpoint == handle->listener) {
3005 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
3006 break;
3007 }
3008 }
3009
3010 std::vector<JankData> jankData;
3011 jankData.reserve(mPendingJankClassifications.size());
3012 while (!mPendingJankClassifications.empty() &&
3013 mPendingJankClassifications.front()->getJankType()) {
3014 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
3015 mPendingJankClassifications.front();
3016 mPendingJankClassifications.pop_front();
3017 jankData.emplace_back(
3018 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
3019 }
3020
3021 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
3022 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003023 mDrawingState.callbackHandles = {};
3024}
3025
3026bool Layer::willPresentCurrentTransaction() const {
3027 // Returns true if the most recent Transaction applied to CurrentState will be presented.
3028 return (getSidebandStreamChanged() || getAutoRefresh() ||
3029 (mDrawingState.modified &&
3030 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
3031}
3032
3033bool Layer::setTransform(uint32_t transform) {
3034 if (mDrawingState.bufferTransform == transform) return false;
3035 mDrawingState.bufferTransform = transform;
3036 mDrawingState.modified = true;
3037 setTransactionFlags(eTransactionNeeded);
3038 return true;
3039}
3040
3041bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
3042 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
3043 mDrawingState.sequence++;
3044 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
3045 mDrawingState.modified = true;
3046 setTransactionFlags(eTransactionNeeded);
3047 return true;
3048}
3049
3050bool Layer::setBufferCrop(const Rect& bufferCrop) {
3051 if (mDrawingState.bufferCrop == bufferCrop) return false;
3052
3053 mDrawingState.sequence++;
3054 mDrawingState.bufferCrop = bufferCrop;
3055
3056 mDrawingState.modified = true;
3057 setTransactionFlags(eTransactionNeeded);
3058 return true;
3059}
3060
3061bool Layer::setDestinationFrame(const Rect& destinationFrame) {
3062 if (mDrawingState.destinationFrame == destinationFrame) return false;
3063
3064 mDrawingState.sequence++;
3065 mDrawingState.destinationFrame = destinationFrame;
3066
3067 mDrawingState.modified = true;
3068 setTransactionFlags(eTransactionNeeded);
3069 return true;
3070}
3071
3072// Translate destination frame into scale and position. If a destination frame is not set, use the
3073// provided scale and position
3074bool Layer::updateGeometry() {
3075 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
3076 mDrawingState.destinationFrame.isEmpty()) {
3077 // If destination frame is not set, use the requested transform set via
3078 // Layer::setPosition and Layer::setMatrix.
3079 return assignTransform(&mDrawingState.transform, mRequestedTransform);
3080 }
3081
3082 Rect destRect = mDrawingState.destinationFrame;
3083 int32_t destW = destRect.width();
3084 int32_t destH = destRect.height();
3085 if (destRect.left < 0) {
3086 destRect.left = 0;
3087 destRect.right = destW;
3088 }
3089 if (destRect.top < 0) {
3090 destRect.top = 0;
3091 destRect.bottom = destH;
3092 }
3093
3094 if (!mDrawingState.buffer) {
3095 ui::Transform t;
3096 t.set(destRect.left, destRect.top);
3097 return assignTransform(&mDrawingState.transform, t);
3098 }
3099
3100 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3101 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3102 // Undo any transformations on the buffer.
3103 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3104 std::swap(bufferWidth, bufferHeight);
3105 }
3106 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3107 if (mDrawingState.transformToDisplayInverse) {
3108 if (invTransform & ui::Transform::ROT_90) {
3109 std::swap(bufferWidth, bufferHeight);
3110 }
3111 }
3112
3113 float sx = destW / static_cast<float>(bufferWidth);
3114 float sy = destH / static_cast<float>(bufferHeight);
3115 ui::Transform t;
3116 t.set(sx, 0, 0, sy);
3117 t.set(destRect.left, destRect.top);
3118 return assignTransform(&mDrawingState.transform, t);
3119}
3120
3121bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3122 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3123 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3124 return false;
3125 }
3126
3127 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3128
3129 mDrawingState.sequence++;
3130 mDrawingState.modified = true;
3131 setTransactionFlags(eTransactionNeeded);
3132
3133 return true;
3134}
3135
3136bool Layer::setPosition(float x, float y) {
3137 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3138 return false;
3139 }
3140
3141 mRequestedTransform.set(x, y);
3142
3143 mDrawingState.sequence++;
3144 mDrawingState.modified = true;
3145 setTransactionFlags(eTransactionNeeded);
3146
3147 return true;
3148}
3149
3150bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3151 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3152 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
3153 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003154 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003155 if (!buffer) {
3156 return false;
3157 }
3158
3159 const bool frameNumberChanged =
3160 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3161 const uint64_t frameNumber =
3162 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003163 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003164
3165 if (mDrawingState.buffer) {
3166 mReleasePreviousBuffer = true;
3167 if (!mBufferInfo.mBuffer ||
3168 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3169 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3170 // If mDrawingState has a buffer, and we are about to update again
3171 // before swapping to drawing state, then the first buffer will be
3172 // dropped and we should decrement the pending buffer count and
3173 // call any release buffer callbacks if set.
3174 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3175 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3176 mDrawingState.acquireFence,
3177 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
3178 mOwnerUid));
3179 decrementPendingBufferCount();
3180 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3181 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3182 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
3183 mDrawingState.bufferSurfaceFrameTX.reset();
3184 }
3185 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3186 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3187 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3188 mLastClientCompositionFence,
3189 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
3190 mOwnerUid));
3191 mLastClientCompositionFence = nullptr;
3192 }
3193 }
3194
3195 mDrawingState.frameNumber = frameNumber;
3196 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3197 mDrawingState.buffer = std::move(buffer);
3198 mDrawingState.clientCacheId = bufferData.cachedBuffer;
3199
3200 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3201 ? bufferData.acquireFence
3202 : Fence::NO_FENCE;
3203 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3204 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3205 // We latched this buffer unsiganled, so we need to pass the acquire fence
3206 // on the callback instead of just the acquire time, since it's unknown at
3207 // this point.
3208 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3209 } else {
3210 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3211 }
3212
3213 mDrawingState.modified = true;
3214 setTransactionFlags(eTransactionNeeded);
3215
3216 const int32_t layerId = getSequence();
3217 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3218 mOwnerUid, postTime, getGameMode());
3219 mDrawingState.desiredPresentTime = desiredPresentTime;
3220 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3221
3222 const nsecs_t presentTime = [&] {
3223 if (!isAutoTimestamp) return desiredPresentTime;
3224
3225 const auto prediction =
3226 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
3227 if (prediction.has_value()) return prediction->presentTime;
3228
3229 return static_cast<nsecs_t>(0);
3230 }();
3231
3232 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
3233 mFlinger->mScheduler->recordLayerHistory(this, presentTime, LayerUpdateType::Buffer);
3234
3235 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3236
3237 if (dequeueTime && *dequeueTime != 0) {
3238 const uint64_t bufferId = mDrawingState.buffer->getId();
3239 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3240 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3241 FrameTracer::FrameEvent::DEQUEUE);
3242 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3243 FrameTracer::FrameEvent::QUEUE);
3244 }
3245
3246 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3247 return true;
3248}
3249
3250bool Layer::setDataspace(ui::Dataspace dataspace) {
3251 mDrawingState.dataspaceRequested = true;
3252 if (mDrawingState.dataspace == dataspace) return false;
3253 mDrawingState.dataspace = dataspace;
3254 mDrawingState.modified = true;
3255 setTransactionFlags(eTransactionNeeded);
3256 return true;
3257}
3258
3259bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3260 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3261 mDrawingState.hdrMetadata = hdrMetadata;
3262 mDrawingState.modified = true;
3263 setTransactionFlags(eTransactionNeeded);
3264 return true;
3265}
3266
3267bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
3268 mDrawingState.surfaceDamageRegion = surfaceDamage;
3269 mDrawingState.modified = true;
3270 setTransactionFlags(eTransactionNeeded);
3271 return true;
3272}
3273
3274bool Layer::setApi(int32_t api) {
3275 if (mDrawingState.api == api) return false;
3276 mDrawingState.api = api;
3277 mDrawingState.modified = true;
3278 setTransactionFlags(eTransactionNeeded);
3279 return true;
3280}
3281
3282bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3283 if (mDrawingState.sidebandStream == sidebandStream) return false;
3284
3285 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3286 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3287 } else if (sidebandStream != nullptr) {
3288 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3289 }
3290
3291 mDrawingState.sidebandStream = sidebandStream;
3292 mDrawingState.modified = true;
3293 setTransactionFlags(eTransactionNeeded);
3294 if (!mSidebandStreamChanged.exchange(true)) {
3295 // mSidebandStreamChanged was false
3296 mFlinger->onLayerUpdate();
3297 }
3298 return true;
3299}
3300
3301bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles) {
3302 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3303 if (handles.empty()) {
3304 mReleasePreviousBuffer = false;
3305 return false;
3306 }
3307
3308 const bool willPresent = willPresentCurrentTransaction();
3309
3310 for (const auto& handle : handles) {
3311 // If this transaction set a buffer on this layer, release its previous buffer
3312 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3313
3314 // If this layer will be presented in this frame
3315 if (willPresent) {
3316 // If this transaction set an acquire fence on this layer, set its acquire time
3317 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3318 handle->frameNumber = mDrawingState.frameNumber;
3319
3320 // Store so latched time and release fence can be set
3321 mDrawingState.callbackHandles.push_back(handle);
3322
3323 } else { // If this layer will NOT need to be relatched and presented this frame
3324 // Notify the transaction completed thread this handle is done
3325 mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
3326 }
3327 }
3328
3329 mReleasePreviousBuffer = false;
3330 mCallbackHandleAcquireTimeOrFence = -1;
3331
3332 return willPresent;
3333}
3334
3335Rect Layer::getBufferSize(const State& /*s*/) const {
3336 // for buffer state layers we use the display frame size as the buffer size.
3337
3338 if (mBufferInfo.mBuffer == nullptr) {
3339 return Rect::INVALID_RECT;
3340 }
3341
3342 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3343 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3344
3345 // Undo any transformations on the buffer and return the result.
3346 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3347 std::swap(bufWidth, bufHeight);
3348 }
3349
3350 if (getTransformToDisplayInverse()) {
3351 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3352 if (invTransform & ui::Transform::ROT_90) {
3353 std::swap(bufWidth, bufHeight);
3354 }
3355 }
3356
3357 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3358}
3359
3360FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3361 if (mBufferInfo.mBuffer == nullptr) {
3362 return parentBounds;
3363 }
3364
3365 return getBufferSize(getDrawingState()).toFloatRect();
3366}
3367
3368bool Layer::fenceHasSignaled() const {
3369 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3370 return true;
3371 }
3372
3373 const bool fenceSignaled =
3374 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3375 if (!fenceSignaled) {
3376 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3377 TimeStats::LatchSkipReason::LateAcquire);
3378 }
3379
3380 return fenceSignaled;
3381}
3382
Vishnu Nairba354102022-08-01 00:14:18 +00003383bool Layer::onPreComposition(nsecs_t refreshStartTime, bool /* updatingOutputGeometryThisFrame */) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003384 for (const auto& handle : mDrawingState.callbackHandles) {
3385 handle->refreshStartTime = refreshStartTime;
3386 }
3387 return hasReadyFrame();
3388}
3389
3390void Layer::setAutoRefresh(bool autoRefresh) {
3391 mDrawingState.autoRefresh = autoRefresh;
3392}
3393
3394bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3395 // We need to update the sideband stream if the layer has both a buffer and a sideband stream.
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003396 auto* snapshot = editLayerSnapshot();
3397 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003398
3399 if (mSidebandStreamChanged.exchange(false)) {
3400 const State& s(getDrawingState());
3401 // mSidebandStreamChanged was true
3402 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003403 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003404 if (mSidebandStream != nullptr) {
3405 setTransactionFlags(eTransactionNeeded);
3406 mFlinger->setTransactionFlags(eTraversalNeeded);
3407 }
3408 recomputeVisibleRegions = true;
3409
3410 return true;
3411 }
3412 return false;
3413}
3414
3415bool Layer::hasFrameUpdate() const {
3416 const State& c(getDrawingState());
3417 return (mDrawingStateModified || mDrawingState.modified) &&
3418 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3419}
3420
3421void Layer::updateTexImage(nsecs_t latchTime) {
3422 const State& s(getDrawingState());
3423
3424 if (!s.buffer) {
3425 if (s.bgColorLayer) {
3426 for (auto& handle : mDrawingState.callbackHandles) {
3427 handle->latchTime = latchTime;
3428 }
3429 }
3430 return;
3431 }
3432
3433 for (auto& handle : mDrawingState.callbackHandles) {
3434 if (handle->frameNumber == mDrawingState.frameNumber) {
3435 handle->latchTime = latchTime;
3436 }
3437 }
3438
3439 const int32_t layerId = getSequence();
3440 const uint64_t bufferId = mDrawingState.buffer->getId();
3441 const uint64_t frameNumber = mDrawingState.frameNumber;
3442 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3443 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3444 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3445
3446 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3447 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3448 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3449 FrameTracer::FrameEvent::LATCH);
3450
3451 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3452 if (bufferSurfaceFrame != nullptr &&
3453 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3454 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3455 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3456 // are processing the next state.
3457 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3458 mDrawingState.acquireFenceTime->getSignalTime(),
3459 latchTime);
3460 mDrawingState.bufferSurfaceFrameTX.reset();
3461 }
3462
3463 std::deque<sp<CallbackHandle>> remainingHandles;
3464 mFlinger->getTransactionCallbackInvoker()
3465 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3466 mDrawingState.callbackHandles = remainingHandles;
3467
3468 mDrawingStateModified = false;
3469}
3470
3471void Layer::gatherBufferInfo() {
3472 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3473 decrementPendingBufferCount();
3474 }
3475
3476 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3477 mBufferInfo.mBuffer = mDrawingState.buffer;
3478 mBufferInfo.mFence = mDrawingState.acquireFence;
3479 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3480 mBufferInfo.mPixelFormat =
3481 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3482 mBufferInfo.mFrameLatencyNeeded = true;
3483 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3484 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3485 mBufferInfo.mFence = mDrawingState.acquireFence;
3486 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3487 auto lastDataspace = mBufferInfo.mDataspace;
3488 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3489 if (lastDataspace != mBufferInfo.mDataspace) {
3490 mFlinger->mSomeDataspaceChanged = true;
3491 }
3492 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3493 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3494 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3495 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3496 mBufferInfo.mApi = mDrawingState.api;
3497 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
3498 mBufferInfo.mBufferSlot = mHwcSlotGenerator->getHwcCacheSlot(mDrawingState.clientCacheId);
3499}
3500
3501Rect Layer::computeBufferCrop(const State& s) {
3502 if (s.buffer && !s.bufferCrop.isEmpty()) {
3503 Rect bufferCrop;
3504 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3505 return bufferCrop;
3506 } else if (s.buffer) {
3507 return s.buffer->getBounds();
3508 } else {
3509 return s.bufferCrop;
3510 }
3511}
3512
3513sp<Layer> Layer::createClone() {
3514 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3515 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003516 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003517 layer->mHwcSlotGenerator = mHwcSlotGenerator;
3518 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3519 return layer;
3520}
3521
3522bool Layer::bufferNeedsFiltering() const {
3523 const State& s(getDrawingState());
3524 if (!s.buffer) {
3525 return false;
3526 }
3527
3528 int32_t bufferWidth = static_cast<int32_t>(s.buffer->getWidth());
3529 int32_t bufferHeight = static_cast<int32_t>(s.buffer->getHeight());
3530
3531 // Undo any transformations on the buffer and return the result.
3532 if (s.bufferTransform & ui::Transform::ROT_90) {
3533 std::swap(bufferWidth, bufferHeight);
3534 }
3535
3536 if (s.transformToDisplayInverse) {
3537 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3538 if (invTransform & ui::Transform::ROT_90) {
3539 std::swap(bufferWidth, bufferHeight);
3540 }
3541 }
3542
3543 const Rect layerSize{getBounds()};
3544 int32_t layerWidth = layerSize.getWidth();
3545 int32_t layerHeight = layerSize.getHeight();
3546
3547 // Align the layer orientation with the buffer before comparism
3548 if (mTransformHint & ui::Transform::ROT_90) {
3549 std::swap(layerWidth, layerHeight);
3550 }
3551
3552 return layerWidth != bufferWidth || layerHeight != bufferHeight;
3553}
3554
3555void Layer::decrementPendingBufferCount() {
3556 int32_t pendingBuffers = --mPendingBufferTransactions;
3557 tracePendingBufferCount(pendingBuffers);
3558}
3559
3560void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3561 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3562}
3563
3564/*
3565 * We don't want to send the layer's transform to input, but rather the
3566 * parent's transform. This is because Layer's transform is
3567 * information about how the buffer is placed on screen. The parent's
3568 * transform makes more sense to send since it's information about how the
3569 * layer is placed on screen. This transform is used by input to determine
3570 * how to go from screen space back to window space.
3571 */
3572ui::Transform Layer::getInputTransform() const {
3573 if (!hasBufferOrSidebandStream()) {
3574 return getTransform();
3575 }
3576 sp<Layer> parent = mDrawingParent.promote();
3577 if (parent == nullptr) {
3578 return ui::Transform();
3579 }
3580
3581 return parent->getTransform();
3582}
3583
3584/**
3585 * Similar to getInputTransform, we need to update the bounds to include the transform.
3586 * This is because bounds don't include the buffer transform, where the input assumes
3587 * that's already included.
3588 */
3589Rect Layer::getInputBounds() const {
3590 if (!hasBufferOrSidebandStream()) {
3591 return getCroppedBufferSize(getDrawingState());
3592 }
3593
3594 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
3595 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
3596 return bufferBounds;
3597 }
3598 return mDrawingState.transform.transform(bufferBounds);
3599}
3600
3601bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3602 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3603
3604 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3605 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3606 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3607 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3608 layer_state_t::eReparent;
3609
3610 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3611 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3612 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3613 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3614 layer_state_t::eInputInfoChanged;
3615
3616 if ((s.what & requiredFlags) != requiredFlags) {
3617 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3618 (s.what | requiredFlags) & ~s.what);
3619 return false;
3620 }
3621
3622 if (s.what & deniedFlags) {
3623 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3624 return false;
3625 }
3626
3627 if (s.what & allowedFlags) {
3628 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3629 }
3630
3631 if (s.what & layer_state_t::ePositionChanged) {
3632 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3633 ALOGV("%s: false [ePositionChanged changed]", __func__);
3634 return false;
3635 }
3636 }
3637
3638 if (s.what & layer_state_t::eAlphaChanged) {
3639 if (mDrawingState.color.a != s.alpha) {
3640 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3641 return false;
3642 }
3643 }
3644
3645 if (s.what & layer_state_t::eColorTransformChanged) {
3646 if (mDrawingState.colorTransform != s.colorTransform) {
3647 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3648 return false;
3649 }
3650 }
3651
3652 if (s.what & layer_state_t::eBackgroundColorChanged) {
3653 if (mDrawingState.bgColorLayer || s.bgColorAlpha != 0) {
3654 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3655 return false;
3656 }
3657 }
3658
3659 if (s.what & layer_state_t::eMatrixChanged) {
3660 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3661 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3662 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3663 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3664 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3665 return false;
3666 }
3667 }
3668
3669 if (s.what & layer_state_t::eCornerRadiusChanged) {
3670 if (mDrawingState.cornerRadius != s.cornerRadius) {
3671 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3672 return false;
3673 }
3674 }
3675
3676 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3677 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3678 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3679 return false;
3680 }
3681 }
3682
3683 if (s.what & layer_state_t::eTransformChanged) {
3684 if (mDrawingState.bufferTransform != s.transform) {
3685 ALOGV("%s: false [eTransformChanged changed]", __func__);
3686 return false;
3687 }
3688 }
3689
3690 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3691 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3692 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3693 return false;
3694 }
3695 }
3696
3697 if (s.what & layer_state_t::eCropChanged) {
3698 if (mDrawingState.crop != s.crop) {
3699 ALOGV("%s: false [eCropChanged changed]", __func__);
3700 return false;
3701 }
3702 }
3703
3704 if (s.what & layer_state_t::eDataspaceChanged) {
3705 if (mDrawingState.dataspace != s.dataspace) {
3706 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3707 return false;
3708 }
3709 }
3710
3711 if (s.what & layer_state_t::eHdrMetadataChanged) {
3712 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3713 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3714 return false;
3715 }
3716 }
3717
3718 if (s.what & layer_state_t::eSidebandStreamChanged) {
3719 if (mDrawingState.sidebandStream != s.sidebandStream) {
3720 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3721 return false;
3722 }
3723 }
3724
3725 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3726 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3727 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3728 return false;
3729 }
3730 }
3731
3732 if (s.what & layer_state_t::eShadowRadiusChanged) {
3733 if (mDrawingState.shadowRadius != s.shadowRadius) {
3734 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3735 return false;
3736 }
3737 }
3738
3739 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3740 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3741 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3742 return false;
3743 }
3744 }
3745
3746 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3747 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3748 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3749 return false;
3750 }
3751 }
3752
3753 if (s.what & layer_state_t::eStretchChanged) {
3754 StretchEffect temp = s.stretchEffect;
3755 temp.sanitize();
3756 if (mDrawingState.stretchEffect != temp) {
3757 ALOGV("%s: false [eStretchChanged changed]", __func__);
3758 return false;
3759 }
3760 }
3761
3762 if (s.what & layer_state_t::eBufferCropChanged) {
3763 if (mDrawingState.bufferCrop != s.bufferCrop) {
3764 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3765 return false;
3766 }
3767 }
3768
3769 if (s.what & layer_state_t::eDestinationFrameChanged) {
3770 if (mDrawingState.destinationFrame != s.destinationFrame) {
3771 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3772 return false;
3773 }
3774 }
3775
3776 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3777 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3778 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3779 return false;
3780 }
3781 }
3782
3783 ALOGV("%s: true", __func__);
3784 return true;
3785}
3786
3787bool Layer::isHdrY410() const {
3788 // pixel format is HDR Y410 masquerading as RGBA_1010102
3789 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3790 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3791 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3792}
3793
3794sp<compositionengine::LayerFE> Layer::getCompositionEngineLayerFE() const {
3795 // There's no need to get a CE Layer if the layer isn't going to draw anything.
3796 if (hasSomethingToDraw()) {
3797 return asLayerFE();
3798 } else {
3799 return nullptr;
3800 }
3801}
3802
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003803const Layer::LayerSnapshot* Layer::getLayerSnapshot() const {
3804 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003805}
3806
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003807Layer::LayerSnapshot* Layer::editLayerSnapshot() {
3808 return mSnapshot.get();
3809}
Patrick Williamsbb25f802022-08-30 23:02:34 +00003810const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003811 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003812}
3813
3814void Layer::useSurfaceDamage() {
3815 if (mFlinger->mForceFullDamage) {
3816 surfaceDamageRegion = Region::INVALID_REGION;
3817 } else {
3818 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3819 }
3820}
3821
3822void Layer::useEmptyDamage() {
3823 surfaceDamageRegion.clear();
3824}
3825
3826bool Layer::isOpaque(const Layer::State& s) const {
3827 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3828 // layer's opaque flag.
3829 if (!hasSomethingToDraw()) {
3830 return false;
3831 }
3832
3833 // if the layer has the opaque flag, then we're always opaque
3834 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3835 return true;
3836 }
3837
3838 // If the buffer has no alpha channel, then we are opaque
3839 if (hasBufferOrSidebandStream() && isOpaqueFormat(getPixelFormat())) {
3840 return true;
3841 }
3842
3843 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3844 return fillsColor() && getAlpha() == 1.0_hf;
3845}
3846
3847bool Layer::canReceiveInput() const {
3848 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3849}
3850
3851bool Layer::isVisible() const {
3852 if (!hasSomethingToDraw()) {
3853 return false;
3854 }
3855
3856 if (isHiddenByPolicy()) {
3857 return false;
3858 }
3859
3860 return getAlpha() > 0.0f || hasBlur();
3861}
3862
3863void Layer::onPostComposition(const DisplayDevice* display,
3864 const std::shared_ptr<FenceTime>& glDoneFence,
3865 const std::shared_ptr<FenceTime>& presentFence,
3866 const CompositorTiming& compositorTiming) {
3867 // mFrameLatencyNeeded is true when a new frame was latched for the
3868 // composition.
3869 if (!mBufferInfo.mFrameLatencyNeeded) return;
3870
3871 for (const auto& handle : mDrawingState.callbackHandles) {
3872 handle->gpuCompositionDoneFence = glDoneFence;
3873 handle->compositorTiming = compositorTiming;
3874 }
3875
3876 // Update mFrameTracker.
3877 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3878 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3879
3880 const int32_t layerId = getSequence();
3881 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3882
3883 const auto outputLayer = findOutputLayerForDisplay(display);
3884 if (outputLayer && outputLayer->requiresClientComposition()) {
3885 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3886 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3887 clientCompositionTimestamp,
3888 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3889 // Update the SurfaceFrames in the drawing state
3890 if (mDrawingState.bufferSurfaceFrameTX) {
3891 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3892 }
3893 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3894 surfaceFrame->setGpuComposition();
3895 }
3896 }
3897
3898 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3899 if (frameReadyFence->isValid()) {
3900 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3901 } else {
3902 // There was no fence for this frame, so assume that it was ready
3903 // to be presented at the desired present time.
3904 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3905 }
3906
3907 if (display) {
Dominik Laskowskif8734e02022-08-26 09:06:59 -07003908 const Fps refreshRate = display->refreshRateConfigs().getActiveModePtr()->getFps();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003909 const std::optional<Fps> renderRate =
3910 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3911
3912 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3913 const auto gameMode = getGameMode();
3914
3915 if (presentFence->isValid()) {
3916 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3917 refreshRate, renderRate, vote, gameMode);
3918 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3919 presentFence,
3920 FrameTracer::FrameEvent::PRESENT_FENCE);
3921 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3922 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3923 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003924 // The HWC doesn't support present fences, so use the present timestamp instead.
3925 const nsecs_t presentTimestamp =
3926 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3927
3928 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3929 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3930 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3931
Patrick Williamsbb25f802022-08-30 23:02:34 +00003932 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3933 refreshRate, renderRate, vote, gameMode);
3934 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3935 mCurrentFrameNumber, actualPresentTime,
3936 FrameTracer::FrameEvent::PRESENT_FENCE);
3937 mFrameTracker.setActualPresentTime(actualPresentTime);
3938 }
3939 }
3940
3941 mFrameTracker.advanceFrame();
3942 mBufferInfo.mFrameLatencyNeeded = false;
3943}
3944
3945bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
3946 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3947 getDrawingState().frameNumber);
3948
3949 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3950
3951 if (refreshRequired) {
3952 return refreshRequired;
3953 }
3954
3955 // If the head buffer's acquire fence hasn't signaled yet, return and
3956 // try again later
3957 if (!fenceHasSignaled()) {
3958 ATRACE_NAME("!fenceHasSignaled()");
3959 mFlinger->onLayerUpdate();
3960 return false;
3961 }
3962
3963 updateTexImage(latchTime);
3964 if (mDrawingState.buffer == nullptr) {
3965 return false;
3966 }
3967
3968 // Capture the old state of the layer for comparisons later
3969 BufferInfo oldBufferInfo = mBufferInfo;
3970 const bool oldOpacity = isOpaque(mDrawingState);
3971 mPreviousFrameNumber = mCurrentFrameNumber;
3972 mCurrentFrameNumber = mDrawingState.frameNumber;
3973 gatherBufferInfo();
3974
3975 if (oldBufferInfo.mBuffer == nullptr) {
3976 // the first time we receive a buffer, we need to trigger a
3977 // geometry invalidation.
3978 recomputeVisibleRegions = true;
3979 }
3980
3981 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3982 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3983 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3984 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3985 recomputeVisibleRegions = true;
3986 }
3987
3988 if (oldBufferInfo.mBuffer != nullptr) {
3989 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3990 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3991 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3992 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3993 recomputeVisibleRegions = true;
3994 }
3995 }
3996
3997 if (oldOpacity != isOpaque(mDrawingState)) {
3998 recomputeVisibleRegions = true;
3999 }
4000
4001 return true;
4002}
4003
4004bool Layer::hasReadyFrame() const {
4005 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4006}
4007
4008bool Layer::isProtected() const {
4009 return (mBufferInfo.mBuffer != nullptr) &&
4010 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4011}
4012
4013// As documented in libhardware header, formats in the range
4014// 0x100 - 0x1FF are specific to the HAL implementation, and
4015// are known to have no alpha channel
4016// TODO: move definition for device-specific range into
4017// hardware.h, instead of using hard-coded values here.
4018#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
4019
4020bool Layer::isOpaqueFormat(PixelFormat format) {
4021 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
4022 return true;
4023 }
4024 switch (format) {
4025 case PIXEL_FORMAT_RGBA_8888:
4026 case PIXEL_FORMAT_BGRA_8888:
4027 case PIXEL_FORMAT_RGBA_FP16:
4028 case PIXEL_FORMAT_RGBA_1010102:
4029 case PIXEL_FORMAT_R_8:
4030 return false;
4031 }
4032 // in all other case, we have no blending (also for unknown formats)
4033 return true;
4034}
4035
4036bool Layer::needsFiltering(const DisplayDevice* display) const {
4037 if (!hasBufferOrSidebandStream()) {
4038 return false;
4039 }
4040 const auto outputLayer = findOutputLayerForDisplay(display);
4041 if (outputLayer == nullptr) {
4042 return false;
4043 }
4044
4045 // We need filtering if the sourceCrop rectangle size does not match the
4046 // displayframe rectangle size (not a 1:1 render)
4047 const auto& compositionState = outputLayer->getState();
4048 const auto displayFrame = compositionState.displayFrame;
4049 const auto sourceCrop = compositionState.sourceCrop;
4050 return sourceCrop.getHeight() != displayFrame.getHeight() ||
4051 sourceCrop.getWidth() != displayFrame.getWidth();
4052}
4053
4054bool Layer::needsFilteringForScreenshots(const DisplayDevice* display,
4055 const ui::Transform& inverseParentTransform) const {
4056 if (!hasBufferOrSidebandStream()) {
4057 return false;
4058 }
4059 const auto outputLayer = findOutputLayerForDisplay(display);
4060 if (outputLayer == nullptr) {
4061 return false;
4062 }
4063
4064 // We need filtering if the sourceCrop rectangle size does not match the
4065 // viewport rectangle size (not a 1:1 render)
4066 const auto& compositionState = outputLayer->getState();
4067 const ui::Transform& displayTransform = display->getTransform();
4068 const ui::Transform inverseTransform = inverseParentTransform * displayTransform.inverse();
4069 // Undo the transformation of the displayFrame so that we're back into
4070 // layer-stack space.
4071 const Rect frame = inverseTransform.transform(compositionState.displayFrame);
4072 const FloatRect sourceCrop = compositionState.sourceCrop;
4073
4074 int32_t frameHeight = frame.getHeight();
4075 int32_t frameWidth = frame.getWidth();
4076 // If the display transform had a rotational component then undo the
4077 // rotation so that the orientation matches the source crop.
4078 if (displayTransform.getOrientation() & ui::Transform::ROT_90) {
4079 std::swap(frameHeight, frameWidth);
4080 }
4081 return sourceCrop.getHeight() != frameHeight || sourceCrop.getWidth() != frameWidth;
4082}
4083
4084void Layer::latchAndReleaseBuffer() {
4085 if (hasReadyFrame()) {
4086 bool ignored = false;
4087 latchBuffer(ignored, systemTime());
4088 }
4089 releasePendingBuffer(systemTime());
4090}
4091
4092PixelFormat Layer::getPixelFormat() const {
4093 return mBufferInfo.mPixelFormat;
4094}
4095
4096bool Layer::getTransformToDisplayInverse() const {
4097 return mBufferInfo.mTransformToDisplayInverse;
4098}
4099
4100Rect Layer::getBufferCrop() const {
4101 // this is the crop rectangle that applies to the buffer
4102 // itself (as opposed to the window)
4103 if (!mBufferInfo.mCrop.isEmpty()) {
4104 // if the buffer crop is defined, we use that
4105 return mBufferInfo.mCrop;
4106 } else if (mBufferInfo.mBuffer != nullptr) {
4107 // otherwise we use the whole buffer
4108 return mBufferInfo.mBuffer->getBounds();
4109 } else {
4110 // if we don't have a buffer yet, we use an empty/invalid crop
4111 return Rect();
4112 }
4113}
4114
4115uint32_t Layer::getBufferTransform() const {
4116 return mBufferInfo.mTransform;
4117}
4118
4119ui::Dataspace Layer::getDataSpace() const {
4120 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
4121}
4122
4123ui::Dataspace Layer::getRequestedDataSpace() const {
4124 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4125}
4126
4127ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4128 ui::Dataspace updatedDataspace = dataspace;
4129 // translate legacy dataspaces to modern dataspaces
4130 switch (dataspace) {
4131 case ui::Dataspace::SRGB:
4132 updatedDataspace = ui::Dataspace::V0_SRGB;
4133 break;
4134 case ui::Dataspace::SRGB_LINEAR:
4135 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4136 break;
4137 case ui::Dataspace::JFIF:
4138 updatedDataspace = ui::Dataspace::V0_JFIF;
4139 break;
4140 case ui::Dataspace::BT601_625:
4141 updatedDataspace = ui::Dataspace::V0_BT601_625;
4142 break;
4143 case ui::Dataspace::BT601_525:
4144 updatedDataspace = ui::Dataspace::V0_BT601_525;
4145 break;
4146 case ui::Dataspace::BT709:
4147 updatedDataspace = ui::Dataspace::V0_BT709;
4148 break;
4149 default:
4150 break;
4151 }
4152
4153 return updatedDataspace;
4154}
4155
4156sp<GraphicBuffer> Layer::getBuffer() const {
4157 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4158}
4159
4160void Layer::getDrawingTransformMatrix(bool filteringEnabled, float outMatrix[16]) const {
4161 sp<GraphicBuffer> buffer = getBuffer();
4162 if (!buffer) {
4163 ALOGE("Buffer should not be null!");
4164 return;
4165 }
4166 GLConsumer::computeTransformMatrix(outMatrix, buffer->getWidth(), buffer->getHeight(),
4167 buffer->getPixelFormat(), mBufferInfo.mCrop,
4168 mBufferInfo.mTransform, filteringEnabled);
4169}
4170
4171void Layer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
4172 mTransformHint = getFixedTransformHint();
4173 if (mTransformHint == ui::Transform::ROT_INVALID) {
4174 mTransformHint = displayTransformHint;
4175 }
4176}
4177
4178const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4179 return mBufferInfo.mBuffer;
4180}
4181
4182bool Layer::setColor(const half3& color) {
4183 if (mDrawingState.color.r == color.r && mDrawingState.color.g == color.g &&
4184 mDrawingState.color.b == color.b) {
4185 return false;
4186 }
4187
4188 mDrawingState.sequence++;
4189 mDrawingState.color.r = color.r;
4190 mDrawingState.color.g = color.g;
4191 mDrawingState.color.b = color.b;
4192 mDrawingState.modified = true;
4193 setTransactionFlags(eTransactionNeeded);
4194 return true;
4195}
4196
4197bool Layer::fillsColor() const {
4198 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4199 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4200}
4201
4202bool Layer::hasBlur() const {
4203 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4204}
4205
Vishnu Nairba354102022-08-01 00:14:18 +00004206void Layer::updateSnapshot(bool updateGeometry) {
4207 if (!getCompositionEngineLayerFE()) {
4208 return;
4209 }
4210
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004211 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004212 if (updateGeometry) {
4213 prepareBasicGeometryCompositionState();
4214 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004215 snapshot->roundedCorner = getRoundedCornerState();
4216 snapshot->stretchEffect = getStretchEffect();
4217 snapshot->transformedBounds = mScreenBounds;
4218 if (mEffectiveShadowRadius > 0.f) {
4219 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4220
4221 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4222 // it if transparent regions are present. This may not be necessary since shadows are
4223 // typically cast by layers without transparent regions.
4224 snapshot->shadowSettings.boundaries = mBounds;
4225
4226 const float casterAlpha = snapshot->alpha;
4227 const bool casterIsOpaque =
4228 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4229
4230 // If the casting layer is translucent, we need to fill in the shadow underneath the
4231 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4232 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4233 snapshot->shadowSettings.ambientColor *= casterAlpha;
4234 snapshot->shadowSettings.spotColor *= casterAlpha;
4235 }
4236 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004237 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004238 snapshot->contentOpaque = isOpaque(mDrawingState);
4239 snapshot->isHdrY410 = isHdrY410();
4240 snapshot->bufferNeedsFiltering = bufferNeedsFiltering();
4241 sp<Layer> p = mDrawingParent.promote();
4242 if (p != nullptr) {
4243 snapshot->transform = p->getTransform();
4244 } else {
4245 snapshot->transform.reset();
4246 }
4247 snapshot->bufferSize = getBufferSize(mDrawingState);
4248 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Nairba354102022-08-01 00:14:18 +00004249 preparePerFrameCompositionState();
4250}
4251
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004252void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4253 mSnapshot->layerMetadata = parentMetadata;
4254 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4255 for (const sp<Layer>& child : mDrawingChildren) {
4256 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4257 }
4258}
4259
4260void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4261 std::unordered_set<Layer*>& visited) {
4262 if (visited.find(this) != visited.end()) {
4263 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4264 return;
4265 }
4266 visited.insert(this);
4267
4268 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4269
4270 if (mDrawingState.zOrderRelatives.empty()) {
4271 return;
4272 }
4273 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4274 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4275 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4276 sp<Layer> relative = weakRelative.promote();
4277 if (!relative) {
4278 continue;
4279 }
4280 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4281 }
4282}
4283
Mathias Agopian13127d82013-03-05 17:47:11 -08004284// ---------------------------------------------------------------------------
4285
Marin Shalamanov46084422020-10-13 12:33:42 +02004286std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004287 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4288 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004289}
4290
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004291} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004292
4293#if defined(__gl_h_)
4294#error "don't include gl/gl.h in this file"
4295#endif
4296
4297#if defined(__gl2_h_)
4298#error "don't include gl2/gl2.h in this file"
4299#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004300
4301// TODO(b/129481165): remove the #pragma below and fix conversion issues
4302#pragma clang diagnostic pop // ignored "-Wconversion"