blob: 96ee28cc9b3e8394fec67aaae3d12589705fb05a [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 // TODO(b/178542907): Implement onSurfaceFrameCreated for BQLayer as well.
1555 onSurfaceFrameCreated(surfaceFrame);
1556 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001557}
1558
Ady Abrahama850c182021-08-04 13:04:37 -07001559bool Layer::setFrameRateForLayerTree(FrameRate frameRate) {
1560 if (mDrawingState.frameRateForLayerTree == frameRate) {
1561 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001562 }
1563
Ady Abrahama850c182021-08-04 13:04:37 -07001564 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001565
Ady Abrahama850c182021-08-04 13:04:37 -07001566 // TODO(b/195668952): we probably don't need to dirty visible regions here
1567 // or even store frameRateForLayerTree in mDrawingState
1568 mDrawingState.sequence++;
1569 mDrawingState.modified = true;
1570 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001571
Dominik Laskowski068173d2021-08-11 17:22:59 -07001572 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
1573 mFlinger->mScheduler->recordLayerHistory(this, systemTime(), LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001574
1575 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001576}
1577
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001578Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1579 return getDrawingState().frameRateForLayerTree;
1580}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001581
Robert Carr1f0a16a2016-10-24 16:27:39 -07001582bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001583 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001584 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001585 if (parent != nullptr && parent->isHiddenByPolicy()) {
1586 return true;
1587 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001588 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1589 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1590 if (zOrderRelativeOf != nullptr) {
1591 if (zOrderRelativeOf->isHiddenByPolicy()) {
1592 return true;
1593 }
1594 }
1595 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001596 if (CC_UNLIKELY(!isTransformValid())) {
1597 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1598 return true;
1599 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001600 return s.flags & layer_state_t::eLayerHidden;
1601}
1602
David Sodman41fdfc92017-11-06 16:09:56 -08001603uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001604 // TODO: should we do something special if mSecure is set?
1605 if (mProtectedByApp) {
1606 // need a hardware-protected path to external video sink
1607 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001608 }
Riley Andrews03414a12014-07-01 14:22:59 -07001609 if (mPotentialCursor) {
1610 usage |= GraphicBuffer::USAGE_CURSOR;
1611 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001612 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001613 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001614}
1615
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001616void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1617 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1618 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001619 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001620
Vishnu Nair6213bd92020-05-08 17:42:25 -07001621 setTransformHint(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001622}
1623
Mathias Agopian13127d82013-03-05 17:47:11 -08001624// ----------------------------------------------------------------------------
1625// debugging
1626// ----------------------------------------------------------------------------
1627
Marissa Wall61c58622018-07-18 10:12:20 -07001628// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001629gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001630 using namespace std::string_literals;
1631
Huihong Luo05539a12022-02-23 10:29:40 -08001632 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001633 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001634 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001635 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001636 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001637 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001638
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001639 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001640 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001641 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001642 info.mX = ds.transform.tx();
1643 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001644 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001645 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001646 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001647 info.mFlags = ds.flags;
1648 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001649 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001650 info.mMatrix[0][0] = ds.transform[0][0];
1651 info.mMatrix[0][1] = ds.transform[0][1];
1652 info.mMatrix[1][0] = ds.transform[1][0];
1653 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001654 {
chaviwd62d3062019-09-04 14:48:02 -07001655 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001656 if (buffer != 0) {
1657 info.mActiveBufferWidth = buffer->getWidth();
1658 info.mActiveBufferHeight = buffer->getHeight();
1659 info.mActiveBufferStride = buffer->getStride();
1660 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001661 } else {
1662 info.mActiveBufferWidth = 0;
1663 info.mActiveBufferHeight = 0;
1664 info.mActiveBufferStride = 0;
1665 info.mActiveBufferFormat = 0;
1666 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001667 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001668 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001669 info.mIsOpaque = isOpaque(ds);
1670 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001671 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001672 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001673}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001674
Yiwei Zhang5434a782018-12-05 18:06:32 -08001675void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001676 result.append(kDumpTableRowLength, '-');
1677 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001678 result.append(" Layer name\n");
1679 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001680 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001681 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001682 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001683 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001684 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001685 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1686 result.append(kDumpTableRowLength, '-');
1687 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001688}
1689
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001690void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1691 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001692 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001693 return;
1694 }
1695
Yiwei Zhang5434a782018-12-05 18:06:32 -08001696 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001697 if (mName.length() > 77) {
1698 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001699 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001700 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001701 shortened.append(mName, mName.length() - 36);
1702 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001703 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001704 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001705 }
1706
Yiwei Zhang5434a782018-12-05 18:06:32 -08001707 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001708
Alec Mourib416efd2018-09-06 21:01:59 +00001709 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001710 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001711
Chia-I Wu1e043612018-03-01 09:45:09 -08001712 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001713 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001714 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001715 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001716 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001717 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001718 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001719 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1720 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001721 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001722 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001723 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001724 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001725 const auto frameRate = getFrameRateForLayerTree();
1726 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1727 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001728 ftl::enum_string(frameRate.type).c_str(),
1729 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001730 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001731 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001732 }
Dan Stozae22aec72016-08-01 13:20:59 -07001733
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001734 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1735 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1736
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001737 result.append(kDumpTableRowLength, '-');
1738 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001739}
Dan Stozae22aec72016-08-01 13:20:59 -07001740
Yiwei Zhang5434a782018-12-05 18:06:32 -08001741void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001742 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001743}
1744
Svetoslavd85084b2014-03-20 10:28:31 -07001745void Layer::clearFrameStats() {
1746 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001747}
1748
Jamie Gennis6547ff42013-07-16 20:12:42 -07001749void Layer::logFrameStats() {
1750 mFrameTracker.logAndResetStats(mName);
1751}
1752
Svetoslavd85084b2014-03-20 10:28:31 -07001753void Layer::getFrameStats(FrameStats* outStats) const {
1754 mFrameTracker.getStats(outStats);
1755}
1756
Vishnu Nair0f085c62019-08-30 08:49:12 -07001757void Layer::dumpCallingUidPid(std::string& result) const {
chaviw250bcbb2020-08-05 11:17:54 -07001758 StringAppendF(&result, "Layer %s (%s) callingPid:%d callingUid:%d ownerUid:%d\n",
1759 getName().c_str(), getType(), mCallingPid, mCallingUid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001760}
1761
Brian Anderson5ea5e592016-12-01 16:54:33 -08001762void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001763 const int32_t layerId = getSequence();
1764 mFlinger->mTimeStats->onDestroy(layerId);
1765 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001766}
1767
Chia-I Wu98f1c102017-05-30 14:54:08 -07001768size_t Layer::getChildrenCount() const {
1769 size_t count = 0;
1770 for (const sp<Layer>& child : mCurrentChildren) {
1771 count += 1 + child->getChildrenCount();
1772 }
1773 return count;
1774}
1775
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001776void Layer::setGameModeForTree(GameMode gameMode) {
1777 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001778 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1779 gameMode =
1780 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001781 }
1782 setGameMode(gameMode);
1783 for (const sp<Layer>& child : mCurrentChildren) {
1784 child->setGameModeForTree(gameMode);
1785 }
1786}
1787
Robert Carr1f0a16a2016-10-24 16:27:39 -07001788void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001789 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001790 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001791
Robert Carr1f0a16a2016-10-24 16:27:39 -07001792 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001793 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001794 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001795 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001796}
1797
1798ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001799 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001800 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001801
Robert Carr1323c952019-01-28 18:13:27 -08001802 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001803 const auto removeResult = mCurrentChildren.remove(layer);
1804
1805 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001806 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001807 layer->updateTreeHasFrameRateVote();
1808
1809 return removeResult;
1810}
1811
Robert Carr15eae092018-03-23 13:43:53 -07001812void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001813 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001814 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001815 const float parentShadowRadius =
1816 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001817 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001818 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001819 }
1820}
1821
chaviwf1961f72017-09-18 16:41:07 -07001822bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001823 sp<Layer> newParent;
1824 if (newParentHandle != nullptr) {
Vishnu Nairf9096652021-07-20 18:49:42 -07001825 newParent = fromHandle(newParentHandle).promote();
Robert Carr54cf5b12019-01-25 14:02:28 -08001826 if (newParent == nullptr) {
1827 ALOGE("Unable to promote Layer handle");
1828 return false;
1829 }
1830 if (newParent == this) {
1831 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1832 return false;
1833 }
1834 }
1835
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001836 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001837 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001838 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001839 }
1840
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001841 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001842 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001843 if (!newParent->isRemovedFromCurrentState()) {
1844 addToCurrentState();
1845 } else {
1846 onRemovedFromCurrentState();
1847 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001848 } else {
1849 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001850 }
1851
chaviw06178942017-07-27 10:25:59 -07001852 return true;
1853}
1854
Peiyong Lind3788632018-09-18 16:01:31 -07001855bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001856 static const mat4 identityMatrix = mat4();
1857
Robert Carr6a160312021-05-17 12:08:20 -07001858 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001859 return false;
1860 }
Robert Carr6a160312021-05-17 12:08:20 -07001861 ++mDrawingState.sequence;
1862 mDrawingState.colorTransform = matrix;
1863 mDrawingState.hasColorTransform = matrix != identityMatrix;
1864 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001865 setTransactionFlags(eTransactionNeeded);
1866 return true;
1867}
1868
chaviwf66724d2018-11-28 16:35:21 -08001869mat4 Layer::getColorTransform() const {
1870 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001871 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001872 colorTransform = parent->getColorTransform() * colorTransform;
1873 }
1874 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001875}
1876
1877bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001878 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001879 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001880 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1881 }
1882 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001883}
1884
Chia-I Wu11481472018-05-04 10:43:19 -07001885bool Layer::isLegacyDataSpace() const {
1886 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001887 return !(getDataSpace() &
1888 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1889 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001890}
1891
Robert Carr1f0a16a2016-10-24 16:27:39 -07001892void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001893 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001894}
1895
Robert Carr6a160312021-05-17 12:08:20 -07001896int32_t Layer::getZ(LayerVector::StateSet) const {
1897 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001898}
1899
Robert Carr1c5481e2019-07-01 14:42:27 -07001900bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001901 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001902 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001903 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001904}
1905
David Sodman41fdfc92017-11-06 16:09:56 -08001906__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001907 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001908 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1909 "makeTraversalList received invalid stateSet");
1910 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1911 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001912 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001913
Robert Carr29abff82017-12-04 13:51:20 -08001914 if (state.zOrderRelatives.size() == 0) {
1915 *outSkipRelativeZUsers = true;
1916 return children;
1917 }
1918
chaviwfd462612018-05-31 16:11:27 -07001919 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001920 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001921 sp<Layer> strongRelative = weakRelative.promote();
1922 if (strongRelative != nullptr) {
1923 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001924 }
1925 }
1926
Dan Stoza412903f2017-04-27 13:42:17 -07001927 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001928 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001929 continue;
1930 }
Robert Carrdb66e622017-04-10 16:55:57 -07001931 traverse.add(child);
1932 }
1933
1934 return traverse;
1935}
1936
Robert Carr1f0a16a2016-10-24 16:27:39 -07001937/**
Robert Carrdb66e622017-04-10 16:55:57 -07001938 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001939 */
Dan Stoza412903f2017-04-27 13:42:17 -07001940void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001941 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1942 // produce a new list for traversing, including our relatives, and not including our children
1943 // who are relatives of another surface. In the case that there are no relative Z,
1944 // makeTraversalList returns our children directly to avoid significant overhead.
1945 // However in this case we need to take the responsibility for filtering children which
1946 // are relatives of another surface here.
1947 bool skipRelativeZUsers = false;
1948 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001949
Robert Carr1f0a16a2016-10-24 16:27:39 -07001950 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001951 for (; i < list.size(); i++) {
1952 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001953 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1954 continue;
1955 }
1956
chaviw301b1d82019-11-06 13:15:09 -08001957 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001958 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001959 }
Dan Stoza412903f2017-04-27 13:42:17 -07001960 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001961 }
Robert Carr29abff82017-12-04 13:51:20 -08001962
Dan Stoza412903f2017-04-27 13:42:17 -07001963 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001964 for (; i < list.size(); i++) {
1965 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001966
Robert Carr29abff82017-12-04 13:51:20 -08001967 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1968 continue;
1969 }
Dan Stoza412903f2017-04-27 13:42:17 -07001970 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001971 }
1972}
1973
1974/**
Robert Carrdb66e622017-04-10 16:55:57 -07001975 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001976 */
Dan Stoza412903f2017-04-27 13:42:17 -07001977void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1978 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001979 // See traverseInZOrder for documentation.
1980 bool skipRelativeZUsers = false;
1981 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001982
Robert Carr1f0a16a2016-10-24 16:27:39 -07001983 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001984 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001985 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001986
1987 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1988 continue;
1989 }
1990
chaviw301b1d82019-11-06 13:15:09 -08001991 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001992 break;
1993 }
Dan Stoza412903f2017-04-27 13:42:17 -07001994 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001995 }
Dan Stoza412903f2017-04-27 13:42:17 -07001996 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001997 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001998 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001999
2000 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
2001 continue;
2002 }
2003
Dan Stoza412903f2017-04-27 13:42:17 -07002004 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002005 }
2006}
2007
Edgar Arriaga844fa672020-01-16 14:21:42 -08002008void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
2009 visitor(this);
2010 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07002011 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002012 for (const sp<Layer>& child : children) {
2013 child->traverse(state, visitor);
2014 }
2015}
2016
chaviw4b129c22018-04-09 16:19:43 -07002017LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
2018 const std::vector<Layer*>& layersInTree) {
2019 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2020 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07002021 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2022 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002023 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002024
chaviwfd462612018-05-31 16:11:27 -07002025 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07002026 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2027 sp<Layer> strongRelative = weakRelative.promote();
2028 // Only add relative layers that are also descendents of the top most parent of the tree.
2029 // If a relative layer is not a descendent, then it should be ignored.
2030 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
2031 traverse.add(strongRelative);
2032 }
2033 }
2034
2035 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07002036 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002037 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
2038 // descendent of the top most parent of the tree. If it's not a descendent, then just add
2039 // the child here since it won't be added later as a relative.
2040 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
2041 childState.zOrderRelativeOf.promote().get())) {
2042 continue;
2043 }
2044 traverse.add(child);
2045 }
2046
2047 return traverse;
2048}
2049
2050void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
2051 LayerVector::StateSet stateSet,
2052 const LayerVector::Visitor& visitor) {
2053 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07002054
2055 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07002056 for (; i < list.size(); i++) {
2057 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08002058 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07002059 break;
2060 }
chaviw4b129c22018-04-09 16:19:43 -07002061 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002062 }
chaviw4b129c22018-04-09 16:19:43 -07002063
chaviwa76b2712017-09-20 12:02:26 -07002064 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07002065 for (; i < list.size(); i++) {
2066 const auto& relative = list[i];
2067 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002068 }
2069}
2070
chaviw4b129c22018-04-09 16:19:43 -07002071std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2072 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2073 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2074
2075 std::vector<Layer*> layersInTree = {this};
2076 for (size_t i = 0; i < children.size(); i++) {
2077 const auto& child = children[i];
2078 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2079 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2080 }
2081
2082 return layersInTree;
2083}
2084
2085void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2086 const LayerVector::Visitor& visitor) {
2087 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2088 std::sort(layersInTree.begin(), layersInTree.end());
2089 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2090}
2091
Peiyong Linefefaac2018-08-17 12:27:51 -07002092ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08002093 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002094}
2095
Garfield Tan2c1782c2022-02-16 15:25:05 -08002096bool Layer::isTransformValid() const {
2097 float transformDet = getTransform().det();
2098 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2099}
2100
chaviw13fdc492017-06-27 12:40:18 -07002101half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002102 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002103
chaviw13fdc492017-06-27 12:40:18 -07002104 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2105 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002106}
Robert Carr6452f122017-03-21 10:41:29 -07002107
Vishnu Nair6213bd92020-05-08 17:42:25 -07002108ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002109 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002110 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2111 return fixedTransformHint;
2112 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002113 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002114 if (!p) return fixedTransformHint;
2115 return p->getFixedTransformHint();
2116}
2117
chaviw13fdc492017-06-27 12:40:18 -07002118half4 Layer::getColor() const {
2119 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002120 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002121}
Robert Carr6452f122017-03-21 10:41:29 -07002122
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002123int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002124 if (getDrawingState().backgroundBlurRadius == 0) {
2125 return 0;
2126 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002127
Vishnu Nair29810f72022-07-01 16:38:41 +00002128 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002129 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2130 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002131}
2132
Galia Peychevae0acf382021-04-12 21:22:34 +02002133const std::vector<BlurRegion> Layer::getBlurRegions() const {
2134 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002135 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002136 for (auto& region : regionsCopy) {
2137 region.alpha = region.alpha * layerAlpha;
2138 }
2139 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002140}
2141
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002142Layer::RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002143 // Get parent settings
2144 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002145 const auto& parent = mDrawingParent.promote();
2146 if (parent != nullptr) {
2147 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002148 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002149 ui::Transform t = getActiveTransform(getDrawingState());
2150 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002151 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002152 parentSettings.radius.x *= t.getScaleX();
2153 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002154 }
2155 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002156
2157 // Get layer settings
2158 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002159 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002160 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002161 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002162
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002163 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002164 // If the parent and the layer have rounded corner settings, use the parent settings if the
2165 // parent crop is entirely inside the layer crop.
2166 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2167 if (parentSettings.cropRect.left > layerCropRect.left &&
2168 parentSettings.cropRect.top > layerCropRect.top &&
2169 parentSettings.cropRect.right < layerCropRect.right &&
2170 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2171 return parentSettings;
2172 } else {
2173 return layerSettings;
2174 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002175 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002176 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002177 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002178 return parentSettings;
2179 }
2180 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002181}
2182
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04002183void Layer::prepareShadowClientComposition(LayerFE::LayerSettings& caster,
Patrick Williams16d8b2c2022-08-08 17:29:05 +00002184 const Rect& layerStackRect) const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00002185 const auto* snapshot = getLayerSnapshot();
2186 renderengine::ShadowSettings state = snapshot->shadowSettings;
2187 if (state.length <= 0.f || (state.ambientColor.a <= 0.f && state.spotColor.a <= 0.f)) {
2188 return;
2189 }
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04002190
Vishnu Nair08f6eae2019-11-26 14:01:39 -08002191 // Shift the spot light x-position to the middle of the display and then
2192 // offset it by casting layer's screen pos.
Vishnu Nairbedb44b2022-08-02 21:47:40 +00002193 state.lightPos.x = (layerStackRect.width() / 2.f) - snapshot->transformedBounds.left;
2194 state.lightPos.y -= snapshot->transformedBounds.top;
2195 caster.shadow = state;
Vishnu Nair08f6eae2019-11-26 14:01:39 -08002196}
2197
Robert Carr88b85e12022-03-21 15:47:35 -07002198bool Layer::findInHierarchy(const sp<Layer>& l) {
2199 if (l == this) {
2200 return true;
2201 }
2202 for (auto& child : mDrawingChildren) {
2203 if (child->findInHierarchy(l)) {
2204 return true;
2205 }
2206 }
2207 return false;
2208}
2209
Robert Carr1f0a16a2016-10-24 16:27:39 -07002210void Layer::commitChildList() {
2211 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2212 const auto& child = mCurrentChildren[i];
2213 child->commitChildList();
2214 }
2215 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002216 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002217 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2218 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2219 if (zOrderRelativeOf == nullptr) return;
2220 if (findInHierarchy(zOrderRelativeOf)) {
2221 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2222 zOrderRelativeOf->mName.c_str());
2223 ALOGE("Severing rel Z loop, potentially dangerous");
2224 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002225 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002226 }
2227 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002228}
2229
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002230
chaviw3277faf2021-05-19 16:45:23 -05002231void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002232 mDrawingState.inputInfo = info;
Vishnu Nairf9096652021-07-20 18:49:42 -07002233 mDrawingState.touchableRegionCrop = fromHandle(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002234 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002235 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002236 setTransactionFlags(eTransactionNeeded);
2237}
2238
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002239LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002240 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002241 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002242 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2243
Vishnu Nair00b90132021-11-05 14:03:40 -07002244 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002245 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2246
Vishnu Nair60db8c02020-04-02 11:55:16 -07002247 // Only populate for the primary display.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002248 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -05002249 const auto compositionType = getCompositionType(*display);
Vishnu Nair60db8c02020-04-02 11:55:16 -07002250 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002251 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2252 [&]() { return layerProto->mutable_visible_region(); });
Vishnu Nair60db8c02020-04-02 11:55:16 -07002253 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08002254 }
2255
chaviw08f3cb22020-01-13 13:17:21 -08002256 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002257 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002258 }
chaviw6d89e2d2020-01-14 14:42:01 -08002259
2260 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002261}
2262
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002263void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002264 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002265 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002266 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002267 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002268 [&]() { return layerInfo->mutable_active_buffer(); });
2269 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2270 layerInfo->mutable_buffer_transform());
2271 }
2272 layerInfo->set_invalidate(contentDirty);
2273 layerInfo->set_is_protected(isProtected());
2274 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2275 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002276 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002277 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002278 layerInfo->set_corner_radius(
2279 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002280 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2281 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2282 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2283 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2284 [&]() { return layerInfo->mutable_position(); });
2285 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002286 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2287 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002288
Vishnu Nair00b90132021-11-05 14:03:40 -07002289 if (hasColorTransform()) {
2290 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002291 }
2292
Vishnu Nair60db8c02020-04-02 11:55:16 -07002293 LayerProtoHelper::writeToProto(mSourceBounds,
2294 [&]() { return layerInfo->mutable_source_bounds(); });
2295 LayerProtoHelper::writeToProto(mScreenBounds,
2296 [&]() { return layerInfo->mutable_screen_bounds(); });
2297 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2298 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2299 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002300}
2301
2302void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002303 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002304 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2305 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002306 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002307
chaviw766c9c52021-02-10 17:36:47 -08002308 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002309
Vishnu Nair00b90132021-11-05 14:03:40 -07002310 layerInfo->set_id(sequence);
2311 layerInfo->set_name(getName().c_str());
2312 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002313
Vishnu Nair00b90132021-11-05 14:03:40 -07002314 for (const auto& child : children) {
2315 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002316 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002317
Vishnu Nair00b90132021-11-05 14:03:40 -07002318 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2319 sp<Layer> strongRelative = weakRelative.promote();
2320 if (strongRelative != nullptr) {
2321 layerInfo->add_relatives(strongRelative->sequence);
2322 }
2323 }
2324
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002325 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002326 [&]() { return layerInfo->mutable_transparent_region(); });
2327
2328 layerInfo->set_layer_stack(getLayerStack().id);
2329 layerInfo->set_z(state.z);
2330
2331 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2332 return layerInfo->mutable_requested_position();
2333 });
2334
Vishnu Nair00b90132021-11-05 14:03:40 -07002335 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2336
2337 layerInfo->set_is_opaque(isOpaque(state));
2338
2339 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2340 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2341 LayerProtoHelper::writeToProto(state.color,
2342 [&]() { return layerInfo->mutable_requested_color(); });
2343 layerInfo->set_flags(state.flags);
2344
2345 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2346 layerInfo->mutable_requested_transform());
2347
2348 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2349 if (parent != nullptr) {
2350 layerInfo->set_parent(parent->sequence);
2351 } else {
2352 layerInfo->set_parent(-1);
2353 }
2354
2355 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2356 if (zOrderRelativeOf != nullptr) {
2357 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2358 } else {
2359 layerInfo->set_z_order_relative_of(-1);
2360 }
2361
2362 layerInfo->set_is_relative_of(state.isRelativeOf);
2363
2364 layerInfo->set_owner_uid(mOwnerUid);
2365
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002366 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002367 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002368 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002369 info = fillInputInfo(
2370 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002371 } else {
2372 info = state.inputInfo;
2373 }
2374
2375 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002376 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002377 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002378
Vishnu Nair00b90132021-11-05 14:03:40 -07002379 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002380 auto protoMap = layerInfo->mutable_metadata();
2381 for (const auto& entry : state.metadata.mMap) {
2382 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2383 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002384 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002385
2386 LayerProtoHelper::writeToProto(state.destinationFrame,
2387 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002388}
2389
Robert Carr2e102c92018-10-23 12:11:15 -07002390bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002391 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002392}
2393
Prabir Pradhan33da9462022-06-14 14:55:57 +00002394// Applies the given transform to the region, while protecting against overflows caused by any
2395// offsets. If applying the offset in the transform to any of the Rects in the region would result
2396// in an overflow, they are not added to the output Region.
2397static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2398 const std::string& debugWindowName) {
2399 // Round the translation using the same rounding strategy used by ui::Transform.
2400 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2401 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2402
2403 ui::Transform transformWithoutOffset = t;
2404 transformWithoutOffset.set(0.f, 0.f);
2405
2406 const Region transformed = transformWithoutOffset.transform(r);
2407
2408 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2409 Region ret;
2410 for (const auto& rect : transformed) {
2411 Rect newRect;
2412 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2413 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2414 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2415 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2416 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2417 debugWindowName.c_str());
2418 continue;
2419 }
2420 ret.orSelf(newRect);
2421 }
2422 return ret;
2423}
2424
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002425void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
2426 Rect tmpBounds = getInputBounds();
2427 if (!tmpBounds.isValid()) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002428 info.touchableRegion.clear();
2429 // A layer could have invalid input bounds and still expect to receive touch input if it has
2430 // replaceTouchableRegionWithCrop. For that case, the input transform needs to be calculated
2431 // correctly to determine the coordinate space for input events. Use an empty rect so that
2432 // the layer will receive input in its own layer space.
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002433 tmpBounds = Rect::EMPTY_RECT;
chaviw7e72caf2020-12-02 16:50:43 -08002434 }
2435
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002436 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2437 // frame and transform used for the layer, which determines the bounds and the coordinate space
2438 // within which the layer will receive input.
2439 //
2440 // The coordinate space within which each of the bounds are specified is explicitly documented
2441 // in the variable name. For example "inputBoundsInLayer" is specified in layer space. A
2442 // Transform converts one coordinate space to another, which is apparent in its naming. For
2443 // example, "layerToDisplay" transforms layer space to display space.
2444 //
2445 // Coordinate space definitions:
2446 // - display: The display device's coordinate space. Correlates to pixels on the display.
2447 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2448 // - layer: The coordinate space of this layer.
2449 // - input: The coordinate space in which this layer will receive input events. This could be
2450 // different than layer space if a surfaceInset is used, which changes the origin
2451 // of the input space.
2452 const FloatRect inputBoundsInLayer = tmpBounds.toFloatRect();
chaviw7e72caf2020-12-02 16:50:43 -08002453
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002454 // Clamp surface inset to the input bounds.
2455 const auto surfaceInset = static_cast<float>(info.surfaceInset);
2456 const float xSurfaceInset =
2457 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getWidth() / 2.f));
2458 const float ySurfaceInset =
2459 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getHeight() / 2.f));
chaviw1ff3d1e2020-07-01 15:53:47 -07002460
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002461 // Apply the insets to the input bounds.
2462 const FloatRect insetBoundsInLayer(inputBoundsInLayer.left + xSurfaceInset,
2463 inputBoundsInLayer.top + ySurfaceInset,
2464 inputBoundsInLayer.right - xSurfaceInset,
2465 inputBoundsInLayer.bottom - ySurfaceInset);
Ady Abraham282f1d72019-07-24 18:05:56 -07002466
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002467 // Crop the input bounds to ensure it is within the parent's bounds.
2468 const FloatRect croppedInsetBoundsInLayer = mBounds.intersect(insetBoundsInLayer);
Ady Abraham282f1d72019-07-24 18:05:56 -07002469
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002470 const ui::Transform layerToScreen = getInputTransform();
2471 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
Vishnu Nair8033a492018-12-05 07:27:23 -08002472
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002473 const Rect roundedFrameInDisplay{layerToDisplay.transform(croppedInsetBoundsInLayer)};
2474 info.frameLeft = roundedFrameInDisplay.left;
2475 info.frameTop = roundedFrameInDisplay.top;
2476 info.frameRight = roundedFrameInDisplay.right;
2477 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002478
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002479 ui::Transform inputToLayer;
2480 inputToLayer.set(insetBoundsInLayer.left, insetBoundsInLayer.top);
2481 const ui::Transform inputToDisplay = layerToDisplay * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002482
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002483 // InputDispatcher expects a display-to-input transform.
2484 info.transform = inputToDisplay.inverse();
2485
2486 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002487 info.touchableRegion =
2488 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002489}
2490
chaviw3277faf2021-05-19 16:45:23 -05002491void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002492 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002493 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002494 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002495 }
2496 if (p != nullptr) {
2497 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2498 }
2499}
2500
Vishnu Naira066d902021-09-13 18:40:17 -07002501gui::DropInputMode Layer::getDropInputMode() const {
2502 gui::DropInputMode mode = mDrawingState.dropInputMode;
2503 if (mode == gui::DropInputMode::ALL) {
2504 return mode;
2505 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002506 sp<Layer> parent = mDrawingParent.promote();
2507 if (parent) {
2508 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002509 if (parentMode != gui::DropInputMode::NONE) {
2510 return parentMode;
2511 }
2512 }
2513 return mode;
2514}
2515
2516void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002517 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002518 return;
2519 }
2520
2521 // Check if we need to drop input unconditionally
2522 gui::DropInputMode dropInputMode = getDropInputMode();
2523 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002524 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002525 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2526 return;
2527 }
2528
2529 // Check if we need to check if the window is obscured by parent
2530 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2531 return;
2532 }
2533
2534 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002535 sp<Layer> parent = mDrawingParent.promote();
2536 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002537 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002538 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2539 static_cast<float>(getAlpha()));
2540 }
2541
2542 // Check if the parent has cropped the buffer
2543 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2544 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002545 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002546 return;
2547 }
2548
2549 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2550 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2551 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2552 // match then the layer has not been cropped by its parents.
2553 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2554 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2555
2556 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002557 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002558 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2559 getDebugName());
2560 } else {
2561 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2562 // input if the window is obscured. This check should be done in surfaceflinger but the
2563 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2564 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002565 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002566 }
2567}
2568
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002569WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002570 if (!hasInputInfo()) {
2571 mDrawingState.inputInfo.name = getName();
2572 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2573 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002574 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002575 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002576 }
2577
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002578 const ui::Transform& displayTransform =
2579 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2580
chaviw3277faf2021-05-19 16:45:23 -05002581 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002582 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002583 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002584
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002585 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002586
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002587 if (displayArgs.transform == nullptr) {
2588 // Do not let the window receive touches if it is not associated with a valid display
2589 // transform. We still allow the window to receive keys and prevent ANRs.
2590 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2591 }
2592
Robert Carr5dc426e2020-06-10 14:29:14 -07002593 // For compatibility reasons we let layers which can receive input
2594 // receive input before they have actually submitted a buffer. Because
2595 // of this we use canReceiveInput instead of isVisible to check the
2596 // policy-visibility, ignoring the buffer state. However for layers with
2597 // hasInputInfo()==false we can use the real visibility state.
2598 // We are just using these layers for occlusion detection in
2599 // InputDispatcher, and obviously if they aren't visible they can't occlude
2600 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002601 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2602 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2603
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002604 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002605 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002606 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002607
Vishnu Nair16a938f2021-09-24 07:14:54 -07002608 // If the window will be blacked out on a display because the display does not have the secure
2609 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002610 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002611 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002612 }
2613
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002614 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2615 if (info.replaceTouchableRegionWithCrop) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002616 const Rect bounds(cropLayer ? cropLayer->mScreenBounds : mScreenBounds);
2617 info.touchableRegion = Region(displayTransform.transform(bounds));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002618 } else if (cropLayer != nullptr) {
[1;3C2b9fc252021-02-04 16:16:50 -08002619 info.touchableRegion = info.touchableRegion.intersect(
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002620 displayTransform.transform(Rect{cropLayer->mScreenBounds}));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002621 }
2622
Winson Chunga30f7c92021-06-29 15:42:56 -07002623 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2624 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002625 if (isTrustedOverlay()) {
2626 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2627 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002628
chaviwaf87b3e2019-10-01 16:59:28 -07002629 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2630 // touches from going outside the cloned area.
2631 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002632 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002633 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2634 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002635 info.touchableRegion = info.touchableRegion.intersect(rect);
2636 }
2637 }
2638
Robert Carr720e5062018-07-30 17:45:14 -07002639 return info;
2640}
2641
chaviwaf87b3e2019-10-01 16:59:28 -07002642sp<Layer> Layer::getClonedRoot() {
2643 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002644 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002645 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002646 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002647 return nullptr;
2648 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002649 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002650}
2651
Robert Carredd13602020-04-13 17:24:34 -07002652bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002653 return mDrawingState.inputInfo.token != nullptr ||
2654 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002655}
2656
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002657compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002658 const DisplayDevice* display) const {
2659 if (!display) return nullptr;
Lloyd Piquede196652020-01-22 17:29:58 -08002660 return display->getCompositionDisplay()->getOutputLayerForLayer(getCompositionEngineLayerFE());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002661}
2662
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002663Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2664 const auto outputLayer = findOutputLayerForDisplay(display);
2665 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002666}
2667
chaviwb4c6e582019-08-16 14:35:07 -07002668void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002669 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002670 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002671 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2672 mPotentialCursor = clonedFrom->mPotentialCursor;
2673 mProtectedByApp = clonedFrom->mProtectedByApp;
2674 updateCloneBufferInfo();
2675}
2676
2677void Layer::updateCloneBufferInfo() {
2678 if (!isClone() || !isClonedFromAlive()) {
2679 return;
2680 }
2681
2682 sp<Layer> clonedFrom = getClonedFrom();
2683 mBufferInfo = clonedFrom->mBufferInfo;
2684 mSidebandStream = clonedFrom->mSidebandStream;
2685 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2686 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2687 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2688
2689 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2690 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2691 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2692 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2693 // the cloned drawingState again.
2694 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2695 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2696 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2697 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2698
2699 cloneDrawingState(clonedFrom.get());
2700
2701 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2702 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2703 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2704 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002705}
chaviw74b03172019-08-19 11:09:03 -07002706
2707void Layer::updateMirrorInfo() {
2708 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2709 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2710 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2711 // that case, we want to delete the reference to the clone since we want it to get
2712 // destroyed. The root, this layer, will still be around since the client can continue
2713 // to hold a reference, but no cloned layers will be displayed.
2714 mClonedChild = nullptr;
2715 return;
2716 }
2717
2718 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2719 // If the real layer exists and is in current state, add the clone as a child of the root.
2720 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2721 // copied to drawingState for the root layer. So the clonedChild is always removed from
2722 // drawingState and then needs to be added back each traversal.
2723 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2724 addChildToDrawing(mClonedChild);
2725 }
2726
2727 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002728 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002729 mClonedChild->updateClonedRelatives(clonedLayersMap);
2730}
2731
2732void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2733 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2734 // to the clone. If the real layer is no longer alive, continue traversing the children
2735 // since we may be able to pull out other children that are still alive.
2736 if (isClonedFromAlive()) {
2737 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002738 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002739 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002740 }
2741
2742 // The clone layer may have children in drawingState since they may have been created and
2743 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2744 // that already exist, since we can just re-use them.
2745 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2746 // not updated in the regular traversal. They are skipped since the root will lose the
2747 // reference to them when it copies its currentChildren to drawing.
2748 for (sp<Layer>& child : mDrawingChildren) {
2749 child->updateClonedDrawingState(clonedLayersMap);
2750 }
2751}
2752
2753void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2754 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2755 mDrawingChildren.clear();
2756
2757 if (!isClonedFromAlive()) {
2758 return;
2759 }
2760
2761 sp<Layer> clonedFrom = getClonedFrom();
2762 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2763 if (child == mirrorRoot) {
2764 // This is to avoid cyclical mirroring.
2765 continue;
2766 }
2767 sp<Layer> clonedChild = clonedLayersMap[child];
2768 if (clonedChild == nullptr) {
2769 clonedChild = child->createClone();
2770 clonedLayersMap[child] = clonedChild;
2771 }
2772 addChildToDrawing(clonedChild);
2773 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2774 }
2775}
2776
chaviwaf87b3e2019-10-01 16:59:28 -07002777void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2778 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2779 if (cropLayer != nullptr) {
2780 if (clonedLayersMap.count(cropLayer) == 0) {
2781 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2782 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002783 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002784 } else {
2785 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2786 mDrawingState.touchableRegionCrop = clonedCropLayer;
2787 }
2788 }
2789 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2790 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002791 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002792}
2793
2794void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002795 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002796 mDrawingState.zOrderRelatives.clear();
2797
2798 if (!isClonedFromAlive()) {
2799 return;
2800 }
2801
chaviwaf87b3e2019-10-01 16:59:28 -07002802 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002803 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002804 const sp<Layer>& relative = relativeWeak.promote();
2805 if (clonedLayersMap.count(relative) > 0) {
2806 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002807 mDrawingState.zOrderRelatives.add(clonedRelative);
2808 }
2809 }
2810
2811 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2812 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2813 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2814 // still traverse the children, but the layer with the missing relativeOf will not be shown
2815 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002816 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2817 if (clonedLayersMap.count(relativeOf) > 0) {
2818 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002819 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2820 }
2821
chaviwaf87b3e2019-10-01 16:59:28 -07002822 updateClonedInputInfo(clonedLayersMap);
2823
chaviw74b03172019-08-19 11:09:03 -07002824 for (sp<Layer>& child : mDrawingChildren) {
2825 child->updateClonedRelatives(clonedLayersMap);
2826 }
2827}
2828
2829void Layer::addChildToDrawing(const sp<Layer>& layer) {
2830 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002831 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002832}
2833
Steven Thomas62a4cf82020-01-31 12:04:03 -08002834Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2835 switch (compatibility) {
2836 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2837 return FrameRateCompatibility::Default;
2838 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2839 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002840 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2841 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002842 case ANATIVEWINDOW_FRAME_RATE_MIN:
2843 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002844 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2845 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002846 default:
2847 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2848 return FrameRateCompatibility::Default;
2849 }
2850}
2851
Marin Shalamanovc5986772021-03-16 16:09:49 +01002852scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2853 switch (strategy) {
2854 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2855 return Seamlessness::OnlySeamless;
2856 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2857 return Seamlessness::SeamedAndSeamless;
2858 default:
2859 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2860 return Seamlessness::Default;
2861 }
2862}
2863
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002864bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002865 const State& s(mDrawingState);
2866 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2867 return true;
2868 }
2869
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002870 sp<Layer> parent = mDrawingParent.promote();
2871 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002872}
2873
Robert Carr6a0382d2021-07-01 15:57:17 -07002874void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2875 mClonedChild = clonedChild;
2876 mHadClonedChild = true;
2877 mFlinger->mNumClones++;
2878}
2879
Vishnu Nairf9096652021-07-20 18:49:42 -07002880const String16 Layer::Handle::kDescriptor = String16("android.Layer.Handle");
2881
2882wp<Layer> Layer::fromHandle(const sp<IBinder>& handleBinder) {
2883 if (handleBinder == nullptr) {
2884 return nullptr;
2885 }
2886
2887 BBinder* b = handleBinder->localBinder();
2888 if (b == nullptr || b->getInterfaceDescriptor() != Handle::kDescriptor) {
2889 return nullptr;
2890 }
2891
2892 // We can safely cast this binder since its local and we verified its interface descriptor.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002893 sp<Handle> handle = sp<Handle>::cast(handleBinder);
Vishnu Nairf9096652021-07-20 18:49:42 -07002894 return handle->owner;
2895}
2896
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002897bool Layer::setDropInputMode(gui::DropInputMode mode) {
2898 if (mDrawingState.dropInputMode == mode) {
2899 return false;
2900 }
2901 mDrawingState.dropInputMode = mode;
2902 return true;
2903}
2904
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002905void Layer::cloneDrawingState(const Layer* from) {
2906 mDrawingState = from->mDrawingState;
2907 // Skip callback info since they are not applicable for cloned layers.
2908 mDrawingState.releaseBufferListener = nullptr;
2909 mDrawingState.callbackHandles = {};
2910}
2911
Patrick Williamsbb25f802022-08-30 23:02:34 +00002912void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2913 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
2914 const sp<Fence>& releaseFence,
2915 uint32_t currentMaxAcquiredBufferCount) {
2916 if (!listener) {
2917 return;
2918 }
2919 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
2920 listener->onReleaseBuffer({buffer->getId(), framenumber},
2921 releaseFence ? releaseFence : Fence::NO_FENCE,
2922 currentMaxAcquiredBufferCount);
2923}
2924
2925void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2926 // If we are displayed on multiple displays in a single composition cycle then we would
2927 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2928 // For example we can only use it if all the displays are client comp, and we need
2929 // to merge all the client comp fences. We could do this, but for now we just
2930 // disable the optimization when a layer is composed on multiple displays.
2931 if (mClearClientCompositionFenceOnLayerDisplayed) {
2932 mLastClientCompositionFence = nullptr;
2933 } else {
2934 mClearClientCompositionFenceOnLayerDisplayed = true;
2935 }
2936
2937 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2938 // buffer that was presented on this layer. The first transaction that came in this frame that
2939 // replaced the previous buffer on this layer needs this release fence, because the fence will
2940 // let the client know when that previous buffer is removed from the screen.
2941 //
2942 // Every other transaction on this layer does not need a release fence because no other
2943 // Transactions that were set on this layer this frame are going to have their preceding buffer
2944 // removed from the display this frame.
2945 //
2946 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2947 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2948 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2949 // the previous buffer will be released this frame. The third transaction also contains a
2950 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2951 // transaction will now no longer be presented so it is released immediately and the third
2952 // transaction doesn't need a previous release fence.
2953 sp<CallbackHandle> ch;
2954 for (auto& handle : mDrawingState.callbackHandles) {
2955 if (handle->releasePreviousBuffer &&
2956 mDrawingState.releaseBufferEndpoint == handle->listener) {
2957 ch = handle;
2958 break;
2959 }
2960 }
2961
2962 // Prevent tracing the same release multiple times.
2963 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2964 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2965 }
2966
2967 if (ch != nullptr) {
2968 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2969 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2970 ch->name = mName;
2971 }
2972}
2973
2974void Layer::onSurfaceFrameCreated(
2975 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2976 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2977 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2978 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2979 // leak.
2980 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2981 mName.c_str());
2982 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2983 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2984 mPendingJankClassifications.pop_front();
2985 }
2986 mPendingJankClassifications.emplace_back(surfaceFrame);
2987}
2988
2989void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2990 for (const auto& handle : mDrawingState.callbackHandles) {
2991 handle->transformHint = mTransformHint;
2992 handle->dequeueReadyTime = dequeueReadyTime;
2993 handle->currentMaxAcquiredBufferCount =
2994 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2995 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2996 handle->previousReleaseCallbackId.framenumber);
2997 }
2998
2999 for (auto& handle : mDrawingState.callbackHandles) {
3000 if (handle->releasePreviousBuffer &&
3001 mDrawingState.releaseBufferEndpoint == handle->listener) {
3002 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
3003 break;
3004 }
3005 }
3006
3007 std::vector<JankData> jankData;
3008 jankData.reserve(mPendingJankClassifications.size());
3009 while (!mPendingJankClassifications.empty() &&
3010 mPendingJankClassifications.front()->getJankType()) {
3011 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
3012 mPendingJankClassifications.front();
3013 mPendingJankClassifications.pop_front();
3014 jankData.emplace_back(
3015 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
3016 }
3017
3018 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
3019 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003020 mDrawingState.callbackHandles = {};
3021}
3022
3023bool Layer::willPresentCurrentTransaction() const {
3024 // Returns true if the most recent Transaction applied to CurrentState will be presented.
3025 return (getSidebandStreamChanged() || getAutoRefresh() ||
3026 (mDrawingState.modified &&
3027 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
3028}
3029
3030bool Layer::setTransform(uint32_t transform) {
3031 if (mDrawingState.bufferTransform == transform) return false;
3032 mDrawingState.bufferTransform = transform;
3033 mDrawingState.modified = true;
3034 setTransactionFlags(eTransactionNeeded);
3035 return true;
3036}
3037
3038bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
3039 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
3040 mDrawingState.sequence++;
3041 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
3042 mDrawingState.modified = true;
3043 setTransactionFlags(eTransactionNeeded);
3044 return true;
3045}
3046
3047bool Layer::setBufferCrop(const Rect& bufferCrop) {
3048 if (mDrawingState.bufferCrop == bufferCrop) return false;
3049
3050 mDrawingState.sequence++;
3051 mDrawingState.bufferCrop = bufferCrop;
3052
3053 mDrawingState.modified = true;
3054 setTransactionFlags(eTransactionNeeded);
3055 return true;
3056}
3057
3058bool Layer::setDestinationFrame(const Rect& destinationFrame) {
3059 if (mDrawingState.destinationFrame == destinationFrame) return false;
3060
3061 mDrawingState.sequence++;
3062 mDrawingState.destinationFrame = destinationFrame;
3063
3064 mDrawingState.modified = true;
3065 setTransactionFlags(eTransactionNeeded);
3066 return true;
3067}
3068
3069// Translate destination frame into scale and position. If a destination frame is not set, use the
3070// provided scale and position
3071bool Layer::updateGeometry() {
3072 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
3073 mDrawingState.destinationFrame.isEmpty()) {
3074 // If destination frame is not set, use the requested transform set via
3075 // Layer::setPosition and Layer::setMatrix.
3076 return assignTransform(&mDrawingState.transform, mRequestedTransform);
3077 }
3078
3079 Rect destRect = mDrawingState.destinationFrame;
3080 int32_t destW = destRect.width();
3081 int32_t destH = destRect.height();
3082 if (destRect.left < 0) {
3083 destRect.left = 0;
3084 destRect.right = destW;
3085 }
3086 if (destRect.top < 0) {
3087 destRect.top = 0;
3088 destRect.bottom = destH;
3089 }
3090
3091 if (!mDrawingState.buffer) {
3092 ui::Transform t;
3093 t.set(destRect.left, destRect.top);
3094 return assignTransform(&mDrawingState.transform, t);
3095 }
3096
3097 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3098 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3099 // Undo any transformations on the buffer.
3100 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3101 std::swap(bufferWidth, bufferHeight);
3102 }
3103 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3104 if (mDrawingState.transformToDisplayInverse) {
3105 if (invTransform & ui::Transform::ROT_90) {
3106 std::swap(bufferWidth, bufferHeight);
3107 }
3108 }
3109
3110 float sx = destW / static_cast<float>(bufferWidth);
3111 float sy = destH / static_cast<float>(bufferHeight);
3112 ui::Transform t;
3113 t.set(sx, 0, 0, sy);
3114 t.set(destRect.left, destRect.top);
3115 return assignTransform(&mDrawingState.transform, t);
3116}
3117
3118bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3119 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3120 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3121 return false;
3122 }
3123
3124 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3125
3126 mDrawingState.sequence++;
3127 mDrawingState.modified = true;
3128 setTransactionFlags(eTransactionNeeded);
3129
3130 return true;
3131}
3132
3133bool Layer::setPosition(float x, float y) {
3134 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3135 return false;
3136 }
3137
3138 mRequestedTransform.set(x, y);
3139
3140 mDrawingState.sequence++;
3141 mDrawingState.modified = true;
3142 setTransactionFlags(eTransactionNeeded);
3143
3144 return true;
3145}
3146
3147bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3148 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3149 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
3150 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003151 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003152 if (!buffer) {
3153 return false;
3154 }
3155
3156 const bool frameNumberChanged =
3157 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3158 const uint64_t frameNumber =
3159 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003160 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003161
3162 if (mDrawingState.buffer) {
3163 mReleasePreviousBuffer = true;
3164 if (!mBufferInfo.mBuffer ||
3165 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3166 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3167 // If mDrawingState has a buffer, and we are about to update again
3168 // before swapping to drawing state, then the first buffer will be
3169 // dropped and we should decrement the pending buffer count and
3170 // call any release buffer callbacks if set.
3171 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3172 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3173 mDrawingState.acquireFence,
3174 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
3175 mOwnerUid));
3176 decrementPendingBufferCount();
3177 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3178 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3179 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
3180 mDrawingState.bufferSurfaceFrameTX.reset();
3181 }
3182 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3183 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3184 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3185 mLastClientCompositionFence,
3186 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
3187 mOwnerUid));
3188 mLastClientCompositionFence = nullptr;
3189 }
3190 }
3191
3192 mDrawingState.frameNumber = frameNumber;
3193 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3194 mDrawingState.buffer = std::move(buffer);
3195 mDrawingState.clientCacheId = bufferData.cachedBuffer;
3196
3197 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3198 ? bufferData.acquireFence
3199 : Fence::NO_FENCE;
3200 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3201 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3202 // We latched this buffer unsiganled, so we need to pass the acquire fence
3203 // on the callback instead of just the acquire time, since it's unknown at
3204 // this point.
3205 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3206 } else {
3207 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3208 }
3209
3210 mDrawingState.modified = true;
3211 setTransactionFlags(eTransactionNeeded);
3212
3213 const int32_t layerId = getSequence();
3214 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3215 mOwnerUid, postTime, getGameMode());
3216 mDrawingState.desiredPresentTime = desiredPresentTime;
3217 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3218
3219 const nsecs_t presentTime = [&] {
3220 if (!isAutoTimestamp) return desiredPresentTime;
3221
3222 const auto prediction =
3223 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
3224 if (prediction.has_value()) return prediction->presentTime;
3225
3226 return static_cast<nsecs_t>(0);
3227 }();
3228
3229 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
3230 mFlinger->mScheduler->recordLayerHistory(this, presentTime, LayerUpdateType::Buffer);
3231
3232 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3233
3234 if (dequeueTime && *dequeueTime != 0) {
3235 const uint64_t bufferId = mDrawingState.buffer->getId();
3236 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3237 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3238 FrameTracer::FrameEvent::DEQUEUE);
3239 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3240 FrameTracer::FrameEvent::QUEUE);
3241 }
3242
3243 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3244 return true;
3245}
3246
3247bool Layer::setDataspace(ui::Dataspace dataspace) {
3248 mDrawingState.dataspaceRequested = true;
3249 if (mDrawingState.dataspace == dataspace) return false;
3250 mDrawingState.dataspace = dataspace;
3251 mDrawingState.modified = true;
3252 setTransactionFlags(eTransactionNeeded);
3253 return true;
3254}
3255
3256bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3257 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3258 mDrawingState.hdrMetadata = hdrMetadata;
3259 mDrawingState.modified = true;
3260 setTransactionFlags(eTransactionNeeded);
3261 return true;
3262}
3263
3264bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
3265 mDrawingState.surfaceDamageRegion = surfaceDamage;
3266 mDrawingState.modified = true;
3267 setTransactionFlags(eTransactionNeeded);
3268 return true;
3269}
3270
3271bool Layer::setApi(int32_t api) {
3272 if (mDrawingState.api == api) return false;
3273 mDrawingState.api = api;
3274 mDrawingState.modified = true;
3275 setTransactionFlags(eTransactionNeeded);
3276 return true;
3277}
3278
3279bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3280 if (mDrawingState.sidebandStream == sidebandStream) return false;
3281
3282 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3283 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3284 } else if (sidebandStream != nullptr) {
3285 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3286 }
3287
3288 mDrawingState.sidebandStream = sidebandStream;
3289 mDrawingState.modified = true;
3290 setTransactionFlags(eTransactionNeeded);
3291 if (!mSidebandStreamChanged.exchange(true)) {
3292 // mSidebandStreamChanged was false
3293 mFlinger->onLayerUpdate();
3294 }
3295 return true;
3296}
3297
3298bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles) {
3299 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3300 if (handles.empty()) {
3301 mReleasePreviousBuffer = false;
3302 return false;
3303 }
3304
3305 const bool willPresent = willPresentCurrentTransaction();
3306
3307 for (const auto& handle : handles) {
3308 // If this transaction set a buffer on this layer, release its previous buffer
3309 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3310
3311 // If this layer will be presented in this frame
3312 if (willPresent) {
3313 // If this transaction set an acquire fence on this layer, set its acquire time
3314 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3315 handle->frameNumber = mDrawingState.frameNumber;
3316
3317 // Store so latched time and release fence can be set
3318 mDrawingState.callbackHandles.push_back(handle);
3319
3320 } else { // If this layer will NOT need to be relatched and presented this frame
3321 // Notify the transaction completed thread this handle is done
3322 mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
3323 }
3324 }
3325
3326 mReleasePreviousBuffer = false;
3327 mCallbackHandleAcquireTimeOrFence = -1;
3328
3329 return willPresent;
3330}
3331
3332Rect Layer::getBufferSize(const State& /*s*/) const {
3333 // for buffer state layers we use the display frame size as the buffer size.
3334
3335 if (mBufferInfo.mBuffer == nullptr) {
3336 return Rect::INVALID_RECT;
3337 }
3338
3339 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3340 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3341
3342 // Undo any transformations on the buffer and return the result.
3343 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3344 std::swap(bufWidth, bufHeight);
3345 }
3346
3347 if (getTransformToDisplayInverse()) {
3348 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3349 if (invTransform & ui::Transform::ROT_90) {
3350 std::swap(bufWidth, bufHeight);
3351 }
3352 }
3353
3354 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3355}
3356
3357FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3358 if (mBufferInfo.mBuffer == nullptr) {
3359 return parentBounds;
3360 }
3361
3362 return getBufferSize(getDrawingState()).toFloatRect();
3363}
3364
3365bool Layer::fenceHasSignaled() const {
3366 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3367 return true;
3368 }
3369
3370 const bool fenceSignaled =
3371 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3372 if (!fenceSignaled) {
3373 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3374 TimeStats::LatchSkipReason::LateAcquire);
3375 }
3376
3377 return fenceSignaled;
3378}
3379
Vishnu Nairba354102022-08-01 00:14:18 +00003380bool Layer::onPreComposition(nsecs_t refreshStartTime, bool /* updatingOutputGeometryThisFrame */) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003381 for (const auto& handle : mDrawingState.callbackHandles) {
3382 handle->refreshStartTime = refreshStartTime;
3383 }
3384 return hasReadyFrame();
3385}
3386
3387void Layer::setAutoRefresh(bool autoRefresh) {
3388 mDrawingState.autoRefresh = autoRefresh;
3389}
3390
3391bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3392 // 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 +00003393 auto* snapshot = editLayerSnapshot();
3394 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003395
3396 if (mSidebandStreamChanged.exchange(false)) {
3397 const State& s(getDrawingState());
3398 // mSidebandStreamChanged was true
3399 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003400 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003401 if (mSidebandStream != nullptr) {
3402 setTransactionFlags(eTransactionNeeded);
3403 mFlinger->setTransactionFlags(eTraversalNeeded);
3404 }
3405 recomputeVisibleRegions = true;
3406
3407 return true;
3408 }
3409 return false;
3410}
3411
3412bool Layer::hasFrameUpdate() const {
3413 const State& c(getDrawingState());
3414 return (mDrawingStateModified || mDrawingState.modified) &&
3415 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3416}
3417
3418void Layer::updateTexImage(nsecs_t latchTime) {
3419 const State& s(getDrawingState());
3420
3421 if (!s.buffer) {
3422 if (s.bgColorLayer) {
3423 for (auto& handle : mDrawingState.callbackHandles) {
3424 handle->latchTime = latchTime;
3425 }
3426 }
3427 return;
3428 }
3429
3430 for (auto& handle : mDrawingState.callbackHandles) {
3431 if (handle->frameNumber == mDrawingState.frameNumber) {
3432 handle->latchTime = latchTime;
3433 }
3434 }
3435
3436 const int32_t layerId = getSequence();
3437 const uint64_t bufferId = mDrawingState.buffer->getId();
3438 const uint64_t frameNumber = mDrawingState.frameNumber;
3439 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3440 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3441 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3442
3443 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3444 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3445 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3446 FrameTracer::FrameEvent::LATCH);
3447
3448 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3449 if (bufferSurfaceFrame != nullptr &&
3450 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3451 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3452 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3453 // are processing the next state.
3454 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3455 mDrawingState.acquireFenceTime->getSignalTime(),
3456 latchTime);
3457 mDrawingState.bufferSurfaceFrameTX.reset();
3458 }
3459
3460 std::deque<sp<CallbackHandle>> remainingHandles;
3461 mFlinger->getTransactionCallbackInvoker()
3462 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3463 mDrawingState.callbackHandles = remainingHandles;
3464
3465 mDrawingStateModified = false;
3466}
3467
3468void Layer::gatherBufferInfo() {
3469 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3470 decrementPendingBufferCount();
3471 }
3472
3473 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3474 mBufferInfo.mBuffer = mDrawingState.buffer;
3475 mBufferInfo.mFence = mDrawingState.acquireFence;
3476 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3477 mBufferInfo.mPixelFormat =
3478 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3479 mBufferInfo.mFrameLatencyNeeded = true;
3480 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3481 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3482 mBufferInfo.mFence = mDrawingState.acquireFence;
3483 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3484 auto lastDataspace = mBufferInfo.mDataspace;
3485 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3486 if (lastDataspace != mBufferInfo.mDataspace) {
3487 mFlinger->mSomeDataspaceChanged = true;
3488 }
3489 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3490 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3491 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3492 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3493 mBufferInfo.mApi = mDrawingState.api;
3494 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
3495 mBufferInfo.mBufferSlot = mHwcSlotGenerator->getHwcCacheSlot(mDrawingState.clientCacheId);
3496}
3497
3498Rect Layer::computeBufferCrop(const State& s) {
3499 if (s.buffer && !s.bufferCrop.isEmpty()) {
3500 Rect bufferCrop;
3501 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3502 return bufferCrop;
3503 } else if (s.buffer) {
3504 return s.buffer->getBounds();
3505 } else {
3506 return s.bufferCrop;
3507 }
3508}
3509
3510sp<Layer> Layer::createClone() {
3511 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3512 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003513 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003514 layer->mHwcSlotGenerator = mHwcSlotGenerator;
3515 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3516 return layer;
3517}
3518
3519bool Layer::bufferNeedsFiltering() const {
3520 const State& s(getDrawingState());
3521 if (!s.buffer) {
3522 return false;
3523 }
3524
3525 int32_t bufferWidth = static_cast<int32_t>(s.buffer->getWidth());
3526 int32_t bufferHeight = static_cast<int32_t>(s.buffer->getHeight());
3527
3528 // Undo any transformations on the buffer and return the result.
3529 if (s.bufferTransform & ui::Transform::ROT_90) {
3530 std::swap(bufferWidth, bufferHeight);
3531 }
3532
3533 if (s.transformToDisplayInverse) {
3534 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3535 if (invTransform & ui::Transform::ROT_90) {
3536 std::swap(bufferWidth, bufferHeight);
3537 }
3538 }
3539
3540 const Rect layerSize{getBounds()};
3541 int32_t layerWidth = layerSize.getWidth();
3542 int32_t layerHeight = layerSize.getHeight();
3543
3544 // Align the layer orientation with the buffer before comparism
3545 if (mTransformHint & ui::Transform::ROT_90) {
3546 std::swap(layerWidth, layerHeight);
3547 }
3548
3549 return layerWidth != bufferWidth || layerHeight != bufferHeight;
3550}
3551
3552void Layer::decrementPendingBufferCount() {
3553 int32_t pendingBuffers = --mPendingBufferTransactions;
3554 tracePendingBufferCount(pendingBuffers);
3555}
3556
3557void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3558 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3559}
3560
3561/*
3562 * We don't want to send the layer's transform to input, but rather the
3563 * parent's transform. This is because Layer's transform is
3564 * information about how the buffer is placed on screen. The parent's
3565 * transform makes more sense to send since it's information about how the
3566 * layer is placed on screen. This transform is used by input to determine
3567 * how to go from screen space back to window space.
3568 */
3569ui::Transform Layer::getInputTransform() const {
3570 if (!hasBufferOrSidebandStream()) {
3571 return getTransform();
3572 }
3573 sp<Layer> parent = mDrawingParent.promote();
3574 if (parent == nullptr) {
3575 return ui::Transform();
3576 }
3577
3578 return parent->getTransform();
3579}
3580
3581/**
3582 * Similar to getInputTransform, we need to update the bounds to include the transform.
3583 * This is because bounds don't include the buffer transform, where the input assumes
3584 * that's already included.
3585 */
3586Rect Layer::getInputBounds() const {
3587 if (!hasBufferOrSidebandStream()) {
3588 return getCroppedBufferSize(getDrawingState());
3589 }
3590
3591 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
3592 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
3593 return bufferBounds;
3594 }
3595 return mDrawingState.transform.transform(bufferBounds);
3596}
3597
3598bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3599 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3600
3601 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3602 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3603 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3604 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3605 layer_state_t::eReparent;
3606
3607 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3608 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3609 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3610 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3611 layer_state_t::eInputInfoChanged;
3612
3613 if ((s.what & requiredFlags) != requiredFlags) {
3614 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3615 (s.what | requiredFlags) & ~s.what);
3616 return false;
3617 }
3618
3619 if (s.what & deniedFlags) {
3620 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3621 return false;
3622 }
3623
3624 if (s.what & allowedFlags) {
3625 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3626 }
3627
3628 if (s.what & layer_state_t::ePositionChanged) {
3629 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3630 ALOGV("%s: false [ePositionChanged changed]", __func__);
3631 return false;
3632 }
3633 }
3634
3635 if (s.what & layer_state_t::eAlphaChanged) {
3636 if (mDrawingState.color.a != s.alpha) {
3637 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3638 return false;
3639 }
3640 }
3641
3642 if (s.what & layer_state_t::eColorTransformChanged) {
3643 if (mDrawingState.colorTransform != s.colorTransform) {
3644 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3645 return false;
3646 }
3647 }
3648
3649 if (s.what & layer_state_t::eBackgroundColorChanged) {
3650 if (mDrawingState.bgColorLayer || s.bgColorAlpha != 0) {
3651 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3652 return false;
3653 }
3654 }
3655
3656 if (s.what & layer_state_t::eMatrixChanged) {
3657 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3658 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3659 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3660 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3661 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3662 return false;
3663 }
3664 }
3665
3666 if (s.what & layer_state_t::eCornerRadiusChanged) {
3667 if (mDrawingState.cornerRadius != s.cornerRadius) {
3668 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3669 return false;
3670 }
3671 }
3672
3673 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3674 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3675 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3676 return false;
3677 }
3678 }
3679
3680 if (s.what & layer_state_t::eTransformChanged) {
3681 if (mDrawingState.bufferTransform != s.transform) {
3682 ALOGV("%s: false [eTransformChanged changed]", __func__);
3683 return false;
3684 }
3685 }
3686
3687 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3688 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3689 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3690 return false;
3691 }
3692 }
3693
3694 if (s.what & layer_state_t::eCropChanged) {
3695 if (mDrawingState.crop != s.crop) {
3696 ALOGV("%s: false [eCropChanged changed]", __func__);
3697 return false;
3698 }
3699 }
3700
3701 if (s.what & layer_state_t::eDataspaceChanged) {
3702 if (mDrawingState.dataspace != s.dataspace) {
3703 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3704 return false;
3705 }
3706 }
3707
3708 if (s.what & layer_state_t::eHdrMetadataChanged) {
3709 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3710 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3711 return false;
3712 }
3713 }
3714
3715 if (s.what & layer_state_t::eSidebandStreamChanged) {
3716 if (mDrawingState.sidebandStream != s.sidebandStream) {
3717 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3718 return false;
3719 }
3720 }
3721
3722 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3723 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3724 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3725 return false;
3726 }
3727 }
3728
3729 if (s.what & layer_state_t::eShadowRadiusChanged) {
3730 if (mDrawingState.shadowRadius != s.shadowRadius) {
3731 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3732 return false;
3733 }
3734 }
3735
3736 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3737 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3738 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3739 return false;
3740 }
3741 }
3742
3743 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3744 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3745 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3746 return false;
3747 }
3748 }
3749
3750 if (s.what & layer_state_t::eStretchChanged) {
3751 StretchEffect temp = s.stretchEffect;
3752 temp.sanitize();
3753 if (mDrawingState.stretchEffect != temp) {
3754 ALOGV("%s: false [eStretchChanged changed]", __func__);
3755 return false;
3756 }
3757 }
3758
3759 if (s.what & layer_state_t::eBufferCropChanged) {
3760 if (mDrawingState.bufferCrop != s.bufferCrop) {
3761 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3762 return false;
3763 }
3764 }
3765
3766 if (s.what & layer_state_t::eDestinationFrameChanged) {
3767 if (mDrawingState.destinationFrame != s.destinationFrame) {
3768 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3769 return false;
3770 }
3771 }
3772
3773 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3774 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3775 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3776 return false;
3777 }
3778 }
3779
3780 ALOGV("%s: true", __func__);
3781 return true;
3782}
3783
3784bool Layer::isHdrY410() const {
3785 // pixel format is HDR Y410 masquerading as RGBA_1010102
3786 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3787 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3788 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3789}
3790
3791sp<compositionengine::LayerFE> Layer::getCompositionEngineLayerFE() const {
3792 // There's no need to get a CE Layer if the layer isn't going to draw anything.
3793 if (hasSomethingToDraw()) {
3794 return asLayerFE();
3795 } else {
3796 return nullptr;
3797 }
3798}
3799
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003800const Layer::LayerSnapshot* Layer::getLayerSnapshot() const {
3801 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003802}
3803
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003804Layer::LayerSnapshot* Layer::editLayerSnapshot() {
3805 return mSnapshot.get();
3806}
Patrick Williamsbb25f802022-08-30 23:02:34 +00003807const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003808 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003809}
3810
3811void Layer::useSurfaceDamage() {
3812 if (mFlinger->mForceFullDamage) {
3813 surfaceDamageRegion = Region::INVALID_REGION;
3814 } else {
3815 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3816 }
3817}
3818
3819void Layer::useEmptyDamage() {
3820 surfaceDamageRegion.clear();
3821}
3822
3823bool Layer::isOpaque(const Layer::State& s) const {
3824 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3825 // layer's opaque flag.
3826 if (!hasSomethingToDraw()) {
3827 return false;
3828 }
3829
3830 // if the layer has the opaque flag, then we're always opaque
3831 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3832 return true;
3833 }
3834
3835 // If the buffer has no alpha channel, then we are opaque
3836 if (hasBufferOrSidebandStream() && isOpaqueFormat(getPixelFormat())) {
3837 return true;
3838 }
3839
3840 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3841 return fillsColor() && getAlpha() == 1.0_hf;
3842}
3843
3844bool Layer::canReceiveInput() const {
3845 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3846}
3847
3848bool Layer::isVisible() const {
3849 if (!hasSomethingToDraw()) {
3850 return false;
3851 }
3852
3853 if (isHiddenByPolicy()) {
3854 return false;
3855 }
3856
3857 return getAlpha() > 0.0f || hasBlur();
3858}
3859
3860void Layer::onPostComposition(const DisplayDevice* display,
3861 const std::shared_ptr<FenceTime>& glDoneFence,
3862 const std::shared_ptr<FenceTime>& presentFence,
3863 const CompositorTiming& compositorTiming) {
3864 // mFrameLatencyNeeded is true when a new frame was latched for the
3865 // composition.
3866 if (!mBufferInfo.mFrameLatencyNeeded) return;
3867
3868 for (const auto& handle : mDrawingState.callbackHandles) {
3869 handle->gpuCompositionDoneFence = glDoneFence;
3870 handle->compositorTiming = compositorTiming;
3871 }
3872
3873 // Update mFrameTracker.
3874 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3875 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3876
3877 const int32_t layerId = getSequence();
3878 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3879
3880 const auto outputLayer = findOutputLayerForDisplay(display);
3881 if (outputLayer && outputLayer->requiresClientComposition()) {
3882 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3883 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3884 clientCompositionTimestamp,
3885 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3886 // Update the SurfaceFrames in the drawing state
3887 if (mDrawingState.bufferSurfaceFrameTX) {
3888 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3889 }
3890 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3891 surfaceFrame->setGpuComposition();
3892 }
3893 }
3894
3895 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3896 if (frameReadyFence->isValid()) {
3897 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3898 } else {
3899 // There was no fence for this frame, so assume that it was ready
3900 // to be presented at the desired present time.
3901 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3902 }
3903
3904 if (display) {
Dominik Laskowskif8734e02022-08-26 09:06:59 -07003905 const Fps refreshRate = display->refreshRateConfigs().getActiveModePtr()->getFps();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003906 const std::optional<Fps> renderRate =
3907 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3908
3909 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3910 const auto gameMode = getGameMode();
3911
3912 if (presentFence->isValid()) {
3913 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3914 refreshRate, renderRate, vote, gameMode);
3915 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3916 presentFence,
3917 FrameTracer::FrameEvent::PRESENT_FENCE);
3918 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3919 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3920 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003921 // The HWC doesn't support present fences, so use the present timestamp instead.
3922 const nsecs_t presentTimestamp =
3923 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3924
3925 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3926 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3927 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3928
Patrick Williamsbb25f802022-08-30 23:02:34 +00003929 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3930 refreshRate, renderRate, vote, gameMode);
3931 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3932 mCurrentFrameNumber, actualPresentTime,
3933 FrameTracer::FrameEvent::PRESENT_FENCE);
3934 mFrameTracker.setActualPresentTime(actualPresentTime);
3935 }
3936 }
3937
3938 mFrameTracker.advanceFrame();
3939 mBufferInfo.mFrameLatencyNeeded = false;
3940}
3941
3942bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
3943 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3944 getDrawingState().frameNumber);
3945
3946 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3947
3948 if (refreshRequired) {
3949 return refreshRequired;
3950 }
3951
3952 // If the head buffer's acquire fence hasn't signaled yet, return and
3953 // try again later
3954 if (!fenceHasSignaled()) {
3955 ATRACE_NAME("!fenceHasSignaled()");
3956 mFlinger->onLayerUpdate();
3957 return false;
3958 }
3959
3960 updateTexImage(latchTime);
3961 if (mDrawingState.buffer == nullptr) {
3962 return false;
3963 }
3964
3965 // Capture the old state of the layer for comparisons later
3966 BufferInfo oldBufferInfo = mBufferInfo;
3967 const bool oldOpacity = isOpaque(mDrawingState);
3968 mPreviousFrameNumber = mCurrentFrameNumber;
3969 mCurrentFrameNumber = mDrawingState.frameNumber;
3970 gatherBufferInfo();
3971
3972 if (oldBufferInfo.mBuffer == nullptr) {
3973 // the first time we receive a buffer, we need to trigger a
3974 // geometry invalidation.
3975 recomputeVisibleRegions = true;
3976 }
3977
3978 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3979 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3980 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3981 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3982 recomputeVisibleRegions = true;
3983 }
3984
3985 if (oldBufferInfo.mBuffer != nullptr) {
3986 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3987 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3988 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3989 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3990 recomputeVisibleRegions = true;
3991 }
3992 }
3993
3994 if (oldOpacity != isOpaque(mDrawingState)) {
3995 recomputeVisibleRegions = true;
3996 }
3997
3998 return true;
3999}
4000
4001bool Layer::hasReadyFrame() const {
4002 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4003}
4004
4005bool Layer::isProtected() const {
4006 return (mBufferInfo.mBuffer != nullptr) &&
4007 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4008}
4009
4010// As documented in libhardware header, formats in the range
4011// 0x100 - 0x1FF are specific to the HAL implementation, and
4012// are known to have no alpha channel
4013// TODO: move definition for device-specific range into
4014// hardware.h, instead of using hard-coded values here.
4015#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
4016
4017bool Layer::isOpaqueFormat(PixelFormat format) {
4018 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
4019 return true;
4020 }
4021 switch (format) {
4022 case PIXEL_FORMAT_RGBA_8888:
4023 case PIXEL_FORMAT_BGRA_8888:
4024 case PIXEL_FORMAT_RGBA_FP16:
4025 case PIXEL_FORMAT_RGBA_1010102:
4026 case PIXEL_FORMAT_R_8:
4027 return false;
4028 }
4029 // in all other case, we have no blending (also for unknown formats)
4030 return true;
4031}
4032
4033bool Layer::needsFiltering(const DisplayDevice* display) const {
4034 if (!hasBufferOrSidebandStream()) {
4035 return false;
4036 }
4037 const auto outputLayer = findOutputLayerForDisplay(display);
4038 if (outputLayer == nullptr) {
4039 return false;
4040 }
4041
4042 // We need filtering if the sourceCrop rectangle size does not match the
4043 // displayframe rectangle size (not a 1:1 render)
4044 const auto& compositionState = outputLayer->getState();
4045 const auto displayFrame = compositionState.displayFrame;
4046 const auto sourceCrop = compositionState.sourceCrop;
4047 return sourceCrop.getHeight() != displayFrame.getHeight() ||
4048 sourceCrop.getWidth() != displayFrame.getWidth();
4049}
4050
4051bool Layer::needsFilteringForScreenshots(const DisplayDevice* display,
4052 const ui::Transform& inverseParentTransform) const {
4053 if (!hasBufferOrSidebandStream()) {
4054 return false;
4055 }
4056 const auto outputLayer = findOutputLayerForDisplay(display);
4057 if (outputLayer == nullptr) {
4058 return false;
4059 }
4060
4061 // We need filtering if the sourceCrop rectangle size does not match the
4062 // viewport rectangle size (not a 1:1 render)
4063 const auto& compositionState = outputLayer->getState();
4064 const ui::Transform& displayTransform = display->getTransform();
4065 const ui::Transform inverseTransform = inverseParentTransform * displayTransform.inverse();
4066 // Undo the transformation of the displayFrame so that we're back into
4067 // layer-stack space.
4068 const Rect frame = inverseTransform.transform(compositionState.displayFrame);
4069 const FloatRect sourceCrop = compositionState.sourceCrop;
4070
4071 int32_t frameHeight = frame.getHeight();
4072 int32_t frameWidth = frame.getWidth();
4073 // If the display transform had a rotational component then undo the
4074 // rotation so that the orientation matches the source crop.
4075 if (displayTransform.getOrientation() & ui::Transform::ROT_90) {
4076 std::swap(frameHeight, frameWidth);
4077 }
4078 return sourceCrop.getHeight() != frameHeight || sourceCrop.getWidth() != frameWidth;
4079}
4080
4081void Layer::latchAndReleaseBuffer() {
4082 if (hasReadyFrame()) {
4083 bool ignored = false;
4084 latchBuffer(ignored, systemTime());
4085 }
4086 releasePendingBuffer(systemTime());
4087}
4088
4089PixelFormat Layer::getPixelFormat() const {
4090 return mBufferInfo.mPixelFormat;
4091}
4092
4093bool Layer::getTransformToDisplayInverse() const {
4094 return mBufferInfo.mTransformToDisplayInverse;
4095}
4096
4097Rect Layer::getBufferCrop() const {
4098 // this is the crop rectangle that applies to the buffer
4099 // itself (as opposed to the window)
4100 if (!mBufferInfo.mCrop.isEmpty()) {
4101 // if the buffer crop is defined, we use that
4102 return mBufferInfo.mCrop;
4103 } else if (mBufferInfo.mBuffer != nullptr) {
4104 // otherwise we use the whole buffer
4105 return mBufferInfo.mBuffer->getBounds();
4106 } else {
4107 // if we don't have a buffer yet, we use an empty/invalid crop
4108 return Rect();
4109 }
4110}
4111
4112uint32_t Layer::getBufferTransform() const {
4113 return mBufferInfo.mTransform;
4114}
4115
4116ui::Dataspace Layer::getDataSpace() const {
4117 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
4118}
4119
4120ui::Dataspace Layer::getRequestedDataSpace() const {
4121 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4122}
4123
4124ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4125 ui::Dataspace updatedDataspace = dataspace;
4126 // translate legacy dataspaces to modern dataspaces
4127 switch (dataspace) {
4128 case ui::Dataspace::SRGB:
4129 updatedDataspace = ui::Dataspace::V0_SRGB;
4130 break;
4131 case ui::Dataspace::SRGB_LINEAR:
4132 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4133 break;
4134 case ui::Dataspace::JFIF:
4135 updatedDataspace = ui::Dataspace::V0_JFIF;
4136 break;
4137 case ui::Dataspace::BT601_625:
4138 updatedDataspace = ui::Dataspace::V0_BT601_625;
4139 break;
4140 case ui::Dataspace::BT601_525:
4141 updatedDataspace = ui::Dataspace::V0_BT601_525;
4142 break;
4143 case ui::Dataspace::BT709:
4144 updatedDataspace = ui::Dataspace::V0_BT709;
4145 break;
4146 default:
4147 break;
4148 }
4149
4150 return updatedDataspace;
4151}
4152
4153sp<GraphicBuffer> Layer::getBuffer() const {
4154 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4155}
4156
4157void Layer::getDrawingTransformMatrix(bool filteringEnabled, float outMatrix[16]) const {
4158 sp<GraphicBuffer> buffer = getBuffer();
4159 if (!buffer) {
4160 ALOGE("Buffer should not be null!");
4161 return;
4162 }
4163 GLConsumer::computeTransformMatrix(outMatrix, buffer->getWidth(), buffer->getHeight(),
4164 buffer->getPixelFormat(), mBufferInfo.mCrop,
4165 mBufferInfo.mTransform, filteringEnabled);
4166}
4167
4168void Layer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
4169 mTransformHint = getFixedTransformHint();
4170 if (mTransformHint == ui::Transform::ROT_INVALID) {
4171 mTransformHint = displayTransformHint;
4172 }
4173}
4174
4175const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4176 return mBufferInfo.mBuffer;
4177}
4178
4179bool Layer::setColor(const half3& color) {
4180 if (mDrawingState.color.r == color.r && mDrawingState.color.g == color.g &&
4181 mDrawingState.color.b == color.b) {
4182 return false;
4183 }
4184
4185 mDrawingState.sequence++;
4186 mDrawingState.color.r = color.r;
4187 mDrawingState.color.g = color.g;
4188 mDrawingState.color.b = color.b;
4189 mDrawingState.modified = true;
4190 setTransactionFlags(eTransactionNeeded);
4191 return true;
4192}
4193
4194bool Layer::fillsColor() const {
4195 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4196 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4197}
4198
4199bool Layer::hasBlur() const {
4200 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4201}
4202
Vishnu Nairba354102022-08-01 00:14:18 +00004203void Layer::updateSnapshot(bool updateGeometry) {
4204 if (!getCompositionEngineLayerFE()) {
4205 return;
4206 }
4207
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004208 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004209 if (updateGeometry) {
4210 prepareBasicGeometryCompositionState();
4211 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004212 snapshot->roundedCorner = getRoundedCornerState();
4213 snapshot->stretchEffect = getStretchEffect();
4214 snapshot->transformedBounds = mScreenBounds;
4215 if (mEffectiveShadowRadius > 0.f) {
4216 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4217
4218 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4219 // it if transparent regions are present. This may not be necessary since shadows are
4220 // typically cast by layers without transparent regions.
4221 snapshot->shadowSettings.boundaries = mBounds;
4222
4223 const float casterAlpha = snapshot->alpha;
4224 const bool casterIsOpaque =
4225 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4226
4227 // If the casting layer is translucent, we need to fill in the shadow underneath the
4228 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4229 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4230 snapshot->shadowSettings.ambientColor *= casterAlpha;
4231 snapshot->shadowSettings.spotColor *= casterAlpha;
4232 }
4233 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004234 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004235 snapshot->contentOpaque = isOpaque(mDrawingState);
4236 snapshot->isHdrY410 = isHdrY410();
4237 snapshot->bufferNeedsFiltering = bufferNeedsFiltering();
4238 sp<Layer> p = mDrawingParent.promote();
4239 if (p != nullptr) {
4240 snapshot->transform = p->getTransform();
4241 } else {
4242 snapshot->transform.reset();
4243 }
4244 snapshot->bufferSize = getBufferSize(mDrawingState);
4245 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Nairba354102022-08-01 00:14:18 +00004246 preparePerFrameCompositionState();
4247}
4248
Mathias Agopian13127d82013-03-05 17:47:11 -08004249// ---------------------------------------------------------------------------
4250
Marin Shalamanov46084422020-10-13 12:33:42 +02004251std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004252 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4253 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004254}
4255
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004256} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004257
4258#if defined(__gl_h_)
4259#error "don't include gl/gl.h in this file"
4260#endif
4261
4262#if defined(__gl2_h_)
4263#error "don't include gl2/gl2.h in this file"
4264#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004265
4266// TODO(b/129481165): remove the #pragma below and fix conversion issues
4267#pragma clang diagnostic pop // ignored "-Wconversion"