blob: e690aaf691dc660c4f821f071a68ebc1df9b2ff1 [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),
167 mCompositionState{mFlinger->getCompositionEngine().createLayerFECompositionState()},
168 mHwcSlotGenerator(sp<HwcSlotGenerator>::make()) {
169 ALOGV("Creating Layer %s", getDebugName());
170
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700171 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700172 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
173 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
174 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700175 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
176 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Vishnu Naira84a2202022-01-12 20:12:55 -0800177 if (args.sequence) {
178 sSequence = *args.sequence + 1;
179 }
Robert Carr6a160312021-05-17 12:08:20 -0700180 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700181 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700182 mDrawingState.z = 0;
183 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700184 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700185 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700186 mDrawingState.transform.set(0, 0);
187 mDrawingState.frameNumber = 0;
188 mDrawingState.bufferTransform = 0;
189 mDrawingState.transformToDisplayInverse = false;
190 mDrawingState.crop.makeInvalid();
191 mDrawingState.acquireFence = sp<Fence>::make(-1);
192 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
193 mDrawingState.dataspace = ui::Dataspace::UNKNOWN;
Vishnu Nairbc4ee5c2022-08-16 03:19:37 +0000194 mDrawingState.dataspaceRequested = false;
Robert Carr6a160312021-05-17 12:08:20 -0700195 mDrawingState.hdrMetadata.validTypes = 0;
196 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
197 mDrawingState.cornerRadius = 0.0f;
198 mDrawingState.backgroundBlurRadius = 0;
199 mDrawingState.api = -1;
200 mDrawingState.hasColorTransform = false;
201 mDrawingState.colorSpaceAgnostic = false;
202 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
203 mDrawingState.metadata = args.metadata;
204 mDrawingState.shadowRadius = 0.f;
205 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
206 mDrawingState.frameTimelineInfo = {};
207 mDrawingState.postTime = -1;
208 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000209 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700210 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700211 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000212 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700213
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700214 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
215 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700216 mDrawingState.color.r = -1.0_hf;
217 mDrawingState.color.g = -1.0_hf;
218 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700219 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700220
221 mFrameTracker.setDisplayRefreshPeriod(
222 args.flinger->mScheduler->getVsyncPeriodFromRefreshRateConfigs());
Robert Carr2e102c92018-10-23 12:11:15 -0700223
Vishnu Nair0f085c62019-08-30 08:49:12 -0700224 mCallingPid = args.callingPid;
225 mCallingUid = args.callingUid;
chaviw250bcbb2020-08-05 11:17:54 -0700226
227 if (mCallingUid == AID_GRAPHICS || mCallingUid == AID_SYSTEM) {
228 // If the system didn't send an ownerUid, use the callingUid for the ownerUid.
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800229 mOwnerUid = args.metadata.getInt32(gui::METADATA_OWNER_UID, mCallingUid);
230 mOwnerPid = args.metadata.getInt32(gui::METADATA_OWNER_PID, mCallingPid);
chaviw250bcbb2020-08-05 11:17:54 -0700231 } else {
232 // A create layer request from a non system request cannot specify the owner uid
233 mOwnerUid = mCallingUid;
Adithya Srinivasan9febda82020-10-19 10:49:41 -0700234 mOwnerPid = mCallingPid;
chaviw250bcbb2020-08-05 11:17:54 -0700235 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000236
237 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
238 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
239 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
240 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Dominik Laskowski75848362019-11-11 17:57:20 -0800241}
242
243void Layer::onFirstRef() {
244 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700245}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700246
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700247Layer::~Layer() {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000248 // The original layer and the clone layer share the same texture and buffer. Therefore, only
249 // one of the layers, in this case the original layer, needs to handle the deletion. The
250 // original layer and the clone should be removed at the same time so there shouldn't be any
251 // issue with the clone layer trying to use the texture.
252 if (mBufferInfo.mBuffer != nullptr) {
253 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
254 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
255 mBufferInfo.mFence,
256 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
257 mOwnerUid));
258 }
259 if (!isClone()) {
260 // The original layer and the clone layer share the same texture. Therefore, only one of
261 // the layers, in this case the original layer, needs to handle the deletion. The original
262 // layer and the clone should be removed at the same time so there shouldn't be any issue
263 // with the clone layer trying to use the deleted texture.
264 mFlinger->deleteTextureAsync(mTextureName);
265 }
266 const int32_t layerId = getSequence();
267 mFlinger->mTimeStats->onDestroy(layerId);
268 mFlinger->mFrameTracer->onDestroy(layerId);
269
David Sodman577c8962017-12-08 14:50:53 -0800270 sp<Client> c(mClientRef.promote());
271 if (c != 0) {
272 c->detachLayer(this);
273 }
274
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000275 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700276 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700277
278 if (mDrawingState.sidebandStream != nullptr) {
279 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
280 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700281 if (mHadClonedChild) {
282 mFlinger->mNumClones--;
283 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700284}
285
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700286LayerCreationArgs::LayerCreationArgs(SurfaceFlinger* flinger, sp<Client> client, std::string name,
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800287 uint32_t flags, LayerMetadata metadata)
Vishnu Nair0f085c62019-08-30 08:49:12 -0700288 : flinger(flinger),
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700289 client(std::move(client)),
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700290 name(std::move(name)),
Vishnu Nair0f085c62019-08-30 08:49:12 -0700291 flags(flags),
292 metadata(std::move(metadata)) {
293 IPCThreadState* ipc = IPCThreadState::self();
294 callingPid = ipc->getCallingPid();
295 callingUid = ipc->getCallingUid();
296}
297
Mathias Agopian13127d82013-03-05 17:47:11 -0800298// ---------------------------------------------------------------------------
299// callbacks
300// ---------------------------------------------------------------------------
301
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700302void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700303 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700304 return;
305 }
Robert Carr2e102c92018-10-23 12:11:15 -0700306
Robert Carr6a160312021-05-17 12:08:20 -0700307 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700308 if (strongRelative == nullptr) {
309 setZOrderRelativeOf(nullptr);
310 return;
311 }
312
313 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700314 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700315 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800316 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700317 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700318}
319
320void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700321 if (!mRemovedFromDrawingState) {
322 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700323 mFlinger->mScheduler->deregisterLayer(this);
324 }
Rob Carr4bba3702018-10-08 21:53:30 +0000325
Ady Abrahamd11bade2022-08-01 16:18:03 -0700326 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700327}
Chia-I Wu38512252017-05-17 14:36:16 -0700328
chaviw68d4dab2020-06-08 15:07:32 -0700329sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000330 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700331 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700332 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700333 }
334 return parent->getRootLayer();
335}
336
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700337void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700338 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
339 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700340 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700341
342 traverse(LayerVector::StateSet::Current, [&](Layer* layer) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700343 layer->removeFromCurrentState();
344 layer->removeRelativeZ(layersInTree);
chaviw68d4dab2020-06-08 15:07:32 -0700345 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700346}
347
chaviw61626f22018-11-15 16:26:27 -0800348void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700349 if (mRemovedFromDrawingState) {
350 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700351 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700352 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700353 }
chaviw61626f22018-11-15 16:26:27 -0800354
355 for (const auto& child : mCurrentChildren) {
356 child->addToCurrentState();
357 }
358}
359
Mathias Agopian13127d82013-03-05 17:47:11 -0800360// ---------------------------------------------------------------------------
361// set-up
362// ---------------------------------------------------------------------------
363
chaviw13fdc492017-06-27 12:40:18 -0700364bool Layer::getPremultipledAlpha() const {
365 return mPremultipliedAlpha;
366}
367
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700368sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800369 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700370 if (mGetHandleCalled) {
371 ALOGE("Get handle called twice" );
372 return nullptr;
373 }
374 mGetHandleCalled = true;
Ady Abrahamd11bade2022-08-01 16:18:03 -0700375 return sp<Handle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800376}
377
378// ---------------------------------------------------------------------------
379// h/w composer set-up
380// ---------------------------------------------------------------------------
381
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700382static Rect reduce(const Rect& win, const Region& exclude) {
383 if (CC_LIKELY(exclude.isEmpty())) {
384 return win;
385 }
386 if (exclude.isRect()) {
387 return win.reduce(exclude.getBounds());
388 }
389 return Region(win).subtract(exclude).getBounds();
390}
391
Dan Stoza80d61162017-12-20 15:57:52 -0800392static FloatRect reduce(const FloatRect& win, const Region& exclude) {
393 if (CC_LIKELY(exclude.isEmpty())) {
394 return win;
395 }
396 // Convert through Rect (by rounding) for lack of FloatRegion
397 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
398}
399
Vishnu Nair4351ad52019-02-11 14:13:02 -0800400Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800401 if (!reduceTransparentRegion) {
402 return Rect{mScreenBounds};
403 }
404
405 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800406 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800407 // Transform to screen space.
408 bounds = t.transform(bounds);
409 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700410}
411
Vishnu Nair4351ad52019-02-11 14:13:02 -0800412FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000413 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800414 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700415}
416
Vishnu Nairf0c28512019-02-08 12:40:28 -0800417FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
418 // Subtract the transparent region and snap to the bounds.
419 return reduce(mBounds, activeTransparentRegion);
420}
421
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700422void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
423 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800424 const State& s(getDrawingState());
425
426 // Calculate effective layer transform
427 mEffectiveTransform = parentTransform * getActiveTransform(s);
428
Garfield Tan2c1782c2022-02-16 15:25:05 -0800429 if (CC_UNLIKELY(!isTransformValid())) {
430 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
431 getDebugName());
432 return;
433 }
434
Vishnu Nair4351ad52019-02-11 14:13:02 -0800435 // Transform parent bounds to layer space
436 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
437
Vishnu Nairc652ff82019-03-15 12:48:54 -0700438 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800439 mSourceBounds = computeSourceBounds(parentBounds);
440
441 // Calculate bounds by croping diplay frame with layer crop and parent bounds
442 FloatRect bounds = mSourceBounds;
443 const Rect layerCrop = getCrop(s);
444 if (!layerCrop.isEmpty()) {
445 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
446 }
447 bounds = bounds.intersect(parentBounds);
448
449 mBounds = bounds;
450 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700451
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700452 // Use the layer's own shadow radius if set. Otherwise get the radius from
453 // parent.
454 if (s.shadowRadius > 0.f) {
455 mEffectiveShadowRadius = s.shadowRadius;
456 } else {
457 mEffectiveShadowRadius = parentShadowRadius;
458 }
459
460 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
461 // don't pass it to its children.
462 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
463
Vishnu Nair4351ad52019-02-11 14:13:02 -0800464 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700465 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800466 }
Vishnu Nairba354102022-08-01 00:14:18 +0000467
468 if (mPotentialCursor) {
469 prepareCursorCompositionState();
470 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800471}
472
Vishnu Nair60356342018-11-13 13:00:45 -0800473Rect Layer::getCroppedBufferSize(const State& s) const {
474 Rect size = getBufferSize(s);
475 Rect crop = getCrop(s);
476 if (!crop.isEmpty() && size.isValid()) {
477 size.intersect(crop, &size);
478 } else if (!crop.isEmpty()) {
479 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700480 }
Vishnu Nair60356342018-11-13 13:00:45 -0800481 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800482}
483
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700484void Layer::setupRoundedCornersCropCoordinates(Rect win,
485 const FloatRect& roundedCornersCrop) const {
486 // Translate win by the rounded corners rect coordinates, to have all values in
487 // layer coordinate space.
488 win.left -= roundedCornersCrop.left;
489 win.right -= roundedCornersCrop.left;
490 win.top -= roundedCornersCrop.top;
491 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700492}
493
Lloyd Piquede196652020-01-22 17:29:58 -0800494void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800495 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800496 const auto alpha = static_cast<float>(getAlpha());
497 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700498 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800499
500 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
501 if (!opaque || alpha != 1.0f) {
502 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
503 : Hwc2::IComposerClient::BlendMode::COVERAGE;
504 }
505
Lloyd Piquede196652020-01-22 17:29:58 -0800506 auto* compositionState = editCompositionState();
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700507 compositionState->outputFilter = getOutputFilter();
Lloyd Piquede196652020-01-22 17:29:58 -0800508 compositionState->isVisible = isVisible();
509 compositionState->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
510 compositionState->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800511
Lloyd Piquede196652020-01-22 17:29:58 -0800512 compositionState->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800513 contentDirty = false;
514
Lloyd Piquede196652020-01-22 17:29:58 -0800515 compositionState->geomLayerBounds = mBounds;
516 compositionState->geomLayerTransform = getTransform();
517 compositionState->geomInverseLayerTransform = compositionState->geomLayerTransform.inverse();
518 compositionState->transparentRegionHint = getActiveTransparentRegion(drawingState);
Lloyd Piquec6687342019-03-07 21:34:57 -0800519
Lloyd Piquede196652020-01-22 17:29:58 -0800520 compositionState->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
521 compositionState->alpha = alpha;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400522 compositionState->backgroundBlurRadius = drawingState.backgroundBlurRadius;
523 compositionState->blurRegions = drawingState.blurRegions;
John Reckc00c6692021-02-16 11:37:33 -0500524 compositionState->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800525}
526
Lloyd Piquede196652020-01-22 17:29:58 -0800527void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800528 const auto& drawingState{getDrawingState()};
Lloyd Piquede196652020-01-22 17:29:58 -0800529 auto* compositionState = editCompositionState();
David Sodman15094112018-10-11 09:39:37 -0700530
Lloyd Piquede196652020-01-22 17:29:58 -0800531 compositionState->geomBufferSize = getBufferSize(drawingState);
532 compositionState->geomContentCrop = getBufferCrop();
533 compositionState->geomCrop = getCrop(drawingState);
534 compositionState->geomBufferTransform = getBufferTransform();
535 compositionState->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
536 compositionState->geomUsesSourceCrop = usesSourceCrop();
537 compositionState->isSecure = isSecure();
538
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800539 compositionState->metadata.clear();
540 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
541 for (const auto& [key, mandatory] : supportedMetadata) {
542 const auto& genericLayerMetadataCompatibilityMap =
543 mFlinger->getGenericLayerMetadataKeyMap();
544 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
545 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
546 continue;
547 }
548 const uint32_t id = compatIter->second;
549
550 auto it = drawingState.metadata.mMap.find(id);
551 if (it == std::end(drawingState.metadata.mMap)) {
552 continue;
553 }
554
555 compositionState->metadata
556 .emplace(key, compositionengine::GenericLayerMetadataEntry{mandatory, it->second});
557 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800558}
David Sodmanba340492018-08-05 21:51:33 -0700559
Lloyd Piquede196652020-01-22 17:29:58 -0800560void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800561 const auto& drawingState{getDrawingState()};
Lloyd Piquede196652020-01-22 17:29:58 -0800562 auto* compositionState = editCompositionState();
Lloyd Piquef5275482019-01-29 18:42:42 -0800563
Lloyd Piquede196652020-01-22 17:29:58 -0800564 compositionState->forceClientComposition = false;
565
566 compositionState->isColorspaceAgnostic = isColorSpaceAgnostic();
567 compositionState->dataspace = getDataSpace();
568 compositionState->colorTransform = getColorTransform();
569 compositionState->colorTransformIsIdentity = !hasColorTransform();
570 compositionState->surfaceDamage = surfaceDamageRegion;
571 compositionState->hasProtectedContent = isProtected();
Sally Qi81d95e62022-03-21 19:41:33 -0700572 compositionState->dimmingEnabled = isDimmingEnabled();
Lloyd Pique688abd42019-02-15 15:42:24 -0800573
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700574 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700575
Lloyd Piquede196652020-01-22 17:29:58 -0800576 compositionState->isOpaque =
Lloyd Pique688abd42019-02-15 15:42:24 -0800577 isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800578
579 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400580 // Rounded corners no longer force client composition, since we may use a
581 // hole punch so that the layer will appear to have rounded corners.
582 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
John Reckc00c6692021-02-16 11:37:33 -0500583 compositionState->stretchEffect.hasEffect()) {
Lloyd Piquede196652020-01-22 17:29:58 -0800584 compositionState->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800585 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700586 // If there are no visible region changes, we still need to update blur parameters.
587 compositionState->blurRegions = drawingState.blurRegions;
588 compositionState->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400589
590 // Layer framerate is used in caching decisions.
591 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
592 // LayerFECompositionState where it would be visible to Flattener.
593 compositionState->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000594
595 if (hasBufferOrSidebandStream()) {
596 preparePerFrameBufferCompositionState();
597 } else {
598 preparePerFrameEffectsCompositionState();
599 }
600}
601
602void Layer::preparePerFrameBufferCompositionState() {
603 // Sideband layers
604 auto* compositionState = editCompositionState();
605 if (compositionState->sidebandStream.get() && !compositionState->sidebandStreamHasFrame) {
606 compositionState->compositionType =
607 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
608 return;
609 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
610 compositionState->compositionType =
611 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
612 } else {
613 // Normal buffer layers
614 compositionState->hdrMetadata = mBufferInfo.mHdrMetadata;
615 compositionState->compositionType = mPotentialCursor
616 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
617 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
618 }
619
620 compositionState->buffer = getBuffer();
621 compositionState->bufferSlot = (mBufferInfo.mBufferSlot == BufferQueue::INVALID_BUFFER_SLOT)
622 ? 0
623 : mBufferInfo.mBufferSlot;
624 compositionState->acquireFence = mBufferInfo.mFence;
625 compositionState->frameNumber = mBufferInfo.mFrameNumber;
626 compositionState->sidebandStreamHasFrame = false;
627}
628
629void Layer::preparePerFrameEffectsCompositionState() {
630 auto* compositionState = editCompositionState();
631 compositionState->color = getColor();
632 compositionState->compositionType =
633 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800634}
635
Lloyd Piquede196652020-01-22 17:29:58 -0800636void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800637 const State& drawingState{getDrawingState()};
Lloyd Piquede196652020-01-22 17:29:58 -0800638 auto* compositionState = editCompositionState();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800639
640 // Apply the layer's transform, followed by the display's global transform
641 // Here we're guaranteed that the layer's transform preserves rects
642 Rect win = getCroppedBufferSize(drawingState);
643 // Subtract the transparent region and snap to the bounds
644 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
645 Rect frame(getTransform().transform(bounds));
646
Lloyd Piquede196652020-01-22 17:29:58 -0800647 compositionState->cursorFrame = frame;
648}
649
650sp<compositionengine::LayerFE> Layer::asLayerFE() const {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700651 compositionengine::LayerFE* layerFE = const_cast<compositionengine::LayerFE*>(
Lloyd Piquede196652020-01-22 17:29:58 -0800652 static_cast<const compositionengine::LayerFE*>(this));
Ady Abrahamd11bade2022-08-01 16:18:03 -0700653 return sp<compositionengine::LayerFE>::fromExisting(layerFE);
Lloyd Piquede196652020-01-22 17:29:58 -0800654}
655
Lloyd Piquea83776c2019-01-29 18:42:32 -0800656const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700657 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800658}
659
Mathias Agopian13127d82013-03-05 17:47:11 -0800660// ---------------------------------------------------------------------------
661// drawing...
662// ---------------------------------------------------------------------------
663
Vishnu Nair9b079a22020-01-21 14:36:08 -0800664std::optional<compositionengine::LayerFE::LayerSettings> Layer::prepareClientComposition(
Patrick Williams16d8b2c2022-08-08 17:29:05 +0000665 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000666 std::optional<compositionengine::LayerFE::LayerSettings> layerSettings =
667 prepareClientCompositionInternal(targetSettings);
668 // Nothing to render.
669 if (!layerSettings) {
670 return {};
671 }
672
673 // HWC requests to clear this layer.
674 if (targetSettings.clearContent) {
675 prepareClearClientComposition(*layerSettings, false /* blackout */);
676 return layerSettings;
677 }
678
679 // set the shadow for the layer if needed
680 prepareShadowClientComposition(*layerSettings, targetSettings.viewport);
681
682 return layerSettings;
683}
684
685std::optional<compositionengine::LayerFE::LayerSettings> Layer::prepareClientCompositionInternal(
686 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
687 ATRACE_CALL();
688
Lloyd Piquede196652020-01-22 17:29:58 -0800689 if (!getCompositionState()) {
Lloyd Piquef16688f2019-02-19 17:47:57 -0800690 return {};
691 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800692
Vishnu Nair4351ad52019-02-11 14:13:02 -0800693 FloatRect bounds = getBounds();
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000694 half alpha = getAlpha();
Vishnu Nair9b079a22020-01-21 14:36:08 -0800695
696 compositionengine::LayerFE::LayerSettings layerSettings;
Lloyd Piquef16688f2019-02-19 17:47:57 -0800697 layerSettings.geometry.boundaries = bounds;
chaviwc6ad8af2020-08-03 11:33:30 -0700698 layerSettings.geometry.positionTransform = getTransform().asMatrix4();
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000699
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400700 // skip drawing content if the targetSettings indicate the content will be occluded
Ady Abrahambaa6cf52021-07-13 14:02:19 -0700701 const bool drawContent = targetSettings.realContentIsVisible || targetSettings.clearContent;
702 layerSettings.skipContentDraw = !drawContent;
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400703
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000704 if (hasColorTransform()) {
Lloyd Piquef16688f2019-02-19 17:47:57 -0800705 layerSettings.colorTransform = getColorTransform();
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000706 }
707
708 const auto roundedCornerState = getRoundedCornerState();
Lloyd Piquef16688f2019-02-19 17:47:57 -0800709 layerSettings.geometry.roundedCornersRadius = roundedCornerState.radius;
710 layerSettings.geometry.roundedCornersCrop = roundedCornerState.cropRect;
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000711
Lloyd Piquef16688f2019-02-19 17:47:57 -0800712 layerSettings.alpha = alpha;
chaviw4244e032019-09-04 11:27:49 -0700713 layerSettings.sourceDataspace = getDataSpace();
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700714
Alec Mouridda07d92022-04-25 22:39:25 +0000715 // Override the dataspace transfer from 170M to sRGB if the device configuration requests this.
716 // We do this here instead of in buffer info so that dumpsys can still report layers that are
717 // using the 170M transfer.
718 if (mFlinger->mTreat170mAsSrgb &&
719 (layerSettings.sourceDataspace & HAL_DATASPACE_TRANSFER_MASK) ==
720 HAL_DATASPACE_TRANSFER_SMPTE_170M) {
721 layerSettings.sourceDataspace = static_cast<ui::Dataspace>(
722 (layerSettings.sourceDataspace & HAL_DATASPACE_STANDARD_MASK) |
723 (layerSettings.sourceDataspace & HAL_DATASPACE_RANGE_MASK) |
724 HAL_DATASPACE_TRANSFER_SRGB);
725 }
726
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700727 layerSettings.whitePointNits = targetSettings.whitePointNits;
Alec Mourif54453c2021-05-13 16:28:28 -0700728 switch (targetSettings.blurSetting) {
729 case LayerFE::ClientCompositionTargetSettings::BlurSetting::Enabled:
730 layerSettings.backgroundBlurRadius = getBackgroundBlurRadius();
731 layerSettings.blurRegions = getBlurRegions();
732 layerSettings.blurRegionTransform =
733 getActiveTransform(getDrawingState()).inverse().asMatrix4();
734 break;
735 case LayerFE::ClientCompositionTargetSettings::BlurSetting::BackgroundBlurOnly:
736 layerSettings.backgroundBlurRadius = getBackgroundBlurRadius();
737 break;
738 case LayerFE::ClientCompositionTargetSettings::BlurSetting::BlurRegionsOnly:
739 layerSettings.blurRegions = getBlurRegions();
740 layerSettings.blurRegionTransform =
741 getActiveTransform(getDrawingState()).inverse().asMatrix4();
742 break;
743 case LayerFE::ClientCompositionTargetSettings::BlurSetting::Disabled:
744 default:
745 break;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +0100746 }
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700747 layerSettings.stretchEffect = getStretchEffect();
Ana Krulec6eab17a2020-12-09 15:52:36 -0800748 // Record the name of the layer for debugging further down the stack.
749 layerSettings.name = getName();
Patrick Williamsbb25f802022-08-30 23:02:34 +0000750
Vishnu Nairf115db82022-09-06 16:59:33 -0700751 if (hasEffect() && !hasBufferOrSidebandStream()) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000752 prepareEffectsClientComposition(layerSettings, targetSettings);
753 return layerSettings;
754 }
755
756 prepareBufferStateClientComposition(layerSettings, targetSettings);
Lloyd Piquef16688f2019-02-19 17:47:57 -0800757 return layerSettings;
Mathias Agopian13127d82013-03-05 17:47:11 -0800758}
759
Vishnu Nairb87d94f2020-02-13 09:17:36 -0800760void Layer::prepareClearClientComposition(LayerFE::LayerSettings& layerSettings,
761 bool blackout) const {
762 layerSettings.source.buffer.buffer = nullptr;
763 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
764 layerSettings.disableBlending = true;
Vishnu Nair3b653e72020-02-24 16:40:50 -0800765 layerSettings.bufferId = 0;
Vishnu Nairb87d94f2020-02-13 09:17:36 -0800766 layerSettings.frameNumber = 0;
767
768 // If layer is blacked out, force alpha to 1 so that we draw a black color layer.
769 layerSettings.alpha = blackout ? 1.0f : 0.0f;
Alec Mouribd17b3b2020-12-17 11:08:30 -0800770 layerSettings.name = getName();
Vishnu Nairb87d94f2020-02-13 09:17:36 -0800771}
772
Patrick Williamsbb25f802022-08-30 23:02:34 +0000773void Layer::prepareEffectsClientComposition(
774 compositionengine::LayerFE::LayerSettings& layerSettings,
775 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
776 // If fill bounds are occluded or the fill color is invalid skip the fill settings.
777 if (targetSettings.realContentIsVisible && fillsColor()) {
778 // Set color for color fill settings.
779 layerSettings.source.solidColor = getColor().rgb;
780 } else if (hasBlur() || drawShadows()) {
781 layerSettings.skipContentDraw = true;
782 }
783}
784
785void Layer::prepareBufferStateClientComposition(
786 compositionengine::LayerFE::LayerSettings& layerSettings,
787 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
Patrick Williams22e33d62022-09-02 19:18:16 +0000788 if (CC_UNLIKELY(!mBufferInfo.mBuffer)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000789 // For surfaceview of tv sideband, there is no activeBuffer
790 // in bufferqueue, we need return LayerSettings.
791 return;
792 }
793 const bool blackOutLayer = (isProtected() && !targetSettings.supportsProtectedContent) ||
794 ((isSecure() || isProtected()) && !targetSettings.isSecure);
795 const bool bufferCanBeUsedAsHwTexture =
796 mBufferInfo.mBuffer->getUsage() & GraphicBuffer::USAGE_HW_TEXTURE;
797 if (blackOutLayer || !bufferCanBeUsedAsHwTexture) {
798 ALOGE_IF(!bufferCanBeUsedAsHwTexture, "%s is blacked out as buffer is not gpu readable",
799 mName.c_str());
800 prepareClearClientComposition(layerSettings, true /* blackout */);
801 return;
802 }
803
804 const State& s(getDrawingState());
805 layerSettings.source.buffer.buffer = mBufferInfo.mBuffer;
806 layerSettings.source.buffer.isOpaque = isOpaque(s);
807 layerSettings.source.buffer.fence = mBufferInfo.mFence;
808 layerSettings.source.buffer.textureName = mTextureName;
809 layerSettings.source.buffer.usePremultipliedAlpha = getPremultipledAlpha();
810 layerSettings.source.buffer.isY410BT2020 = isHdrY410();
811 bool hasSmpte2086 = mBufferInfo.mHdrMetadata.validTypes & HdrMetadata::SMPTE2086;
812 bool hasCta861_3 = mBufferInfo.mHdrMetadata.validTypes & HdrMetadata::CTA861_3;
813 float maxLuminance = 0.f;
814 if (hasSmpte2086 && hasCta861_3) {
815 maxLuminance = std::min(mBufferInfo.mHdrMetadata.smpte2086.maxLuminance,
816 mBufferInfo.mHdrMetadata.cta8613.maxContentLightLevel);
817 } else if (hasSmpte2086) {
818 maxLuminance = mBufferInfo.mHdrMetadata.smpte2086.maxLuminance;
819 } else if (hasCta861_3) {
820 maxLuminance = mBufferInfo.mHdrMetadata.cta8613.maxContentLightLevel;
821 } else {
822 switch (layerSettings.sourceDataspace & HAL_DATASPACE_TRANSFER_MASK) {
823 case HAL_DATASPACE_TRANSFER_ST2084:
824 case HAL_DATASPACE_TRANSFER_HLG:
825 // Behavior-match previous releases for HDR content
826 maxLuminance = defaultMaxLuminance;
827 break;
828 }
829 }
830 layerSettings.source.buffer.maxLuminanceNits = maxLuminance;
831 layerSettings.frameNumber = mCurrentFrameNumber;
832 layerSettings.bufferId = mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getId() : 0;
833
834 const bool useFiltering =
835 targetSettings.needsFiltering || mNeedsFiltering || bufferNeedsFiltering();
836
837 // Query the texture matrix given our current filtering mode.
838 float textureMatrix[16];
839 getDrawingTransformMatrix(useFiltering, textureMatrix);
840
841 if (getTransformToDisplayInverse()) {
842 /*
843 * the code below applies the primary display's inverse transform to
844 * the texture transform
845 */
846 uint32_t transform = DisplayDevice::getPrimaryDisplayRotationFlags();
847 mat4 tr = inverseOrientation(transform);
848
849 /**
850 * TODO(b/36727915): This is basically a hack.
851 *
852 * Ensure that regardless of the parent transformation,
853 * this buffer is always transformed from native display
854 * orientation to display orientation. For example, in the case
855 * of a camera where the buffer remains in native orientation,
856 * we want the pixels to always be upright.
857 */
858 sp<Layer> p = mDrawingParent.promote();
859 if (p != nullptr) {
860 const auto parentTransform = p->getTransform();
861 tr = tr * inverseOrientation(parentTransform.getOrientation());
862 }
863
864 // and finally apply it to the original texture matrix
865 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
866 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
867 }
868
869 const Rect win{getBounds()};
870 float bufferWidth = getBufferSize(s).getWidth();
871 float bufferHeight = getBufferSize(s).getHeight();
872
Patrick Williams83f36b22022-09-14 17:57:35 +0000873 // Layers can have a "buffer size" of [0, 0, -1, -1] when no display frame has
Patrick Williamsbb25f802022-08-30 23:02:34 +0000874 // been set and there is no parent layer bounds. In that case, the scale is meaningless so
875 // ignore them.
876 if (!getBufferSize(s).isValid()) {
877 bufferWidth = float(win.right) - float(win.left);
878 bufferHeight = float(win.bottom) - float(win.top);
879 }
880
881 const float scaleHeight = (float(win.bottom) - float(win.top)) / bufferHeight;
882 const float scaleWidth = (float(win.right) - float(win.left)) / bufferWidth;
883 const float translateY = float(win.top) / bufferHeight;
884 const float translateX = float(win.left) / bufferWidth;
885
886 // Flip y-coordinates because GLConsumer expects OpenGL convention.
887 mat4 tr = mat4::translate(vec4(.5f, .5f, 0.f, 1.f)) * mat4::scale(vec4(1.f, -1.f, 1.f, 1.f)) *
888 mat4::translate(vec4(-.5f, -.5f, 0.f, 1.f)) *
889 mat4::translate(vec4(translateX, translateY, 0.f, 1.f)) *
890 mat4::scale(vec4(scaleWidth, scaleHeight, 1.0f, 1.0f));
891
892 layerSettings.source.buffer.useTextureFiltering = useFiltering;
893 layerSettings.source.buffer.textureTransform =
894 mat4(static_cast<const float*>(textureMatrix)) * tr;
895
896 return;
897}
898
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500899aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
900 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700901 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800902 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500903 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800904 }
905 if (outputLayer->getState().hwc) {
906 return (*outputLayer->getState().hwc).hwcCompositionType;
907 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500908 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800909 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800910}
911
Mathias Agopian13127d82013-03-05 17:47:11 -0800912// ----------------------------------------------------------------------------
913// local state
914// ----------------------------------------------------------------------------
915
David Sodman41fdfc92017-11-06 16:09:56 -0800916bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800917 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700918 if (s.flags & layer_state_t::eLayerSecure) {
919 return true;
920 }
921
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000922 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700923 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700924}
925
Mathias Agopian13127d82013-03-05 17:47:11 -0800926// ----------------------------------------------------------------------------
927// transaction
928// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800929
Marissa Wall61c58622018-07-18 10:12:20 -0700930uint32_t Layer::doTransaction(uint32_t flags) {
931 ATRACE_CALL();
932
Robert Carr0758e5d2021-03-11 22:15:04 -0800933 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700934 mDrawingStateModified = mDrawingState.modified;
935 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700936
Alec Mourib416efd2018-09-06 21:01:59 +0000937 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700938
Robert Carr6a160312021-05-17 12:08:20 -0700939 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800940 // invalidate and recompute the visible regions if needed
941 flags |= Layer::eVisibleRegion;
942 }
943
Robert Carr6a160312021-05-17 12:08:20 -0700944 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800945 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000946 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800947 flags |= eVisibleRegion;
948 this->contentDirty = true;
949
950 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700951 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800952 }
953
Arthur Hung9ed43392022-05-27 06:31:57 +0000954 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
955 mFlinger->mUpdateInputInfo = true;
956 }
957
Robert Carr6a160312021-05-17 12:08:20 -0700958 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800959
Mathias Agopian13127d82013-03-05 17:47:11 -0800960 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800961}
962
Robert Carr6a160312021-05-17 12:08:20 -0700963void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000964 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
965 // bufferSurfaceFrameTX will be presented in latchBuffer.
966 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
967 if (surfaceFrame->getPresentState() != PresentState::Presented) {
968 // With applyPendingStates, we could end up having presented surfaceframes from previous
969 // states
970 surfaceFrame->setPresentState(PresentState::Presented);
971 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
972 }
973 }
Robert Carr6a160312021-05-17 12:08:20 -0700974 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700975}
976
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700977uint32_t Layer::clearTransactionFlags(uint32_t mask) {
978 const auto flags = mTransactionFlags & mask;
979 mTransactionFlags &= ~mask;
980 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800981}
982
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700983void Layer::setTransactionFlags(uint32_t mask) {
984 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800985}
986
Robert Carr1f0a16a2016-10-24 16:27:39 -0700987bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
988 ssize_t idx = mCurrentChildren.indexOf(childLayer);
989 if (idx < 0) {
990 return false;
991 }
992 if (childLayer->setLayer(z)) {
993 mCurrentChildren.removeAt(idx);
994 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800995 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700996 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800997 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700998}
999
Robert Carr503c7042017-09-27 15:06:08 -07001000bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
1001 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
1002 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1003 if (idx < 0) {
1004 return false;
1005 }
1006 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
1007 mCurrentChildren.removeAt(idx);
1008 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -08001009 return true;
Robert Carr503c7042017-09-27 15:06:08 -07001010 }
Robert Carr503d2bd2017-12-04 15:49:47 -08001011 return false;
Robert Carr503c7042017-09-27 15:06:08 -07001012}
1013
Robert Carrae060832016-11-28 10:51:00 -08001014bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -07001015 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
1016 mDrawingState.sequence++;
1017 mDrawingState.z = z;
1018 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001019
Robert Carra70e91c2021-06-11 13:59:52 -07001020 mFlinger->mSomeChildrenChanged = true;
1021
Robert Carrdb66e622017-04-10 16:55:57 -07001022 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -07001023 if (mDrawingState.zOrderRelativeOf != nullptr) {
1024 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -07001025 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001026 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -07001027 }
chaviw606e5cf2019-03-01 10:12:10 -08001028 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -07001029 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001030 setTransactionFlags(eTransactionNeeded);
1031 return true;
1032}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001033
Robert Carrdb66e622017-04-10 16:55:57 -07001034void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -07001035 mDrawingState.zOrderRelatives.remove(relative);
1036 mDrawingState.sequence++;
1037 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -07001038 setTransactionFlags(eTransactionNeeded);
1039}
1040
1041void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -07001042 mDrawingState.zOrderRelatives.add(relative);
1043 mDrawingState.modified = true;
1044 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -07001045 setTransactionFlags(eTransactionNeeded);
1046}
1047
chaviw606e5cf2019-03-01 10:12:10 -08001048void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -07001049 mDrawingState.zOrderRelativeOf = relativeOf;
1050 mDrawingState.sequence++;
1051 mDrawingState.modified = true;
1052 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -07001053
chaviw606e5cf2019-03-01 10:12:10 -08001054 setTransactionFlags(eTransactionNeeded);
1055}
1056
Robert Carr503d2bd2017-12-04 15:49:47 -08001057bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nairf9096652021-07-20 18:49:42 -07001058 sp<Layer> relative = fromHandle(relativeToHandle).promote();
Robert Carrdb66e622017-04-10 16:55:57 -07001059 if (relative == nullptr) {
1060 return false;
1061 }
1062
Robert Carr6a160312021-05-17 12:08:20 -07001063 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
1064 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -08001065 return false;
1066 }
1067
Robert Carr88b85e12022-03-21 15:47:35 -07001068 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
1069 (relative->mDrawingState.zOrderRelativeOf == this)) {
1070 ALOGE("Detected relative layer loop between %s and %s",
1071 mName.c_str(), relative->mName.c_str());
1072 ALOGE("Ignoring new call to set relative layer");
1073 return false;
1074 }
1075
Robert Carra70e91c2021-06-11 13:59:52 -07001076 mFlinger->mSomeChildrenChanged = true;
1077
Robert Carr6a160312021-05-17 12:08:20 -07001078 mDrawingState.sequence++;
1079 mDrawingState.modified = true;
1080 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -07001081
Robert Carr6a160312021-05-17 12:08:20 -07001082 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -07001083 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001084 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -07001085 }
chaviw606e5cf2019-03-01 10:12:10 -08001086 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001087 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -07001088
1089 setTransactionFlags(eTransactionNeeded);
1090
1091 return true;
1092}
1093
Winson Chunga30f7c92021-06-29 15:42:56 -07001094bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
1095 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
1096 mDrawingState.isTrustedOverlay = isTrustedOverlay;
1097 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00001098 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -07001099 setTransactionFlags(eTransactionNeeded);
1100 return true;
1101}
1102
1103bool Layer::isTrustedOverlay() const {
1104 if (getDrawingState().isTrustedOverlay) {
1105 return true;
1106 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001107 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -07001108 return (p != nullptr) && p->isTrustedOverlay();
1109}
1110
Dan Stoza9e56aa02015-11-02 13:00:03 -08001111bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -07001112 if (mDrawingState.color.a == alpha) return false;
1113 mDrawingState.sequence++;
1114 mDrawingState.color.a = alpha;
1115 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001116 setTransactionFlags(eTransactionNeeded);
1117 return true;
1118}
chaviw13fdc492017-06-27 12:40:18 -07001119
Valerie Haudd0b7572019-01-29 14:59:27 -08001120bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -07001121 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -07001122 return false;
Valerie Hauaa194562019-02-05 16:21:38 -08001123 }
Robert Carr6a160312021-05-17 12:08:20 -07001124 mDrawingState.sequence++;
1125 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -08001126 setTransactionFlags(eTransactionNeeded);
1127
Robert Carr6a160312021-05-17 12:08:20 -07001128 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001129 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001130 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001131 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001132 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -08001133 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001134 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001135
Valerie Haudd0b7572019-01-29 14:59:27 -08001136 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001137 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001138 mFlinger->mLayersAdded = true;
1139 // set up SF to handle added color layer
1140 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -07001141 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001142 }
1143 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001144 } else if (mDrawingState.bgColorLayer && alpha == 0) {
1145 mDrawingState.bgColorLayer->reparent(nullptr);
1146 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001147 return true;
1148 }
1149
Robert Carr6a160312021-05-17 12:08:20 -07001150 mDrawingState.bgColorLayer->setColor(color);
1151 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1152 mDrawingState.bgColorLayer->setAlpha(alpha);
1153 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001154
chaviw13fdc492017-06-27 12:40:18 -07001155 return true;
1156}
1157
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001158bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001159 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001160
Robert Carr6a160312021-05-17 12:08:20 -07001161 mDrawingState.sequence++;
1162 mDrawingState.cornerRadius = cornerRadius;
1163 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001164 setTransactionFlags(eTransactionNeeded);
1165 return true;
1166}
1167
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001168bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001169 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001170 // If we start or stop drawing blur then the layer's visibility state may change so increment
1171 // the magic sequence number.
1172 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1173 mDrawingState.sequence++;
1174 }
Robert Carr6a160312021-05-17 12:08:20 -07001175 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1176 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001177 setTransactionFlags(eTransactionNeeded);
1178 return true;
1179}
Marissa Wall61c58622018-07-18 10:12:20 -07001180
Mathias Agopian13127d82013-03-05 17:47:11 -08001181bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001182 mDrawingState.sequence++;
1183 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001184 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001185 setTransactionFlags(eTransactionNeeded);
1186 return true;
1187}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001188
Lucas Dupinc3800b82020-10-02 16:24:48 -07001189bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001190 // If we start or stop drawing blur then the layer's visibility state may change so increment
1191 // the magic sequence number.
1192 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1193 mDrawingState.sequence++;
1194 }
Robert Carr6a160312021-05-17 12:08:20 -07001195 mDrawingState.blurRegions = blurRegions;
1196 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001197 setTransactionFlags(eTransactionNeeded);
1198 return true;
1199}
1200
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001201bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001202 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1203 if (mDrawingState.flags == newFlags) return false;
1204 mDrawingState.sequence++;
1205 mDrawingState.flags = newFlags;
1206 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001207 setTransactionFlags(eTransactionNeeded);
1208 return true;
1209}
Robert Carr99e27f02016-06-16 15:18:02 -07001210
chaviw25714502021-02-11 10:01:08 -08001211bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001212 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001213 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001214 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001215
Robert Carr6a160312021-05-17 12:08:20 -07001216 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001217 setTransactionFlags(eTransactionNeeded);
1218 return true;
1219}
Robert Carr8d5227b2017-03-16 15:41:03 -07001220
Evan Roskyef876c92019-01-25 17:46:06 -08001221bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001222 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1223 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001224 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001225 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001226}
1227
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001228bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001229 if (mDrawingState.layerStack == layerStack) return false;
1230 mDrawingState.sequence++;
1231 mDrawingState.layerStack = layerStack;
1232 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001233 setTransactionFlags(eTransactionNeeded);
1234 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001235}
1236
Peiyong Linc502cb72019-03-01 15:00:23 -08001237bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001238 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001239 return false;
1240 }
Robert Carr6a160312021-05-17 12:08:20 -07001241 mDrawingState.sequence++;
1242 mDrawingState.colorSpaceAgnostic = agnostic;
1243 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001244 setTransactionFlags(eTransactionNeeded);
1245 return true;
1246}
1247
Sally Qi81d95e62022-03-21 19:41:33 -07001248bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1249 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1250
1251 mDrawingState.sequence++;
1252 mDrawingState.dimmingEnabled = dimmingEnabled;
1253 mDrawingState.modified = true;
1254 setTransactionFlags(eTransactionNeeded);
1255 return true;
1256}
1257
Ana Krulecc84d09b2019-11-02 23:10:29 +01001258bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001259 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1260 mDrawingState.frameRateSelectionPriority = priority;
1261 mDrawingState.sequence++;
1262 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001263 setTransactionFlags(eTransactionNeeded);
1264 return true;
1265}
1266
1267int32_t Layer::getFrameRateSelectionPriority() const {
1268 // Check if layer has priority set.
1269 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1270 return mDrawingState.frameRateSelectionPriority;
1271 }
1272 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001273 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001274 if (parent != nullptr) {
1275 return parent->getFrameRateSelectionPriority();
1276 }
1277
1278 return Layer::PRIORITY_UNSET;
1279}
1280
Andy Labrada096227e2022-06-15 16:58:11 +00001281bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1282 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1283 mDrawingState.defaultFrameRateCompatibility = compatibility;
1284 mDrawingState.modified = true;
1285 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1286 setTransactionFlags(eTransactionNeeded);
1287 return true;
1288}
1289
1290scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1291 return mDrawingState.defaultFrameRateCompatibility;
1292}
1293
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001294bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1295 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1296};
1297
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001298ui::LayerStack Layer::getLayerStack() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001299 if (const auto parent = mDrawingParent.promote()) {
1300 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001301 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001302 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001303}
1304
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001305bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001306 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001307 return false;
1308 }
1309
Robert Carr6a160312021-05-17 12:08:20 -07001310 mDrawingState.sequence++;
1311 mDrawingState.shadowRadius = shadowRadius;
1312 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001313 setTransactionFlags(eTransactionNeeded);
1314 return true;
1315}
1316
Vishnu Nair6213bd92020-05-08 17:42:25 -07001317bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001318 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001319 return false;
1320 }
1321
Robert Carr6a160312021-05-17 12:08:20 -07001322 mDrawingState.sequence++;
1323 mDrawingState.fixedTransformHint = fixedTransformHint;
1324 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001325 setTransactionFlags(eTransactionNeeded);
1326 return true;
1327}
1328
John Reckcdb4ed72021-02-04 13:39:33 -05001329bool Layer::setStretchEffect(const StretchEffect& effect) {
1330 StretchEffect temp = effect;
1331 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001332 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001333 return false;
1334 }
Robert Carr6a160312021-05-17 12:08:20 -07001335 mDrawingState.sequence++;
1336 mDrawingState.stretchEffect = temp;
1337 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001338 setTransactionFlags(eTransactionNeeded);
1339 return true;
1340}
1341
John Reckc00c6692021-02-16 11:37:33 -05001342StretchEffect Layer::getStretchEffect() const {
1343 if (mDrawingState.stretchEffect.hasEffect()) {
1344 return mDrawingState.stretchEffect;
1345 }
1346
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001347 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001348 if (parent != nullptr) {
1349 auto effect = parent->getStretchEffect();
1350 if (effect.hasEffect()) {
1351 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1352 return effect;
1353 }
1354 }
1355 return StretchEffect{};
1356}
1357
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001358bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1359 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001360 return false;
1361 }
1362 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001363 mBorderWidth = width;
1364 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001365 return true;
1366}
1367
1368bool Layer::isBorderEnabled() {
1369 return mBorderEnabled;
1370}
1371
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001372float Layer::getBorderWidth() {
1373 return mBorderWidth;
1374}
1375
1376const half4& Layer::getBorderColor() {
1377 return mBorderColor;
1378}
1379
Ady Abrahama850c182021-08-04 13:04:37 -07001380bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1381 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1382 const auto frameRate = [&] {
1383 if (mDrawingState.frameRate.rate.isValid() ||
1384 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1385 return mDrawingState.frameRate;
1386 }
1387
1388 return parentFrameRate;
1389 }();
1390
1391 *transactionNeeded |= setFrameRateForLayerTree(frameRate);
1392
1393 // The frame rate is propagated to the children
1394 bool childrenHaveFrameRate = false;
1395 for (const sp<Layer>& child : mCurrentChildren) {
1396 childrenHaveFrameRate |=
1397 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1398 }
1399
1400 // If we don't have a valid frame rate, but the children do, we set this
1401 // layer as NoVote to allow the children to control the refresh rate
1402 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1403 childrenHaveFrameRate) {
1404 *transactionNeeded |=
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001405 setFrameRateForLayerTree(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001406 }
1407
1408 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1409 // the same reason we are allowing touch boost for those layers. See
1410 // RefreshRateConfigs::getBestRefreshRate for more details.
1411 const auto layerVotedWithDefaultCompatibility =
1412 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1413 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1414 const auto layerVotedWithExactCompatibility =
1415 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1416 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1417 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1418}
1419
Ady Abraham60e42ea2020-03-09 19:17:31 -07001420void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001421 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001422 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001423 while (auto parent = layer->getParent()) {
1424 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001425 }
Ady Abrahama850c182021-08-04 13:04:37 -07001426 return layer;
1427 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001428
Ady Abraham60e42ea2020-03-09 19:17:31 -07001429 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001430 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001431
Ady Abrahama850c182021-08-04 13:04:37 -07001432 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001433 if (transactionNeeded) {
1434 mFlinger->setTransactionFlags(eTraversalNeeded);
1435 }
1436}
1437
Ady Abraham71c437d2020-01-31 15:56:57 -08001438bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001439 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001440 return false;
1441 }
1442
Robert Carr6a160312021-05-17 12:08:20 -07001443 mDrawingState.sequence++;
1444 mDrawingState.frameRate = frameRate;
1445 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001446
1447 updateTreeHasFrameRateVote();
1448
Steven Thomas3172e202020-01-06 19:25:30 -08001449 setTransactionFlags(eTransactionNeeded);
1450 return true;
1451}
1452
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001453void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1454 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001455 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001456
1457 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1458 // there are two transactions with the same token, the first one without a buffer and the
1459 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1460 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001461 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1462 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001463 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001464 mDrawingState.bufferSurfaceFrameTX = it->second;
1465 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1466 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1467 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001468 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001469 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001470 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1471 }
1472}
1473
1474void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1475 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001476 mDrawingState.frameTimelineInfo = info;
1477 mDrawingState.postTime = postTime;
1478 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001479 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001480
Robert Carr6a160312021-05-17 12:08:20 -07001481 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001482 bufferSurfaceFrameTX != nullptr) {
1483 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1484 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1485 // being used for BufferSurfaceFrame, don't create a new one.
1486 return;
1487 }
1488 }
1489 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1490 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1491 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001492 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1493 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001494 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001495 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001496 } else {
1497 if (it->second->getPresentState() == PresentState::Presented) {
1498 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1499 // have been from previous vsync.
1500 it->second = createSurfaceFrameForTransaction(info, postTime);
1501 }
1502 }
1503}
1504
1505void Layer::addSurfaceFrameDroppedForBuffer(
1506 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001507 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001508 surfaceFrame->setPresentState(PresentState::Dropped);
1509 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1510}
1511
1512void Layer::addSurfaceFramePresentedForBuffer(
1513 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1514 nsecs_t currentLatchTime) {
1515 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1516 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1517 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1518 mLastLatchTime = currentLatchTime;
1519}
1520
1521std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1522 const FrameTimelineInfo& info, nsecs_t postTime) {
1523 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001524 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1525 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001526 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001527 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001528 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001529 // For Transactions, the post time is considered to be both queue and acquire fence time.
1530 surfaceFrame->setActualQueueTime(postTime);
1531 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001532 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1533 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001534 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001535 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001536 onSurfaceFrameCreated(surfaceFrame);
1537 return surfaceFrame;
1538}
1539
1540std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1541 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1542 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001543 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001544 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001545 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001546 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001547 // For buffers, acquire fence time will set during latch.
1548 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001549 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1550 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001551 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001552 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001553 // TODO(b/178542907): Implement onSurfaceFrameCreated for BQLayer as well.
1554 onSurfaceFrameCreated(surfaceFrame);
1555 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001556}
1557
Ady Abrahama850c182021-08-04 13:04:37 -07001558bool Layer::setFrameRateForLayerTree(FrameRate frameRate) {
1559 if (mDrawingState.frameRateForLayerTree == frameRate) {
1560 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001561 }
1562
Ady Abrahama850c182021-08-04 13:04:37 -07001563 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001564
Ady Abrahama850c182021-08-04 13:04:37 -07001565 // TODO(b/195668952): we probably don't need to dirty visible regions here
1566 // or even store frameRateForLayerTree in mDrawingState
1567 mDrawingState.sequence++;
1568 mDrawingState.modified = true;
1569 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001570
Dominik Laskowski068173d2021-08-11 17:22:59 -07001571 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
1572 mFlinger->mScheduler->recordLayerHistory(this, systemTime(), LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001573
1574 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001575}
1576
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001577Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1578 return getDrawingState().frameRateForLayerTree;
1579}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001580
Robert Carr1f0a16a2016-10-24 16:27:39 -07001581bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001582 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001583 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001584 if (parent != nullptr && parent->isHiddenByPolicy()) {
1585 return true;
1586 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001587 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1588 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1589 if (zOrderRelativeOf != nullptr) {
1590 if (zOrderRelativeOf->isHiddenByPolicy()) {
1591 return true;
1592 }
1593 }
1594 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001595 if (CC_UNLIKELY(!isTransformValid())) {
1596 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1597 return true;
1598 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001599 return s.flags & layer_state_t::eLayerHidden;
1600}
1601
David Sodman41fdfc92017-11-06 16:09:56 -08001602uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001603 // TODO: should we do something special if mSecure is set?
1604 if (mProtectedByApp) {
1605 // need a hardware-protected path to external video sink
1606 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001607 }
Riley Andrews03414a12014-07-01 14:22:59 -07001608 if (mPotentialCursor) {
1609 usage |= GraphicBuffer::USAGE_CURSOR;
1610 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001611 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001612 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001613}
1614
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001615void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1616 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1617 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001618 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001619
Vishnu Nair6213bd92020-05-08 17:42:25 -07001620 setTransformHint(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001621}
1622
Mathias Agopian13127d82013-03-05 17:47:11 -08001623// ----------------------------------------------------------------------------
1624// debugging
1625// ----------------------------------------------------------------------------
1626
Marissa Wall61c58622018-07-18 10:12:20 -07001627// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001628gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001629 using namespace std::string_literals;
1630
Huihong Luo05539a12022-02-23 10:29:40 -08001631 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001632 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001633 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001634 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001635 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001636 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001637
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001638 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001639 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001640 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001641 info.mX = ds.transform.tx();
1642 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001643 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001644 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001645 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001646 info.mFlags = ds.flags;
1647 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001648 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001649 info.mMatrix[0][0] = ds.transform[0][0];
1650 info.mMatrix[0][1] = ds.transform[0][1];
1651 info.mMatrix[1][0] = ds.transform[1][0];
1652 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001653 {
chaviwd62d3062019-09-04 14:48:02 -07001654 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001655 if (buffer != 0) {
1656 info.mActiveBufferWidth = buffer->getWidth();
1657 info.mActiveBufferHeight = buffer->getHeight();
1658 info.mActiveBufferStride = buffer->getStride();
1659 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001660 } else {
1661 info.mActiveBufferWidth = 0;
1662 info.mActiveBufferHeight = 0;
1663 info.mActiveBufferStride = 0;
1664 info.mActiveBufferFormat = 0;
1665 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001666 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001667 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001668 info.mIsOpaque = isOpaque(ds);
1669 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001670 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001671 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001672}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001673
Yiwei Zhang5434a782018-12-05 18:06:32 -08001674void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001675 result.append(kDumpTableRowLength, '-');
1676 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001677 result.append(" Layer name\n");
1678 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001679 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001680 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001681 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001682 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001683 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001684 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1685 result.append(kDumpTableRowLength, '-');
1686 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001687}
1688
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001689void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1690 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001691 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001692 return;
1693 }
1694
Yiwei Zhang5434a782018-12-05 18:06:32 -08001695 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001696 if (mName.length() > 77) {
1697 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001698 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001699 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001700 shortened.append(mName, mName.length() - 36);
1701 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001702 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001703 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001704 }
1705
Yiwei Zhang5434a782018-12-05 18:06:32 -08001706 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001707
Alec Mourib416efd2018-09-06 21:01:59 +00001708 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001709 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001710
Chia-I Wu1e043612018-03-01 09:45:09 -08001711 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001712 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001713 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001714 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001715 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001716 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001717 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001718 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1719 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001720 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001721 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001722 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001723 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001724 const auto frameRate = getFrameRateForLayerTree();
1725 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1726 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001727 ftl::enum_string(frameRate.type).c_str(),
1728 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001729 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001730 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001731 }
Dan Stozae22aec72016-08-01 13:20:59 -07001732
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001733 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1734 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1735
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001736 result.append(kDumpTableRowLength, '-');
1737 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001738}
Dan Stozae22aec72016-08-01 13:20:59 -07001739
Yiwei Zhang5434a782018-12-05 18:06:32 -08001740void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001741 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001742}
1743
Svetoslavd85084b2014-03-20 10:28:31 -07001744void Layer::clearFrameStats() {
1745 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001746}
1747
Jamie Gennis6547ff42013-07-16 20:12:42 -07001748void Layer::logFrameStats() {
1749 mFrameTracker.logAndResetStats(mName);
1750}
1751
Svetoslavd85084b2014-03-20 10:28:31 -07001752void Layer::getFrameStats(FrameStats* outStats) const {
1753 mFrameTracker.getStats(outStats);
1754}
1755
Vishnu Nair0f085c62019-08-30 08:49:12 -07001756void Layer::dumpCallingUidPid(std::string& result) const {
chaviw250bcbb2020-08-05 11:17:54 -07001757 StringAppendF(&result, "Layer %s (%s) callingPid:%d callingUid:%d ownerUid:%d\n",
1758 getName().c_str(), getType(), mCallingPid, mCallingUid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001759}
1760
Brian Anderson5ea5e592016-12-01 16:54:33 -08001761void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001762 const int32_t layerId = getSequence();
1763 mFlinger->mTimeStats->onDestroy(layerId);
1764 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001765}
1766
Chia-I Wu98f1c102017-05-30 14:54:08 -07001767size_t Layer::getChildrenCount() const {
1768 size_t count = 0;
1769 for (const sp<Layer>& child : mCurrentChildren) {
1770 count += 1 + child->getChildrenCount();
1771 }
1772 return count;
1773}
1774
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001775void Layer::setGameModeForTree(GameMode gameMode) {
1776 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001777 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1778 gameMode =
1779 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001780 }
1781 setGameMode(gameMode);
1782 for (const sp<Layer>& child : mCurrentChildren) {
1783 child->setGameModeForTree(gameMode);
1784 }
1785}
1786
Robert Carr1f0a16a2016-10-24 16:27:39 -07001787void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001788 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001789 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001790
Robert Carr1f0a16a2016-10-24 16:27:39 -07001791 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001792 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001793 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001794 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001795}
1796
1797ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001798 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001799 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001800
Robert Carr1323c952019-01-28 18:13:27 -08001801 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001802 const auto removeResult = mCurrentChildren.remove(layer);
1803
1804 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001805 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001806 layer->updateTreeHasFrameRateVote();
1807
1808 return removeResult;
1809}
1810
Robert Carr15eae092018-03-23 13:43:53 -07001811void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001812 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001813 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001814 const float parentShadowRadius =
1815 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001816 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001817 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001818 }
1819}
1820
chaviwf1961f72017-09-18 16:41:07 -07001821bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001822 sp<Layer> newParent;
1823 if (newParentHandle != nullptr) {
Vishnu Nairf9096652021-07-20 18:49:42 -07001824 newParent = fromHandle(newParentHandle).promote();
Robert Carr54cf5b12019-01-25 14:02:28 -08001825 if (newParent == nullptr) {
1826 ALOGE("Unable to promote Layer handle");
1827 return false;
1828 }
1829 if (newParent == this) {
1830 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1831 return false;
1832 }
1833 }
1834
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001835 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001836 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001837 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001838 }
1839
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001840 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001841 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001842 if (!newParent->isRemovedFromCurrentState()) {
1843 addToCurrentState();
1844 } else {
1845 onRemovedFromCurrentState();
1846 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001847 } else {
1848 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001849 }
1850
chaviw06178942017-07-27 10:25:59 -07001851 return true;
1852}
1853
Peiyong Lind3788632018-09-18 16:01:31 -07001854bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001855 static const mat4 identityMatrix = mat4();
1856
Robert Carr6a160312021-05-17 12:08:20 -07001857 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001858 return false;
1859 }
Robert Carr6a160312021-05-17 12:08:20 -07001860 ++mDrawingState.sequence;
1861 mDrawingState.colorTransform = matrix;
1862 mDrawingState.hasColorTransform = matrix != identityMatrix;
1863 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001864 setTransactionFlags(eTransactionNeeded);
1865 return true;
1866}
1867
chaviwf66724d2018-11-28 16:35:21 -08001868mat4 Layer::getColorTransform() const {
1869 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001870 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001871 colorTransform = parent->getColorTransform() * colorTransform;
1872 }
1873 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001874}
1875
1876bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001877 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001878 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001879 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1880 }
1881 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001882}
1883
Chia-I Wu11481472018-05-04 10:43:19 -07001884bool Layer::isLegacyDataSpace() const {
1885 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001886 return !(getDataSpace() &
1887 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1888 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001889}
1890
Robert Carr1f0a16a2016-10-24 16:27:39 -07001891void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001892 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001893}
1894
Robert Carr6a160312021-05-17 12:08:20 -07001895int32_t Layer::getZ(LayerVector::StateSet) const {
1896 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001897}
1898
Robert Carr1c5481e2019-07-01 14:42:27 -07001899bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001900 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001901 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001902 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001903}
1904
David Sodman41fdfc92017-11-06 16:09:56 -08001905__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001906 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001907 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1908 "makeTraversalList received invalid stateSet");
1909 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1910 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001911 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001912
Robert Carr29abff82017-12-04 13:51:20 -08001913 if (state.zOrderRelatives.size() == 0) {
1914 *outSkipRelativeZUsers = true;
1915 return children;
1916 }
1917
chaviwfd462612018-05-31 16:11:27 -07001918 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001919 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001920 sp<Layer> strongRelative = weakRelative.promote();
1921 if (strongRelative != nullptr) {
1922 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001923 }
1924 }
1925
Dan Stoza412903f2017-04-27 13:42:17 -07001926 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001927 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001928 continue;
1929 }
Robert Carrdb66e622017-04-10 16:55:57 -07001930 traverse.add(child);
1931 }
1932
1933 return traverse;
1934}
1935
Robert Carr1f0a16a2016-10-24 16:27:39 -07001936/**
Robert Carrdb66e622017-04-10 16:55:57 -07001937 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001938 */
Dan Stoza412903f2017-04-27 13:42:17 -07001939void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001940 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1941 // produce a new list for traversing, including our relatives, and not including our children
1942 // who are relatives of another surface. In the case that there are no relative Z,
1943 // makeTraversalList returns our children directly to avoid significant overhead.
1944 // However in this case we need to take the responsibility for filtering children which
1945 // are relatives of another surface here.
1946 bool skipRelativeZUsers = false;
1947 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001948
Robert Carr1f0a16a2016-10-24 16:27:39 -07001949 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001950 for (; i < list.size(); i++) {
1951 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001952 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1953 continue;
1954 }
1955
chaviw301b1d82019-11-06 13:15:09 -08001956 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001957 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001958 }
Dan Stoza412903f2017-04-27 13:42:17 -07001959 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001960 }
Robert Carr29abff82017-12-04 13:51:20 -08001961
Dan Stoza412903f2017-04-27 13:42:17 -07001962 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001963 for (; i < list.size(); i++) {
1964 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001965
Robert Carr29abff82017-12-04 13:51:20 -08001966 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1967 continue;
1968 }
Dan Stoza412903f2017-04-27 13:42:17 -07001969 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001970 }
1971}
1972
1973/**
Robert Carrdb66e622017-04-10 16:55:57 -07001974 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001975 */
Dan Stoza412903f2017-04-27 13:42:17 -07001976void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1977 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001978 // See traverseInZOrder for documentation.
1979 bool skipRelativeZUsers = false;
1980 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001981
Robert Carr1f0a16a2016-10-24 16:27:39 -07001982 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001983 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001984 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001985
1986 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1987 continue;
1988 }
1989
chaviw301b1d82019-11-06 13:15:09 -08001990 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001991 break;
1992 }
Dan Stoza412903f2017-04-27 13:42:17 -07001993 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001994 }
Dan Stoza412903f2017-04-27 13:42:17 -07001995 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001996 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001997 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001998
1999 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
2000 continue;
2001 }
2002
Dan Stoza412903f2017-04-27 13:42:17 -07002003 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002004 }
2005}
2006
Edgar Arriaga844fa672020-01-16 14:21:42 -08002007void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
2008 visitor(this);
2009 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07002010 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002011 for (const sp<Layer>& child : children) {
2012 child->traverse(state, visitor);
2013 }
2014}
2015
chaviw4b129c22018-04-09 16:19:43 -07002016LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
2017 const std::vector<Layer*>& layersInTree) {
2018 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2019 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07002020 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2021 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002022 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002023
chaviwfd462612018-05-31 16:11:27 -07002024 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07002025 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2026 sp<Layer> strongRelative = weakRelative.promote();
2027 // Only add relative layers that are also descendents of the top most parent of the tree.
2028 // If a relative layer is not a descendent, then it should be ignored.
2029 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
2030 traverse.add(strongRelative);
2031 }
2032 }
2033
2034 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07002035 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002036 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
2037 // descendent of the top most parent of the tree. If it's not a descendent, then just add
2038 // the child here since it won't be added later as a relative.
2039 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
2040 childState.zOrderRelativeOf.promote().get())) {
2041 continue;
2042 }
2043 traverse.add(child);
2044 }
2045
2046 return traverse;
2047}
2048
2049void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
2050 LayerVector::StateSet stateSet,
2051 const LayerVector::Visitor& visitor) {
2052 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07002053
2054 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07002055 for (; i < list.size(); i++) {
2056 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08002057 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07002058 break;
2059 }
chaviw4b129c22018-04-09 16:19:43 -07002060 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002061 }
chaviw4b129c22018-04-09 16:19:43 -07002062
chaviwa76b2712017-09-20 12:02:26 -07002063 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07002064 for (; i < list.size(); i++) {
2065 const auto& relative = list[i];
2066 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002067 }
2068}
2069
chaviw4b129c22018-04-09 16:19:43 -07002070std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2071 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2072 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2073
2074 std::vector<Layer*> layersInTree = {this};
2075 for (size_t i = 0; i < children.size(); i++) {
2076 const auto& child = children[i];
2077 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2078 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2079 }
2080
2081 return layersInTree;
2082}
2083
2084void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2085 const LayerVector::Visitor& visitor) {
2086 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2087 std::sort(layersInTree.begin(), layersInTree.end());
2088 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2089}
2090
Peiyong Linefefaac2018-08-17 12:27:51 -07002091ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08002092 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002093}
2094
Garfield Tan2c1782c2022-02-16 15:25:05 -08002095bool Layer::isTransformValid() const {
2096 float transformDet = getTransform().det();
2097 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2098}
2099
chaviw13fdc492017-06-27 12:40:18 -07002100half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002101 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002102
chaviw13fdc492017-06-27 12:40:18 -07002103 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2104 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002105}
Robert Carr6452f122017-03-21 10:41:29 -07002106
Vishnu Nair6213bd92020-05-08 17:42:25 -07002107ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002108 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002109 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2110 return fixedTransformHint;
2111 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002112 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002113 if (!p) return fixedTransformHint;
2114 return p->getFixedTransformHint();
2115}
2116
chaviw13fdc492017-06-27 12:40:18 -07002117half4 Layer::getColor() const {
2118 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002119 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002120}
Robert Carr6452f122017-03-21 10:41:29 -07002121
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002122int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002123 if (getDrawingState().backgroundBlurRadius == 0) {
2124 return 0;
2125 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002126
Vishnu Nair29810f72022-07-01 16:38:41 +00002127 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002128 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2129 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002130}
2131
Galia Peychevae0acf382021-04-12 21:22:34 +02002132const std::vector<BlurRegion> Layer::getBlurRegions() const {
2133 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002134 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002135 for (auto& region : regionsCopy) {
2136 region.alpha = region.alpha * layerAlpha;
2137 }
2138 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002139}
2140
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002141Layer::RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002142 // Get parent settings
2143 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002144 const auto& parent = mDrawingParent.promote();
2145 if (parent != nullptr) {
2146 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002147 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002148 ui::Transform t = getActiveTransform(getDrawingState());
2149 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002150 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002151 parentSettings.radius.x *= t.getScaleX();
2152 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002153 }
2154 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002155
2156 // Get layer settings
2157 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002158 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002159 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002160 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002161
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002162 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002163 // If the parent and the layer have rounded corner settings, use the parent settings if the
2164 // parent crop is entirely inside the layer crop.
2165 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2166 if (parentSettings.cropRect.left > layerCropRect.left &&
2167 parentSettings.cropRect.top > layerCropRect.top &&
2168 parentSettings.cropRect.right < layerCropRect.right &&
2169 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2170 return parentSettings;
2171 } else {
2172 return layerSettings;
2173 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002174 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002175 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002176 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002177 return parentSettings;
2178 }
2179 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002180}
2181
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04002182void Layer::prepareShadowClientComposition(LayerFE::LayerSettings& caster,
Patrick Williams16d8b2c2022-08-08 17:29:05 +00002183 const Rect& layerStackRect) const {
Vishnu Nair08f6eae2019-11-26 14:01:39 -08002184 renderengine::ShadowSettings state = mFlinger->mDrawingState.globalShadowSettings;
2185
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04002186 // Note: this preserves existing behavior of shadowing the entire layer and not cropping it if
Patrick Williams46b61b92022-09-01 17:25:49 +00002187 // transparent regions are present. This may not be necessary since shadows are typically cast
2188 // by layers without transparent regions.
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04002189 state.boundaries = mBounds;
2190
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.
Marin Shalamanov6ad317c2020-07-29 23:34:07 +02002193 state.lightPos.x = (layerStackRect.width() / 2.f) - mScreenBounds.left;
Vishnu Nair08f6eae2019-11-26 14:01:39 -08002194 state.lightPos.y -= mScreenBounds.top;
2195
2196 state.length = mEffectiveShadowRadius;
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04002197
2198 if (state.length > 0.f) {
2199 const float casterAlpha = caster.alpha;
2200 const bool casterIsOpaque =
2201 ((caster.source.buffer.buffer != nullptr) && caster.source.buffer.isOpaque);
2202
2203 // If the casting layer is translucent, we need to fill in the shadow underneath the layer.
2204 // Otherwise the generated shadow will only be shown around the casting layer.
2205 state.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
2206 state.ambientColor *= casterAlpha;
2207 state.spotColor *= casterAlpha;
2208
2209 if (state.ambientColor.a > 0.f && state.spotColor.a > 0.f) {
2210 caster.shadow = state;
2211 }
2212 }
Vishnu Nair08f6eae2019-11-26 14:01:39 -08002213}
2214
Robert Carr88b85e12022-03-21 15:47:35 -07002215bool Layer::findInHierarchy(const sp<Layer>& l) {
2216 if (l == this) {
2217 return true;
2218 }
2219 for (auto& child : mDrawingChildren) {
2220 if (child->findInHierarchy(l)) {
2221 return true;
2222 }
2223 }
2224 return false;
2225}
2226
Robert Carr1f0a16a2016-10-24 16:27:39 -07002227void Layer::commitChildList() {
2228 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2229 const auto& child = mCurrentChildren[i];
2230 child->commitChildList();
2231 }
2232 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002233 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002234 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2235 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2236 if (zOrderRelativeOf == nullptr) return;
2237 if (findInHierarchy(zOrderRelativeOf)) {
2238 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2239 zOrderRelativeOf->mName.c_str());
2240 ALOGE("Severing rel Z loop, potentially dangerous");
2241 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002242 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002243 }
2244 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002245}
2246
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002247
chaviw3277faf2021-05-19 16:45:23 -05002248void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002249 mDrawingState.inputInfo = info;
Vishnu Nairf9096652021-07-20 18:49:42 -07002250 mDrawingState.touchableRegionCrop = fromHandle(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002251 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002252 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002253 setTransactionFlags(eTransactionNeeded);
2254}
2255
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002256LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08002257 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002258 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002259 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2260
Vishnu Nair00b90132021-11-05 14:03:40 -07002261 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002262 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
2263
Vishnu Nair60db8c02020-04-02 11:55:16 -07002264 // Only populate for the primary display.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08002265 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -05002266 const auto compositionType = getCompositionType(*display);
Vishnu Nair60db8c02020-04-02 11:55:16 -07002267 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002268 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
2269 [&]() { return layerProto->mutable_visible_region(); });
Vishnu Nair60db8c02020-04-02 11:55:16 -07002270 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08002271 }
2272
chaviw08f3cb22020-01-13 13:17:21 -08002273 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002274 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002275 }
chaviw6d89e2d2020-01-14 14:42:01 -08002276
2277 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002278}
2279
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002280void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002281 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002282 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002283 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002284 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002285 [&]() { return layerInfo->mutable_active_buffer(); });
2286 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2287 layerInfo->mutable_buffer_transform());
2288 }
2289 layerInfo->set_invalidate(contentDirty);
2290 layerInfo->set_is_protected(isProtected());
2291 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2292 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002293 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002294 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002295 layerInfo->set_corner_radius(
2296 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002297 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2298 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2299 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2300 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2301 [&]() { return layerInfo->mutable_position(); });
2302 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002303 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2304 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002305
Vishnu Nair00b90132021-11-05 14:03:40 -07002306 if (hasColorTransform()) {
2307 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002308 }
2309
Vishnu Nair60db8c02020-04-02 11:55:16 -07002310 LayerProtoHelper::writeToProto(mSourceBounds,
2311 [&]() { return layerInfo->mutable_source_bounds(); });
2312 LayerProtoHelper::writeToProto(mScreenBounds,
2313 [&]() { return layerInfo->mutable_screen_bounds(); });
2314 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2315 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2316 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002317}
2318
2319void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002320 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002321 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2322 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002323 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002324
chaviw766c9c52021-02-10 17:36:47 -08002325 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002326
Vishnu Nair00b90132021-11-05 14:03:40 -07002327 layerInfo->set_id(sequence);
2328 layerInfo->set_name(getName().c_str());
2329 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002330
Vishnu Nair00b90132021-11-05 14:03:40 -07002331 for (const auto& child : children) {
2332 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002333 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002334
Vishnu Nair00b90132021-11-05 14:03:40 -07002335 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2336 sp<Layer> strongRelative = weakRelative.promote();
2337 if (strongRelative != nullptr) {
2338 layerInfo->add_relatives(strongRelative->sequence);
2339 }
2340 }
2341
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002342 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002343 [&]() { return layerInfo->mutable_transparent_region(); });
2344
2345 layerInfo->set_layer_stack(getLayerStack().id);
2346 layerInfo->set_z(state.z);
2347
2348 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2349 return layerInfo->mutable_requested_position();
2350 });
2351
Vishnu Nair00b90132021-11-05 14:03:40 -07002352 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2353
2354 layerInfo->set_is_opaque(isOpaque(state));
2355
2356 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2357 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2358 LayerProtoHelper::writeToProto(state.color,
2359 [&]() { return layerInfo->mutable_requested_color(); });
2360 layerInfo->set_flags(state.flags);
2361
2362 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2363 layerInfo->mutable_requested_transform());
2364
2365 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2366 if (parent != nullptr) {
2367 layerInfo->set_parent(parent->sequence);
2368 } else {
2369 layerInfo->set_parent(-1);
2370 }
2371
2372 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2373 if (zOrderRelativeOf != nullptr) {
2374 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2375 } else {
2376 layerInfo->set_z_order_relative_of(-1);
2377 }
2378
2379 layerInfo->set_is_relative_of(state.isRelativeOf);
2380
2381 layerInfo->set_owner_uid(mOwnerUid);
2382
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002383 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002384 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002385 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002386 info = fillInputInfo(
2387 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002388 } else {
2389 info = state.inputInfo;
2390 }
2391
2392 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002393 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002394 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002395
Vishnu Nair00b90132021-11-05 14:03:40 -07002396 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002397 auto protoMap = layerInfo->mutable_metadata();
2398 for (const auto& entry : state.metadata.mMap) {
2399 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2400 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002401 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002402
2403 LayerProtoHelper::writeToProto(state.destinationFrame,
2404 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002405}
2406
Robert Carr2e102c92018-10-23 12:11:15 -07002407bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002408 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002409}
2410
Prabir Pradhan33da9462022-06-14 14:55:57 +00002411// Applies the given transform to the region, while protecting against overflows caused by any
2412// offsets. If applying the offset in the transform to any of the Rects in the region would result
2413// in an overflow, they are not added to the output Region.
2414static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2415 const std::string& debugWindowName) {
2416 // Round the translation using the same rounding strategy used by ui::Transform.
2417 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2418 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2419
2420 ui::Transform transformWithoutOffset = t;
2421 transformWithoutOffset.set(0.f, 0.f);
2422
2423 const Region transformed = transformWithoutOffset.transform(r);
2424
2425 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2426 Region ret;
2427 for (const auto& rect : transformed) {
2428 Rect newRect;
2429 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2430 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2431 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2432 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2433 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2434 debugWindowName.c_str());
2435 continue;
2436 }
2437 ret.orSelf(newRect);
2438 }
2439 return ret;
2440}
2441
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002442void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
2443 Rect tmpBounds = getInputBounds();
2444 if (!tmpBounds.isValid()) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002445 info.touchableRegion.clear();
2446 // A layer could have invalid input bounds and still expect to receive touch input if it has
2447 // replaceTouchableRegionWithCrop. For that case, the input transform needs to be calculated
2448 // correctly to determine the coordinate space for input events. Use an empty rect so that
2449 // the layer will receive input in its own layer space.
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002450 tmpBounds = Rect::EMPTY_RECT;
chaviw7e72caf2020-12-02 16:50:43 -08002451 }
2452
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002453 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2454 // frame and transform used for the layer, which determines the bounds and the coordinate space
2455 // within which the layer will receive input.
2456 //
2457 // The coordinate space within which each of the bounds are specified is explicitly documented
2458 // in the variable name. For example "inputBoundsInLayer" is specified in layer space. A
2459 // Transform converts one coordinate space to another, which is apparent in its naming. For
2460 // example, "layerToDisplay" transforms layer space to display space.
2461 //
2462 // Coordinate space definitions:
2463 // - display: The display device's coordinate space. Correlates to pixels on the display.
2464 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2465 // - layer: The coordinate space of this layer.
2466 // - input: The coordinate space in which this layer will receive input events. This could be
2467 // different than layer space if a surfaceInset is used, which changes the origin
2468 // of the input space.
2469 const FloatRect inputBoundsInLayer = tmpBounds.toFloatRect();
chaviw7e72caf2020-12-02 16:50:43 -08002470
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002471 // Clamp surface inset to the input bounds.
2472 const auto surfaceInset = static_cast<float>(info.surfaceInset);
2473 const float xSurfaceInset =
2474 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getWidth() / 2.f));
2475 const float ySurfaceInset =
2476 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getHeight() / 2.f));
chaviw1ff3d1e2020-07-01 15:53:47 -07002477
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002478 // Apply the insets to the input bounds.
2479 const FloatRect insetBoundsInLayer(inputBoundsInLayer.left + xSurfaceInset,
2480 inputBoundsInLayer.top + ySurfaceInset,
2481 inputBoundsInLayer.right - xSurfaceInset,
2482 inputBoundsInLayer.bottom - ySurfaceInset);
Ady Abraham282f1d72019-07-24 18:05:56 -07002483
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002484 // Crop the input bounds to ensure it is within the parent's bounds.
2485 const FloatRect croppedInsetBoundsInLayer = mBounds.intersect(insetBoundsInLayer);
Ady Abraham282f1d72019-07-24 18:05:56 -07002486
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002487 const ui::Transform layerToScreen = getInputTransform();
2488 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
Vishnu Nair8033a492018-12-05 07:27:23 -08002489
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002490 const Rect roundedFrameInDisplay{layerToDisplay.transform(croppedInsetBoundsInLayer)};
2491 info.frameLeft = roundedFrameInDisplay.left;
2492 info.frameTop = roundedFrameInDisplay.top;
2493 info.frameRight = roundedFrameInDisplay.right;
2494 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002495
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002496 ui::Transform inputToLayer;
2497 inputToLayer.set(insetBoundsInLayer.left, insetBoundsInLayer.top);
2498 const ui::Transform inputToDisplay = layerToDisplay * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002499
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002500 // InputDispatcher expects a display-to-input transform.
2501 info.transform = inputToDisplay.inverse();
2502
2503 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002504 info.touchableRegion =
2505 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002506}
2507
chaviw3277faf2021-05-19 16:45:23 -05002508void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002509 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002510 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002511 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002512 }
2513 if (p != nullptr) {
2514 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2515 }
2516}
2517
Vishnu Naira066d902021-09-13 18:40:17 -07002518gui::DropInputMode Layer::getDropInputMode() const {
2519 gui::DropInputMode mode = mDrawingState.dropInputMode;
2520 if (mode == gui::DropInputMode::ALL) {
2521 return mode;
2522 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002523 sp<Layer> parent = mDrawingParent.promote();
2524 if (parent) {
2525 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002526 if (parentMode != gui::DropInputMode::NONE) {
2527 return parentMode;
2528 }
2529 }
2530 return mode;
2531}
2532
2533void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002534 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002535 return;
2536 }
2537
2538 // Check if we need to drop input unconditionally
2539 gui::DropInputMode dropInputMode = getDropInputMode();
2540 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002541 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002542 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2543 return;
2544 }
2545
2546 // Check if we need to check if the window is obscured by parent
2547 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2548 return;
2549 }
2550
2551 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002552 sp<Layer> parent = mDrawingParent.promote();
2553 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002554 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002555 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2556 static_cast<float>(getAlpha()));
2557 }
2558
2559 // Check if the parent has cropped the buffer
2560 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2561 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002562 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002563 return;
2564 }
2565
2566 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2567 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2568 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2569 // match then the layer has not been cropped by its parents.
2570 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2571 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2572
2573 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002574 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002575 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2576 getDebugName());
2577 } else {
2578 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2579 // input if the window is obscured. This check should be done in surfaceflinger but the
2580 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2581 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002582 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002583 }
2584}
2585
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002586WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002587 if (!hasInputInfo()) {
2588 mDrawingState.inputInfo.name = getName();
2589 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2590 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002591 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002592 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002593 }
2594
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002595 const ui::Transform& displayTransform =
2596 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2597
chaviw3277faf2021-05-19 16:45:23 -05002598 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002599 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002600 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002601
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002602 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002603
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002604 if (displayArgs.transform == nullptr) {
2605 // Do not let the window receive touches if it is not associated with a valid display
2606 // transform. We still allow the window to receive keys and prevent ANRs.
2607 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2608 }
2609
Robert Carr5dc426e2020-06-10 14:29:14 -07002610 // For compatibility reasons we let layers which can receive input
2611 // receive input before they have actually submitted a buffer. Because
2612 // of this we use canReceiveInput instead of isVisible to check the
2613 // policy-visibility, ignoring the buffer state. However for layers with
2614 // hasInputInfo()==false we can use the real visibility state.
2615 // We are just using these layers for occlusion detection in
2616 // InputDispatcher, and obviously if they aren't visible they can't occlude
2617 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002618 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2619 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2620
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002621 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002622 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002623 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002624
Vishnu Nair16a938f2021-09-24 07:14:54 -07002625 // If the window will be blacked out on a display because the display does not have the secure
2626 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002627 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002628 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002629 }
2630
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002631 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2632 if (info.replaceTouchableRegionWithCrop) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002633 const Rect bounds(cropLayer ? cropLayer->mScreenBounds : mScreenBounds);
2634 info.touchableRegion = Region(displayTransform.transform(bounds));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002635 } else if (cropLayer != nullptr) {
[1;3C2b9fc252021-02-04 16:16:50 -08002636 info.touchableRegion = info.touchableRegion.intersect(
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002637 displayTransform.transform(Rect{cropLayer->mScreenBounds}));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002638 }
2639
Winson Chunga30f7c92021-06-29 15:42:56 -07002640 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2641 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002642 if (isTrustedOverlay()) {
2643 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2644 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002645
chaviwaf87b3e2019-10-01 16:59:28 -07002646 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2647 // touches from going outside the cloned area.
2648 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002649 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002650 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2651 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002652 info.touchableRegion = info.touchableRegion.intersect(rect);
2653 }
2654 }
2655
Robert Carr720e5062018-07-30 17:45:14 -07002656 return info;
2657}
2658
chaviwaf87b3e2019-10-01 16:59:28 -07002659sp<Layer> Layer::getClonedRoot() {
2660 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002661 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002662 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002663 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002664 return nullptr;
2665 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002666 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002667}
2668
Robert Carredd13602020-04-13 17:24:34 -07002669bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002670 return mDrawingState.inputInfo.token != nullptr ||
2671 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002672}
2673
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002674compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002675 const DisplayDevice* display) const {
2676 if (!display) return nullptr;
Lloyd Piquede196652020-01-22 17:29:58 -08002677 return display->getCompositionDisplay()->getOutputLayerForLayer(getCompositionEngineLayerFE());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002678}
2679
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002680Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2681 const auto outputLayer = findOutputLayerForDisplay(display);
2682 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002683}
2684
chaviwb4c6e582019-08-16 14:35:07 -07002685void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002686 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002687 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002688 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2689 mPotentialCursor = clonedFrom->mPotentialCursor;
2690 mProtectedByApp = clonedFrom->mProtectedByApp;
2691 updateCloneBufferInfo();
2692}
2693
2694void Layer::updateCloneBufferInfo() {
2695 if (!isClone() || !isClonedFromAlive()) {
2696 return;
2697 }
2698
2699 sp<Layer> clonedFrom = getClonedFrom();
2700 mBufferInfo = clonedFrom->mBufferInfo;
2701 mSidebandStream = clonedFrom->mSidebandStream;
2702 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2703 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2704 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2705
2706 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2707 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2708 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2709 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2710 // the cloned drawingState again.
2711 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2712 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2713 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2714 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2715
2716 cloneDrawingState(clonedFrom.get());
2717
2718 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2719 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2720 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2721 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002722}
chaviw74b03172019-08-19 11:09:03 -07002723
2724void Layer::updateMirrorInfo() {
2725 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2726 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2727 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2728 // that case, we want to delete the reference to the clone since we want it to get
2729 // destroyed. The root, this layer, will still be around since the client can continue
2730 // to hold a reference, but no cloned layers will be displayed.
2731 mClonedChild = nullptr;
2732 return;
2733 }
2734
2735 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2736 // If the real layer exists and is in current state, add the clone as a child of the root.
2737 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2738 // copied to drawingState for the root layer. So the clonedChild is always removed from
2739 // drawingState and then needs to be added back each traversal.
2740 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2741 addChildToDrawing(mClonedChild);
2742 }
2743
2744 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002745 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002746 mClonedChild->updateClonedRelatives(clonedLayersMap);
2747}
2748
2749void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2750 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2751 // to the clone. If the real layer is no longer alive, continue traversing the children
2752 // since we may be able to pull out other children that are still alive.
2753 if (isClonedFromAlive()) {
2754 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002755 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002756 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002757 }
2758
2759 // The clone layer may have children in drawingState since they may have been created and
2760 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2761 // that already exist, since we can just re-use them.
2762 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2763 // not updated in the regular traversal. They are skipped since the root will lose the
2764 // reference to them when it copies its currentChildren to drawing.
2765 for (sp<Layer>& child : mDrawingChildren) {
2766 child->updateClonedDrawingState(clonedLayersMap);
2767 }
2768}
2769
2770void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2771 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2772 mDrawingChildren.clear();
2773
2774 if (!isClonedFromAlive()) {
2775 return;
2776 }
2777
2778 sp<Layer> clonedFrom = getClonedFrom();
2779 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2780 if (child == mirrorRoot) {
2781 // This is to avoid cyclical mirroring.
2782 continue;
2783 }
2784 sp<Layer> clonedChild = clonedLayersMap[child];
2785 if (clonedChild == nullptr) {
2786 clonedChild = child->createClone();
2787 clonedLayersMap[child] = clonedChild;
2788 }
2789 addChildToDrawing(clonedChild);
2790 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2791 }
2792}
2793
chaviwaf87b3e2019-10-01 16:59:28 -07002794void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2795 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2796 if (cropLayer != nullptr) {
2797 if (clonedLayersMap.count(cropLayer) == 0) {
2798 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2799 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002800 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002801 } else {
2802 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2803 mDrawingState.touchableRegionCrop = clonedCropLayer;
2804 }
2805 }
2806 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2807 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002808 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002809}
2810
2811void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002812 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002813 mDrawingState.zOrderRelatives.clear();
2814
2815 if (!isClonedFromAlive()) {
2816 return;
2817 }
2818
chaviwaf87b3e2019-10-01 16:59:28 -07002819 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002820 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002821 const sp<Layer>& relative = relativeWeak.promote();
2822 if (clonedLayersMap.count(relative) > 0) {
2823 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002824 mDrawingState.zOrderRelatives.add(clonedRelative);
2825 }
2826 }
2827
2828 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2829 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2830 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2831 // still traverse the children, but the layer with the missing relativeOf will not be shown
2832 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002833 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2834 if (clonedLayersMap.count(relativeOf) > 0) {
2835 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002836 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2837 }
2838
chaviwaf87b3e2019-10-01 16:59:28 -07002839 updateClonedInputInfo(clonedLayersMap);
2840
chaviw74b03172019-08-19 11:09:03 -07002841 for (sp<Layer>& child : mDrawingChildren) {
2842 child->updateClonedRelatives(clonedLayersMap);
2843 }
2844}
2845
2846void Layer::addChildToDrawing(const sp<Layer>& layer) {
2847 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002848 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002849}
2850
Steven Thomas62a4cf82020-01-31 12:04:03 -08002851Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2852 switch (compatibility) {
2853 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2854 return FrameRateCompatibility::Default;
2855 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2856 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002857 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2858 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002859 case ANATIVEWINDOW_FRAME_RATE_MIN:
2860 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002861 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2862 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002863 default:
2864 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2865 return FrameRateCompatibility::Default;
2866 }
2867}
2868
Marin Shalamanovc5986772021-03-16 16:09:49 +01002869scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2870 switch (strategy) {
2871 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2872 return Seamlessness::OnlySeamless;
2873 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2874 return Seamlessness::SeamedAndSeamless;
2875 default:
2876 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2877 return Seamlessness::Default;
2878 }
2879}
2880
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002881bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002882 const State& s(mDrawingState);
2883 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2884 return true;
2885 }
2886
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002887 sp<Layer> parent = mDrawingParent.promote();
2888 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002889}
2890
Robert Carr6a0382d2021-07-01 15:57:17 -07002891void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2892 mClonedChild = clonedChild;
2893 mHadClonedChild = true;
2894 mFlinger->mNumClones++;
2895}
2896
Vishnu Nairf9096652021-07-20 18:49:42 -07002897const String16 Layer::Handle::kDescriptor = String16("android.Layer.Handle");
2898
2899wp<Layer> Layer::fromHandle(const sp<IBinder>& handleBinder) {
2900 if (handleBinder == nullptr) {
2901 return nullptr;
2902 }
2903
2904 BBinder* b = handleBinder->localBinder();
2905 if (b == nullptr || b->getInterfaceDescriptor() != Handle::kDescriptor) {
2906 return nullptr;
2907 }
2908
2909 // We can safely cast this binder since its local and we verified its interface descriptor.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002910 sp<Handle> handle = sp<Handle>::cast(handleBinder);
Vishnu Nairf9096652021-07-20 18:49:42 -07002911 return handle->owner;
2912}
2913
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002914bool Layer::setDropInputMode(gui::DropInputMode mode) {
2915 if (mDrawingState.dropInputMode == mode) {
2916 return false;
2917 }
2918 mDrawingState.dropInputMode = mode;
2919 return true;
2920}
2921
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002922void Layer::cloneDrawingState(const Layer* from) {
2923 mDrawingState = from->mDrawingState;
2924 // Skip callback info since they are not applicable for cloned layers.
2925 mDrawingState.releaseBufferListener = nullptr;
2926 mDrawingState.callbackHandles = {};
2927}
2928
Patrick Williamsbb25f802022-08-30 23:02:34 +00002929void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2930 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
2931 const sp<Fence>& releaseFence,
2932 uint32_t currentMaxAcquiredBufferCount) {
2933 if (!listener) {
2934 return;
2935 }
2936 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
2937 listener->onReleaseBuffer({buffer->getId(), framenumber},
2938 releaseFence ? releaseFence : Fence::NO_FENCE,
2939 currentMaxAcquiredBufferCount);
2940}
2941
2942void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2943 // If we are displayed on multiple displays in a single composition cycle then we would
2944 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2945 // For example we can only use it if all the displays are client comp, and we need
2946 // to merge all the client comp fences. We could do this, but for now we just
2947 // disable the optimization when a layer is composed on multiple displays.
2948 if (mClearClientCompositionFenceOnLayerDisplayed) {
2949 mLastClientCompositionFence = nullptr;
2950 } else {
2951 mClearClientCompositionFenceOnLayerDisplayed = true;
2952 }
2953
2954 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2955 // buffer that was presented on this layer. The first transaction that came in this frame that
2956 // replaced the previous buffer on this layer needs this release fence, because the fence will
2957 // let the client know when that previous buffer is removed from the screen.
2958 //
2959 // Every other transaction on this layer does not need a release fence because no other
2960 // Transactions that were set on this layer this frame are going to have their preceding buffer
2961 // removed from the display this frame.
2962 //
2963 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2964 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2965 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2966 // the previous buffer will be released this frame. The third transaction also contains a
2967 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2968 // transaction will now no longer be presented so it is released immediately and the third
2969 // transaction doesn't need a previous release fence.
2970 sp<CallbackHandle> ch;
2971 for (auto& handle : mDrawingState.callbackHandles) {
2972 if (handle->releasePreviousBuffer &&
2973 mDrawingState.releaseBufferEndpoint == handle->listener) {
2974 ch = handle;
2975 break;
2976 }
2977 }
2978
2979 // Prevent tracing the same release multiple times.
2980 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2981 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2982 }
2983
2984 if (ch != nullptr) {
2985 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2986 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2987 ch->name = mName;
2988 }
2989}
2990
2991void Layer::onSurfaceFrameCreated(
2992 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2993 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2994 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2995 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2996 // leak.
2997 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2998 mName.c_str());
2999 std::string miniDump = mPendingJankClassifications.front()->miniDump();
3000 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
3001 mPendingJankClassifications.pop_front();
3002 }
3003 mPendingJankClassifications.emplace_back(surfaceFrame);
3004}
3005
3006void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
3007 for (const auto& handle : mDrawingState.callbackHandles) {
3008 handle->transformHint = mTransformHint;
3009 handle->dequeueReadyTime = dequeueReadyTime;
3010 handle->currentMaxAcquiredBufferCount =
3011 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
3012 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
3013 handle->previousReleaseCallbackId.framenumber);
3014 }
3015
3016 for (auto& handle : mDrawingState.callbackHandles) {
3017 if (handle->releasePreviousBuffer &&
3018 mDrawingState.releaseBufferEndpoint == handle->listener) {
3019 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
3020 break;
3021 }
3022 }
3023
3024 std::vector<JankData> jankData;
3025 jankData.reserve(mPendingJankClassifications.size());
3026 while (!mPendingJankClassifications.empty() &&
3027 mPendingJankClassifications.front()->getJankType()) {
3028 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
3029 mPendingJankClassifications.front();
3030 mPendingJankClassifications.pop_front();
3031 jankData.emplace_back(
3032 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
3033 }
3034
3035 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
3036 jankData);
3037
3038 sp<Fence> releaseFence = Fence::NO_FENCE;
3039 for (auto& handle : mDrawingState.callbackHandles) {
3040 if (handle->releasePreviousBuffer &&
3041 mDrawingState.releaseBufferEndpoint == handle->listener) {
3042 releaseFence =
3043 handle->previousReleaseFence ? handle->previousReleaseFence : Fence::NO_FENCE;
3044 break;
3045 }
3046 }
3047
3048 mDrawingState.callbackHandles = {};
3049}
3050
3051bool Layer::willPresentCurrentTransaction() const {
3052 // Returns true if the most recent Transaction applied to CurrentState will be presented.
3053 return (getSidebandStreamChanged() || getAutoRefresh() ||
3054 (mDrawingState.modified &&
3055 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
3056}
3057
3058bool Layer::setTransform(uint32_t transform) {
3059 if (mDrawingState.bufferTransform == transform) return false;
3060 mDrawingState.bufferTransform = transform;
3061 mDrawingState.modified = true;
3062 setTransactionFlags(eTransactionNeeded);
3063 return true;
3064}
3065
3066bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
3067 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
3068 mDrawingState.sequence++;
3069 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
3070 mDrawingState.modified = true;
3071 setTransactionFlags(eTransactionNeeded);
3072 return true;
3073}
3074
3075bool Layer::setBufferCrop(const Rect& bufferCrop) {
3076 if (mDrawingState.bufferCrop == bufferCrop) return false;
3077
3078 mDrawingState.sequence++;
3079 mDrawingState.bufferCrop = bufferCrop;
3080
3081 mDrawingState.modified = true;
3082 setTransactionFlags(eTransactionNeeded);
3083 return true;
3084}
3085
3086bool Layer::setDestinationFrame(const Rect& destinationFrame) {
3087 if (mDrawingState.destinationFrame == destinationFrame) return false;
3088
3089 mDrawingState.sequence++;
3090 mDrawingState.destinationFrame = destinationFrame;
3091
3092 mDrawingState.modified = true;
3093 setTransactionFlags(eTransactionNeeded);
3094 return true;
3095}
3096
3097// Translate destination frame into scale and position. If a destination frame is not set, use the
3098// provided scale and position
3099bool Layer::updateGeometry() {
3100 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
3101 mDrawingState.destinationFrame.isEmpty()) {
3102 // If destination frame is not set, use the requested transform set via
3103 // Layer::setPosition and Layer::setMatrix.
3104 return assignTransform(&mDrawingState.transform, mRequestedTransform);
3105 }
3106
3107 Rect destRect = mDrawingState.destinationFrame;
3108 int32_t destW = destRect.width();
3109 int32_t destH = destRect.height();
3110 if (destRect.left < 0) {
3111 destRect.left = 0;
3112 destRect.right = destW;
3113 }
3114 if (destRect.top < 0) {
3115 destRect.top = 0;
3116 destRect.bottom = destH;
3117 }
3118
3119 if (!mDrawingState.buffer) {
3120 ui::Transform t;
3121 t.set(destRect.left, destRect.top);
3122 return assignTransform(&mDrawingState.transform, t);
3123 }
3124
3125 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3126 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3127 // Undo any transformations on the buffer.
3128 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3129 std::swap(bufferWidth, bufferHeight);
3130 }
3131 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3132 if (mDrawingState.transformToDisplayInverse) {
3133 if (invTransform & ui::Transform::ROT_90) {
3134 std::swap(bufferWidth, bufferHeight);
3135 }
3136 }
3137
3138 float sx = destW / static_cast<float>(bufferWidth);
3139 float sy = destH / static_cast<float>(bufferHeight);
3140 ui::Transform t;
3141 t.set(sx, 0, 0, sy);
3142 t.set(destRect.left, destRect.top);
3143 return assignTransform(&mDrawingState.transform, t);
3144}
3145
3146bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3147 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3148 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3149 return false;
3150 }
3151
3152 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3153
3154 mDrawingState.sequence++;
3155 mDrawingState.modified = true;
3156 setTransactionFlags(eTransactionNeeded);
3157
3158 return true;
3159}
3160
3161bool Layer::setPosition(float x, float y) {
3162 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3163 return false;
3164 }
3165
3166 mRequestedTransform.set(x, y);
3167
3168 mDrawingState.sequence++;
3169 mDrawingState.modified = true;
3170 setTransactionFlags(eTransactionNeeded);
3171
3172 return true;
3173}
3174
3175bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3176 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3177 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
3178 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003179 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003180 if (!buffer) {
3181 return false;
3182 }
3183
3184 const bool frameNumberChanged =
3185 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3186 const uint64_t frameNumber =
3187 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003188 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003189
3190 if (mDrawingState.buffer) {
3191 mReleasePreviousBuffer = true;
3192 if (!mBufferInfo.mBuffer ||
3193 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3194 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3195 // If mDrawingState has a buffer, and we are about to update again
3196 // before swapping to drawing state, then the first buffer will be
3197 // dropped and we should decrement the pending buffer count and
3198 // call any release buffer callbacks if set.
3199 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3200 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3201 mDrawingState.acquireFence,
3202 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
3203 mOwnerUid));
3204 decrementPendingBufferCount();
3205 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3206 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3207 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
3208 mDrawingState.bufferSurfaceFrameTX.reset();
3209 }
3210 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3211 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3212 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3213 mLastClientCompositionFence,
3214 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
3215 mOwnerUid));
3216 mLastClientCompositionFence = nullptr;
3217 }
3218 }
3219
3220 mDrawingState.frameNumber = frameNumber;
3221 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3222 mDrawingState.buffer = std::move(buffer);
3223 mDrawingState.clientCacheId = bufferData.cachedBuffer;
3224
3225 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3226 ? bufferData.acquireFence
3227 : Fence::NO_FENCE;
3228 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3229 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3230 // We latched this buffer unsiganled, so we need to pass the acquire fence
3231 // on the callback instead of just the acquire time, since it's unknown at
3232 // this point.
3233 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3234 } else {
3235 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3236 }
3237
3238 mDrawingState.modified = true;
3239 setTransactionFlags(eTransactionNeeded);
3240
3241 const int32_t layerId = getSequence();
3242 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3243 mOwnerUid, postTime, getGameMode());
3244 mDrawingState.desiredPresentTime = desiredPresentTime;
3245 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3246
3247 const nsecs_t presentTime = [&] {
3248 if (!isAutoTimestamp) return desiredPresentTime;
3249
3250 const auto prediction =
3251 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
3252 if (prediction.has_value()) return prediction->presentTime;
3253
3254 return static_cast<nsecs_t>(0);
3255 }();
3256
3257 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
3258 mFlinger->mScheduler->recordLayerHistory(this, presentTime, LayerUpdateType::Buffer);
3259
3260 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3261
3262 if (dequeueTime && *dequeueTime != 0) {
3263 const uint64_t bufferId = mDrawingState.buffer->getId();
3264 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3265 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3266 FrameTracer::FrameEvent::DEQUEUE);
3267 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3268 FrameTracer::FrameEvent::QUEUE);
3269 }
3270
3271 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
3272 return true;
3273}
3274
3275bool Layer::setDataspace(ui::Dataspace dataspace) {
3276 mDrawingState.dataspaceRequested = true;
3277 if (mDrawingState.dataspace == dataspace) return false;
3278 mDrawingState.dataspace = dataspace;
3279 mDrawingState.modified = true;
3280 setTransactionFlags(eTransactionNeeded);
3281 return true;
3282}
3283
3284bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3285 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3286 mDrawingState.hdrMetadata = hdrMetadata;
3287 mDrawingState.modified = true;
3288 setTransactionFlags(eTransactionNeeded);
3289 return true;
3290}
3291
3292bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
3293 mDrawingState.surfaceDamageRegion = surfaceDamage;
3294 mDrawingState.modified = true;
3295 setTransactionFlags(eTransactionNeeded);
3296 return true;
3297}
3298
3299bool Layer::setApi(int32_t api) {
3300 if (mDrawingState.api == api) return false;
3301 mDrawingState.api = api;
3302 mDrawingState.modified = true;
3303 setTransactionFlags(eTransactionNeeded);
3304 return true;
3305}
3306
3307bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
3308 if (mDrawingState.sidebandStream == sidebandStream) return false;
3309
3310 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3311 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3312 } else if (sidebandStream != nullptr) {
3313 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3314 }
3315
3316 mDrawingState.sidebandStream = sidebandStream;
3317 mDrawingState.modified = true;
3318 setTransactionFlags(eTransactionNeeded);
3319 if (!mSidebandStreamChanged.exchange(true)) {
3320 // mSidebandStreamChanged was false
3321 mFlinger->onLayerUpdate();
3322 }
3323 return true;
3324}
3325
3326bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles) {
3327 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3328 if (handles.empty()) {
3329 mReleasePreviousBuffer = false;
3330 return false;
3331 }
3332
3333 const bool willPresent = willPresentCurrentTransaction();
3334
3335 for (const auto& handle : handles) {
3336 // If this transaction set a buffer on this layer, release its previous buffer
3337 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3338
3339 // If this layer will be presented in this frame
3340 if (willPresent) {
3341 // If this transaction set an acquire fence on this layer, set its acquire time
3342 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3343 handle->frameNumber = mDrawingState.frameNumber;
3344
3345 // Store so latched time and release fence can be set
3346 mDrawingState.callbackHandles.push_back(handle);
3347
3348 } else { // If this layer will NOT need to be relatched and presented this frame
3349 // Notify the transaction completed thread this handle is done
3350 mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
3351 }
3352 }
3353
3354 mReleasePreviousBuffer = false;
3355 mCallbackHandleAcquireTimeOrFence = -1;
3356
3357 return willPresent;
3358}
3359
3360Rect Layer::getBufferSize(const State& /*s*/) const {
3361 // for buffer state layers we use the display frame size as the buffer size.
3362
3363 if (mBufferInfo.mBuffer == nullptr) {
3364 return Rect::INVALID_RECT;
3365 }
3366
3367 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3368 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3369
3370 // Undo any transformations on the buffer and return the result.
3371 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3372 std::swap(bufWidth, bufHeight);
3373 }
3374
3375 if (getTransformToDisplayInverse()) {
3376 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3377 if (invTransform & ui::Transform::ROT_90) {
3378 std::swap(bufWidth, bufHeight);
3379 }
3380 }
3381
3382 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3383}
3384
3385FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3386 if (mBufferInfo.mBuffer == nullptr) {
3387 return parentBounds;
3388 }
3389
3390 return getBufferSize(getDrawingState()).toFloatRect();
3391}
3392
3393bool Layer::fenceHasSignaled() const {
3394 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3395 return true;
3396 }
3397
3398 const bool fenceSignaled =
3399 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3400 if (!fenceSignaled) {
3401 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3402 TimeStats::LatchSkipReason::LateAcquire);
3403 }
3404
3405 return fenceSignaled;
3406}
3407
Vishnu Nairba354102022-08-01 00:14:18 +00003408bool Layer::onPreComposition(nsecs_t refreshStartTime, bool /* updatingOutputGeometryThisFrame */) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003409 for (const auto& handle : mDrawingState.callbackHandles) {
3410 handle->refreshStartTime = refreshStartTime;
3411 }
3412 return hasReadyFrame();
3413}
3414
3415void Layer::setAutoRefresh(bool autoRefresh) {
3416 mDrawingState.autoRefresh = autoRefresh;
3417}
3418
3419bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3420 // We need to update the sideband stream if the layer has both a buffer and a sideband stream.
3421 editCompositionState()->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
3422
3423 if (mSidebandStreamChanged.exchange(false)) {
3424 const State& s(getDrawingState());
3425 // mSidebandStreamChanged was true
3426 mSidebandStream = s.sidebandStream;
3427 editCompositionState()->sidebandStream = mSidebandStream;
3428 if (mSidebandStream != nullptr) {
3429 setTransactionFlags(eTransactionNeeded);
3430 mFlinger->setTransactionFlags(eTraversalNeeded);
3431 }
3432 recomputeVisibleRegions = true;
3433
3434 return true;
3435 }
3436 return false;
3437}
3438
3439bool Layer::hasFrameUpdate() const {
3440 const State& c(getDrawingState());
3441 return (mDrawingStateModified || mDrawingState.modified) &&
3442 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3443}
3444
3445void Layer::updateTexImage(nsecs_t latchTime) {
3446 const State& s(getDrawingState());
3447
3448 if (!s.buffer) {
3449 if (s.bgColorLayer) {
3450 for (auto& handle : mDrawingState.callbackHandles) {
3451 handle->latchTime = latchTime;
3452 }
3453 }
3454 return;
3455 }
3456
3457 for (auto& handle : mDrawingState.callbackHandles) {
3458 if (handle->frameNumber == mDrawingState.frameNumber) {
3459 handle->latchTime = latchTime;
3460 }
3461 }
3462
3463 const int32_t layerId = getSequence();
3464 const uint64_t bufferId = mDrawingState.buffer->getId();
3465 const uint64_t frameNumber = mDrawingState.frameNumber;
3466 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3467 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3468 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3469
3470 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3471 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3472 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3473 FrameTracer::FrameEvent::LATCH);
3474
3475 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3476 if (bufferSurfaceFrame != nullptr &&
3477 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3478 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3479 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3480 // are processing the next state.
3481 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3482 mDrawingState.acquireFenceTime->getSignalTime(),
3483 latchTime);
3484 mDrawingState.bufferSurfaceFrameTX.reset();
3485 }
3486
3487 std::deque<sp<CallbackHandle>> remainingHandles;
3488 mFlinger->getTransactionCallbackInvoker()
3489 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3490 mDrawingState.callbackHandles = remainingHandles;
3491
3492 mDrawingStateModified = false;
3493}
3494
3495void Layer::gatherBufferInfo() {
3496 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3497 decrementPendingBufferCount();
3498 }
3499
3500 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3501 mBufferInfo.mBuffer = mDrawingState.buffer;
3502 mBufferInfo.mFence = mDrawingState.acquireFence;
3503 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3504 mBufferInfo.mPixelFormat =
3505 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3506 mBufferInfo.mFrameLatencyNeeded = true;
3507 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3508 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3509 mBufferInfo.mFence = mDrawingState.acquireFence;
3510 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3511 auto lastDataspace = mBufferInfo.mDataspace;
3512 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3513 if (lastDataspace != mBufferInfo.mDataspace) {
3514 mFlinger->mSomeDataspaceChanged = true;
3515 }
3516 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3517 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3518 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3519 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3520 mBufferInfo.mApi = mDrawingState.api;
3521 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
3522 mBufferInfo.mBufferSlot = mHwcSlotGenerator->getHwcCacheSlot(mDrawingState.clientCacheId);
3523}
3524
3525Rect Layer::computeBufferCrop(const State& s) {
3526 if (s.buffer && !s.bufferCrop.isEmpty()) {
3527 Rect bufferCrop;
3528 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3529 return bufferCrop;
3530 } else if (s.buffer) {
3531 return s.buffer->getBounds();
3532 } else {
3533 return s.bufferCrop;
3534 }
3535}
3536
3537sp<Layer> Layer::createClone() {
3538 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3539 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003540 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003541 layer->mHwcSlotGenerator = mHwcSlotGenerator;
3542 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3543 return layer;
3544}
3545
3546bool Layer::bufferNeedsFiltering() const {
3547 const State& s(getDrawingState());
3548 if (!s.buffer) {
3549 return false;
3550 }
3551
3552 int32_t bufferWidth = static_cast<int32_t>(s.buffer->getWidth());
3553 int32_t bufferHeight = static_cast<int32_t>(s.buffer->getHeight());
3554
3555 // Undo any transformations on the buffer and return the result.
3556 if (s.bufferTransform & ui::Transform::ROT_90) {
3557 std::swap(bufferWidth, bufferHeight);
3558 }
3559
3560 if (s.transformToDisplayInverse) {
3561 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3562 if (invTransform & ui::Transform::ROT_90) {
3563 std::swap(bufferWidth, bufferHeight);
3564 }
3565 }
3566
3567 const Rect layerSize{getBounds()};
3568 int32_t layerWidth = layerSize.getWidth();
3569 int32_t layerHeight = layerSize.getHeight();
3570
3571 // Align the layer orientation with the buffer before comparism
3572 if (mTransformHint & ui::Transform::ROT_90) {
3573 std::swap(layerWidth, layerHeight);
3574 }
3575
3576 return layerWidth != bufferWidth || layerHeight != bufferHeight;
3577}
3578
3579void Layer::decrementPendingBufferCount() {
3580 int32_t pendingBuffers = --mPendingBufferTransactions;
3581 tracePendingBufferCount(pendingBuffers);
3582}
3583
3584void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3585 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3586}
3587
3588/*
3589 * We don't want to send the layer's transform to input, but rather the
3590 * parent's transform. This is because Layer's transform is
3591 * information about how the buffer is placed on screen. The parent's
3592 * transform makes more sense to send since it's information about how the
3593 * layer is placed on screen. This transform is used by input to determine
3594 * how to go from screen space back to window space.
3595 */
3596ui::Transform Layer::getInputTransform() const {
3597 if (!hasBufferOrSidebandStream()) {
3598 return getTransform();
3599 }
3600 sp<Layer> parent = mDrawingParent.promote();
3601 if (parent == nullptr) {
3602 return ui::Transform();
3603 }
3604
3605 return parent->getTransform();
3606}
3607
3608/**
3609 * Similar to getInputTransform, we need to update the bounds to include the transform.
3610 * This is because bounds don't include the buffer transform, where the input assumes
3611 * that's already included.
3612 */
3613Rect Layer::getInputBounds() const {
3614 if (!hasBufferOrSidebandStream()) {
3615 return getCroppedBufferSize(getDrawingState());
3616 }
3617
3618 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
3619 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
3620 return bufferBounds;
3621 }
3622 return mDrawingState.transform.transform(bufferBounds);
3623}
3624
3625bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3626 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3627
3628 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3629 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3630 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3631 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3632 layer_state_t::eReparent;
3633
3634 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3635 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3636 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3637 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3638 layer_state_t::eInputInfoChanged;
3639
3640 if ((s.what & requiredFlags) != requiredFlags) {
3641 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3642 (s.what | requiredFlags) & ~s.what);
3643 return false;
3644 }
3645
3646 if (s.what & deniedFlags) {
3647 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3648 return false;
3649 }
3650
3651 if (s.what & allowedFlags) {
3652 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3653 }
3654
3655 if (s.what & layer_state_t::ePositionChanged) {
3656 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3657 ALOGV("%s: false [ePositionChanged changed]", __func__);
3658 return false;
3659 }
3660 }
3661
3662 if (s.what & layer_state_t::eAlphaChanged) {
3663 if (mDrawingState.color.a != s.alpha) {
3664 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3665 return false;
3666 }
3667 }
3668
3669 if (s.what & layer_state_t::eColorTransformChanged) {
3670 if (mDrawingState.colorTransform != s.colorTransform) {
3671 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3672 return false;
3673 }
3674 }
3675
3676 if (s.what & layer_state_t::eBackgroundColorChanged) {
3677 if (mDrawingState.bgColorLayer || s.bgColorAlpha != 0) {
3678 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3679 return false;
3680 }
3681 }
3682
3683 if (s.what & layer_state_t::eMatrixChanged) {
3684 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3685 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3686 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3687 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3688 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3689 return false;
3690 }
3691 }
3692
3693 if (s.what & layer_state_t::eCornerRadiusChanged) {
3694 if (mDrawingState.cornerRadius != s.cornerRadius) {
3695 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3696 return false;
3697 }
3698 }
3699
3700 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3701 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3702 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3703 return false;
3704 }
3705 }
3706
3707 if (s.what & layer_state_t::eTransformChanged) {
3708 if (mDrawingState.bufferTransform != s.transform) {
3709 ALOGV("%s: false [eTransformChanged changed]", __func__);
3710 return false;
3711 }
3712 }
3713
3714 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3715 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3716 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3717 return false;
3718 }
3719 }
3720
3721 if (s.what & layer_state_t::eCropChanged) {
3722 if (mDrawingState.crop != s.crop) {
3723 ALOGV("%s: false [eCropChanged changed]", __func__);
3724 return false;
3725 }
3726 }
3727
3728 if (s.what & layer_state_t::eDataspaceChanged) {
3729 if (mDrawingState.dataspace != s.dataspace) {
3730 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3731 return false;
3732 }
3733 }
3734
3735 if (s.what & layer_state_t::eHdrMetadataChanged) {
3736 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3737 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3738 return false;
3739 }
3740 }
3741
3742 if (s.what & layer_state_t::eSidebandStreamChanged) {
3743 if (mDrawingState.sidebandStream != s.sidebandStream) {
3744 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3745 return false;
3746 }
3747 }
3748
3749 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3750 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3751 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3752 return false;
3753 }
3754 }
3755
3756 if (s.what & layer_state_t::eShadowRadiusChanged) {
3757 if (mDrawingState.shadowRadius != s.shadowRadius) {
3758 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3759 return false;
3760 }
3761 }
3762
3763 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3764 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3765 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3766 return false;
3767 }
3768 }
3769
3770 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3771 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3772 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3773 return false;
3774 }
3775 }
3776
3777 if (s.what & layer_state_t::eStretchChanged) {
3778 StretchEffect temp = s.stretchEffect;
3779 temp.sanitize();
3780 if (mDrawingState.stretchEffect != temp) {
3781 ALOGV("%s: false [eStretchChanged changed]", __func__);
3782 return false;
3783 }
3784 }
3785
3786 if (s.what & layer_state_t::eBufferCropChanged) {
3787 if (mDrawingState.bufferCrop != s.bufferCrop) {
3788 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3789 return false;
3790 }
3791 }
3792
3793 if (s.what & layer_state_t::eDestinationFrameChanged) {
3794 if (mDrawingState.destinationFrame != s.destinationFrame) {
3795 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3796 return false;
3797 }
3798 }
3799
3800 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3801 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3802 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3803 return false;
3804 }
3805 }
3806
3807 ALOGV("%s: true", __func__);
3808 return true;
3809}
3810
3811bool Layer::isHdrY410() const {
3812 // pixel format is HDR Y410 masquerading as RGBA_1010102
3813 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3814 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3815 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3816}
3817
3818sp<compositionengine::LayerFE> Layer::getCompositionEngineLayerFE() const {
3819 // There's no need to get a CE Layer if the layer isn't going to draw anything.
3820 if (hasSomethingToDraw()) {
3821 return asLayerFE();
3822 } else {
3823 return nullptr;
3824 }
3825}
3826
3827compositionengine::LayerFECompositionState* Layer::editCompositionState() {
3828 return mCompositionState.get();
3829}
3830
3831const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
3832 return mCompositionState.get();
3833}
3834
3835void Layer::useSurfaceDamage() {
3836 if (mFlinger->mForceFullDamage) {
3837 surfaceDamageRegion = Region::INVALID_REGION;
3838 } else {
3839 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3840 }
3841}
3842
3843void Layer::useEmptyDamage() {
3844 surfaceDamageRegion.clear();
3845}
3846
3847bool Layer::isOpaque(const Layer::State& s) const {
3848 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3849 // layer's opaque flag.
3850 if (!hasSomethingToDraw()) {
3851 return false;
3852 }
3853
3854 // if the layer has the opaque flag, then we're always opaque
3855 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3856 return true;
3857 }
3858
3859 // If the buffer has no alpha channel, then we are opaque
3860 if (hasBufferOrSidebandStream() && isOpaqueFormat(getPixelFormat())) {
3861 return true;
3862 }
3863
3864 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3865 return fillsColor() && getAlpha() == 1.0_hf;
3866}
3867
3868bool Layer::canReceiveInput() const {
3869 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3870}
3871
3872bool Layer::isVisible() const {
3873 if (!hasSomethingToDraw()) {
3874 return false;
3875 }
3876
3877 if (isHiddenByPolicy()) {
3878 return false;
3879 }
3880
3881 return getAlpha() > 0.0f || hasBlur();
3882}
3883
3884void Layer::onPostComposition(const DisplayDevice* display,
3885 const std::shared_ptr<FenceTime>& glDoneFence,
3886 const std::shared_ptr<FenceTime>& presentFence,
3887 const CompositorTiming& compositorTiming) {
3888 // mFrameLatencyNeeded is true when a new frame was latched for the
3889 // composition.
3890 if (!mBufferInfo.mFrameLatencyNeeded) return;
3891
3892 for (const auto& handle : mDrawingState.callbackHandles) {
3893 handle->gpuCompositionDoneFence = glDoneFence;
3894 handle->compositorTiming = compositorTiming;
3895 }
3896
3897 // Update mFrameTracker.
3898 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3899 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3900
3901 const int32_t layerId = getSequence();
3902 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3903
3904 const auto outputLayer = findOutputLayerForDisplay(display);
3905 if (outputLayer && outputLayer->requiresClientComposition()) {
3906 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3907 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3908 clientCompositionTimestamp,
3909 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3910 // Update the SurfaceFrames in the drawing state
3911 if (mDrawingState.bufferSurfaceFrameTX) {
3912 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3913 }
3914 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3915 surfaceFrame->setGpuComposition();
3916 }
3917 }
3918
3919 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3920 if (frameReadyFence->isValid()) {
3921 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3922 } else {
3923 // There was no fence for this frame, so assume that it was ready
3924 // to be presented at the desired present time.
3925 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3926 }
3927
3928 if (display) {
Dominik Laskowskif8734e02022-08-26 09:06:59 -07003929 const Fps refreshRate = display->refreshRateConfigs().getActiveModePtr()->getFps();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003930 const std::optional<Fps> renderRate =
3931 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3932
3933 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3934 const auto gameMode = getGameMode();
3935
3936 if (presentFence->isValid()) {
3937 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3938 refreshRate, renderRate, vote, gameMode);
3939 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3940 presentFence,
3941 FrameTracer::FrameEvent::PRESENT_FENCE);
3942 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3943 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3944 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
3945 // The HWC doesn't support present fences, so use the refresh
3946 // timestamp instead.
3947 const nsecs_t actualPresentTime = display->getRefreshTimestamp();
3948 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3949 refreshRate, renderRate, vote, gameMode);
3950 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3951 mCurrentFrameNumber, actualPresentTime,
3952 FrameTracer::FrameEvent::PRESENT_FENCE);
3953 mFrameTracker.setActualPresentTime(actualPresentTime);
3954 }
3955 }
3956
3957 mFrameTracker.advanceFrame();
3958 mBufferInfo.mFrameLatencyNeeded = false;
3959}
3960
3961bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
3962 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3963 getDrawingState().frameNumber);
3964
3965 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3966
3967 if (refreshRequired) {
3968 return refreshRequired;
3969 }
3970
3971 // If the head buffer's acquire fence hasn't signaled yet, return and
3972 // try again later
3973 if (!fenceHasSignaled()) {
3974 ATRACE_NAME("!fenceHasSignaled()");
3975 mFlinger->onLayerUpdate();
3976 return false;
3977 }
3978
3979 updateTexImage(latchTime);
3980 if (mDrawingState.buffer == nullptr) {
3981 return false;
3982 }
3983
3984 // Capture the old state of the layer for comparisons later
3985 BufferInfo oldBufferInfo = mBufferInfo;
3986 const bool oldOpacity = isOpaque(mDrawingState);
3987 mPreviousFrameNumber = mCurrentFrameNumber;
3988 mCurrentFrameNumber = mDrawingState.frameNumber;
3989 gatherBufferInfo();
3990
3991 if (oldBufferInfo.mBuffer == nullptr) {
3992 // the first time we receive a buffer, we need to trigger a
3993 // geometry invalidation.
3994 recomputeVisibleRegions = true;
3995 }
3996
3997 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3998 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3999 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
4000 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
4001 recomputeVisibleRegions = true;
4002 }
4003
4004 if (oldBufferInfo.mBuffer != nullptr) {
4005 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
4006 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
4007 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
4008 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
4009 recomputeVisibleRegions = true;
4010 }
4011 }
4012
4013 if (oldOpacity != isOpaque(mDrawingState)) {
4014 recomputeVisibleRegions = true;
4015 }
4016
4017 return true;
4018}
4019
4020bool Layer::hasReadyFrame() const {
4021 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4022}
4023
4024bool Layer::isProtected() const {
4025 return (mBufferInfo.mBuffer != nullptr) &&
4026 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4027}
4028
4029// As documented in libhardware header, formats in the range
4030// 0x100 - 0x1FF are specific to the HAL implementation, and
4031// are known to have no alpha channel
4032// TODO: move definition for device-specific range into
4033// hardware.h, instead of using hard-coded values here.
4034#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
4035
4036bool Layer::isOpaqueFormat(PixelFormat format) {
4037 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
4038 return true;
4039 }
4040 switch (format) {
4041 case PIXEL_FORMAT_RGBA_8888:
4042 case PIXEL_FORMAT_BGRA_8888:
4043 case PIXEL_FORMAT_RGBA_FP16:
4044 case PIXEL_FORMAT_RGBA_1010102:
4045 case PIXEL_FORMAT_R_8:
4046 return false;
4047 }
4048 // in all other case, we have no blending (also for unknown formats)
4049 return true;
4050}
4051
4052bool Layer::needsFiltering(const DisplayDevice* display) 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 // displayframe rectangle size (not a 1:1 render)
4063 const auto& compositionState = outputLayer->getState();
4064 const auto displayFrame = compositionState.displayFrame;
4065 const auto sourceCrop = compositionState.sourceCrop;
4066 return sourceCrop.getHeight() != displayFrame.getHeight() ||
4067 sourceCrop.getWidth() != displayFrame.getWidth();
4068}
4069
4070bool Layer::needsFilteringForScreenshots(const DisplayDevice* display,
4071 const ui::Transform& inverseParentTransform) const {
4072 if (!hasBufferOrSidebandStream()) {
4073 return false;
4074 }
4075 const auto outputLayer = findOutputLayerForDisplay(display);
4076 if (outputLayer == nullptr) {
4077 return false;
4078 }
4079
4080 // We need filtering if the sourceCrop rectangle size does not match the
4081 // viewport rectangle size (not a 1:1 render)
4082 const auto& compositionState = outputLayer->getState();
4083 const ui::Transform& displayTransform = display->getTransform();
4084 const ui::Transform inverseTransform = inverseParentTransform * displayTransform.inverse();
4085 // Undo the transformation of the displayFrame so that we're back into
4086 // layer-stack space.
4087 const Rect frame = inverseTransform.transform(compositionState.displayFrame);
4088 const FloatRect sourceCrop = compositionState.sourceCrop;
4089
4090 int32_t frameHeight = frame.getHeight();
4091 int32_t frameWidth = frame.getWidth();
4092 // If the display transform had a rotational component then undo the
4093 // rotation so that the orientation matches the source crop.
4094 if (displayTransform.getOrientation() & ui::Transform::ROT_90) {
4095 std::swap(frameHeight, frameWidth);
4096 }
4097 return sourceCrop.getHeight() != frameHeight || sourceCrop.getWidth() != frameWidth;
4098}
4099
4100void Layer::latchAndReleaseBuffer() {
4101 if (hasReadyFrame()) {
4102 bool ignored = false;
4103 latchBuffer(ignored, systemTime());
4104 }
4105 releasePendingBuffer(systemTime());
4106}
4107
4108PixelFormat Layer::getPixelFormat() const {
4109 return mBufferInfo.mPixelFormat;
4110}
4111
4112bool Layer::getTransformToDisplayInverse() const {
4113 return mBufferInfo.mTransformToDisplayInverse;
4114}
4115
4116Rect Layer::getBufferCrop() const {
4117 // this is the crop rectangle that applies to the buffer
4118 // itself (as opposed to the window)
4119 if (!mBufferInfo.mCrop.isEmpty()) {
4120 // if the buffer crop is defined, we use that
4121 return mBufferInfo.mCrop;
4122 } else if (mBufferInfo.mBuffer != nullptr) {
4123 // otherwise we use the whole buffer
4124 return mBufferInfo.mBuffer->getBounds();
4125 } else {
4126 // if we don't have a buffer yet, we use an empty/invalid crop
4127 return Rect();
4128 }
4129}
4130
4131uint32_t Layer::getBufferTransform() const {
4132 return mBufferInfo.mTransform;
4133}
4134
4135ui::Dataspace Layer::getDataSpace() const {
4136 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
4137}
4138
4139ui::Dataspace Layer::getRequestedDataSpace() const {
4140 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4141}
4142
4143ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4144 ui::Dataspace updatedDataspace = dataspace;
4145 // translate legacy dataspaces to modern dataspaces
4146 switch (dataspace) {
4147 case ui::Dataspace::SRGB:
4148 updatedDataspace = ui::Dataspace::V0_SRGB;
4149 break;
4150 case ui::Dataspace::SRGB_LINEAR:
4151 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4152 break;
4153 case ui::Dataspace::JFIF:
4154 updatedDataspace = ui::Dataspace::V0_JFIF;
4155 break;
4156 case ui::Dataspace::BT601_625:
4157 updatedDataspace = ui::Dataspace::V0_BT601_625;
4158 break;
4159 case ui::Dataspace::BT601_525:
4160 updatedDataspace = ui::Dataspace::V0_BT601_525;
4161 break;
4162 case ui::Dataspace::BT709:
4163 updatedDataspace = ui::Dataspace::V0_BT709;
4164 break;
4165 default:
4166 break;
4167 }
4168
4169 return updatedDataspace;
4170}
4171
4172sp<GraphicBuffer> Layer::getBuffer() const {
4173 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4174}
4175
4176void Layer::getDrawingTransformMatrix(bool filteringEnabled, float outMatrix[16]) const {
4177 sp<GraphicBuffer> buffer = getBuffer();
4178 if (!buffer) {
4179 ALOGE("Buffer should not be null!");
4180 return;
4181 }
4182 GLConsumer::computeTransformMatrix(outMatrix, buffer->getWidth(), buffer->getHeight(),
4183 buffer->getPixelFormat(), mBufferInfo.mCrop,
4184 mBufferInfo.mTransform, filteringEnabled);
4185}
4186
4187void Layer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
4188 mTransformHint = getFixedTransformHint();
4189 if (mTransformHint == ui::Transform::ROT_INVALID) {
4190 mTransformHint = displayTransformHint;
4191 }
4192}
4193
4194const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4195 return mBufferInfo.mBuffer;
4196}
4197
4198bool Layer::setColor(const half3& color) {
4199 if (mDrawingState.color.r == color.r && mDrawingState.color.g == color.g &&
4200 mDrawingState.color.b == color.b) {
4201 return false;
4202 }
4203
4204 mDrawingState.sequence++;
4205 mDrawingState.color.r = color.r;
4206 mDrawingState.color.g = color.g;
4207 mDrawingState.color.b = color.b;
4208 mDrawingState.modified = true;
4209 setTransactionFlags(eTransactionNeeded);
4210 return true;
4211}
4212
4213bool Layer::fillsColor() const {
4214 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4215 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4216}
4217
4218bool Layer::hasBlur() const {
4219 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4220}
4221
Vishnu Nairba354102022-08-01 00:14:18 +00004222void Layer::updateSnapshot(bool updateGeometry) {
4223 if (!getCompositionEngineLayerFE()) {
4224 return;
4225 }
4226
4227 if (updateGeometry) {
4228 prepareBasicGeometryCompositionState();
4229 prepareGeometryCompositionState();
4230 }
4231 preparePerFrameCompositionState();
4232}
4233
Mathias Agopian13127d82013-03-05 17:47:11 -08004234// ---------------------------------------------------------------------------
4235
Marin Shalamanov46084422020-10-13 12:33:42 +02004236std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004237 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
4238 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02004239}
4240
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004241} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004242
4243#if defined(__gl_h_)
4244#error "don't include gl/gl.h in this file"
4245#endif
4246
4247#if defined(__gl2_h_)
4248#error "don't include gl2/gl2.h in this file"
4249#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004250
4251// TODO(b/129481165): remove the #pragma below and fix conversion issues
4252#pragma clang diagnostic pop // ignored "-Wconversion"