blob: 631cf65de84782f1a4fc985f2915a1c7c25aac32 [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>
43#include <gui/LayerDebugInfo.h>
44#include <gui/Surface.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000045#include <gui/TraceUtils.h>
Alec Mourie60041e2019-06-14 18:59:51 -070046#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070047#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070049#include <stdint.h>
50#include <stdlib.h>
51#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000052#include <system/graphics-base-v1.0.h>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070053#include <ui/DataspaceUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080054#include <ui/DebugUtils.h>
55#include <ui/GraphicBuffer.h>
56#include <ui/PixelFormat.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#include <utils/Errors.h>
58#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080059#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080061#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Alec Mourie60041e2019-06-14 18:59:51 -070063#include <algorithm>
64#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070065#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070066#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"
Vishnu Naircb8be502022-10-12 19:03:23 +000072#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000073#include "FrontEnd/LayerHandle.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080074#include "LayerProtoHelper.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080076#include "TimeStats/TimeStats.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070077#include "TunnelModeEnabledReporter.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070078
David Sodman41fdfc92017-11-06 16:09:56 -080079#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000080#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082namespace android {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010083namespace {
84constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000085
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000086const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000087
Patrick Williamsbb25f802022-08-30 23:02:34 +000088bool assignTransform(ui::Transform* dst, ui::Transform& from) {
89 if (*dst == from) {
90 return false;
91 }
92 *dst = from;
93 return true;
94}
95
96TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
97 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
98 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
99 const auto frameRateCompatibility = [frameRate] {
100 switch (frameRate.type) {
101 case Layer::FrameRateCompatibility::Default:
102 return FrameRateCompatibility::Default;
103 case Layer::FrameRateCompatibility::ExactOrMultiple:
104 return FrameRateCompatibility::ExactOrMultiple;
105 default:
106 return FrameRateCompatibility::Undefined;
107 }
108 }();
109
110 const auto seamlessness = [frameRate] {
111 switch (frameRate.seamlessness) {
112 case scheduler::Seamlessness::OnlySeamless:
113 return Seamlessness::ShouldBeSeamless;
114 case scheduler::Seamlessness::SeamedAndSeamless:
115 return Seamlessness::NotRequired;
116 default:
117 return Seamlessness::Undefined;
118 }
119 }();
120
121 return TimeStats::SetFrameRateVote{.frameRate = frameRate.rate.getValue(),
122 .frameRateCompatibility = frameRateCompatibility,
123 .seamlessness = seamlessness};
124}
125
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100126} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700128using namespace ftl::flag_operators;
129
Yiwei Zhang5434a782018-12-05 18:06:32 -0800130using base::StringAppendF;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800131using gui::GameMode;
132using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500133using gui::WindowInfo;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800134
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700135using PresentState = frametimeline::SurfaceFrame::PresentState;
136
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700137Layer::Layer(const LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000138 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700139 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000140 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700141 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800142 mWindowType(static_cast<WindowInfo::Type>(
143 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000144 mLayerCreationFlags(args.flags),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000145 mBorderEnabled(false),
146 mTextureName(args.textureName),
Vishnu Naire14c6b32022-08-06 04:20:15 +0000147 mHwcSlotGenerator(sp<HwcSlotGenerator>::make()),
148 mLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000149 ALOGV("Creating Layer %s", getDebugName());
150
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700151 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700152 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
153 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
154 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700155 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
156 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700157 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700158 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700159 mDrawingState.z = 0;
160 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700161 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700162 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700163 mDrawingState.transform.set(0, 0);
164 mDrawingState.frameNumber = 0;
165 mDrawingState.bufferTransform = 0;
166 mDrawingState.transformToDisplayInverse = false;
167 mDrawingState.crop.makeInvalid();
168 mDrawingState.acquireFence = sp<Fence>::make(-1);
169 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
170 mDrawingState.dataspace = ui::Dataspace::UNKNOWN;
Vishnu Nairbc4ee5c2022-08-16 03:19:37 +0000171 mDrawingState.dataspaceRequested = false;
Robert Carr6a160312021-05-17 12:08:20 -0700172 mDrawingState.hdrMetadata.validTypes = 0;
173 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
174 mDrawingState.cornerRadius = 0.0f;
175 mDrawingState.backgroundBlurRadius = 0;
176 mDrawingState.api = -1;
177 mDrawingState.hasColorTransform = false;
178 mDrawingState.colorSpaceAgnostic = false;
179 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
180 mDrawingState.metadata = args.metadata;
181 mDrawingState.shadowRadius = 0.f;
182 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
183 mDrawingState.frameTimelineInfo = {};
184 mDrawingState.postTime = -1;
185 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000186 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700187 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700188 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000189 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700190
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700191 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
192 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700193 mDrawingState.color.r = -1.0_hf;
194 mDrawingState.color.g = -1.0_hf;
195 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700196 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700197
198 mFrameTracker.setDisplayRefreshPeriod(
199 args.flinger->mScheduler->getVsyncPeriodFromRefreshRateConfigs());
Robert Carr2e102c92018-10-23 12:11:15 -0700200
Vishnu Naircb8be502022-10-12 19:03:23 +0000201 mOwnerUid = args.ownerUid;
202 mOwnerPid = args.ownerPid;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000203
204 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
205 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
206 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
207 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000208
209 mSnapshot->sequence = sequence;
210 mSnapshot->name = getDebugName();
211 mSnapshot->textureName = mTextureName;
212 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
213 mSnapshot->transform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800214}
215
216void Layer::onFirstRef() {
217 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700218}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700219
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700220Layer::~Layer() {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000221 // The original layer and the clone layer share the same texture and buffer. Therefore, only
222 // one of the layers, in this case the original layer, needs to handle the deletion. The
223 // original layer and the clone should be removed at the same time so there shouldn't be any
224 // issue with the clone layer trying to use the texture.
225 if (mBufferInfo.mBuffer != nullptr) {
226 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
227 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
228 mBufferInfo.mFence,
229 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
230 mOwnerUid));
231 }
232 if (!isClone()) {
233 // The original layer and the clone layer share the same texture. Therefore, only one of
234 // the layers, in this case the original layer, needs to handle the deletion. The original
235 // layer and the clone should be removed at the same time so there shouldn't be any issue
236 // with the clone layer trying to use the deleted texture.
237 mFlinger->deleteTextureAsync(mTextureName);
238 }
239 const int32_t layerId = getSequence();
240 mFlinger->mTimeStats->onDestroy(layerId);
241 mFlinger->mFrameTracer->onDestroy(layerId);
242
David Sodman577c8962017-12-08 14:50:53 -0800243 sp<Client> c(mClientRef.promote());
244 if (c != 0) {
245 c->detachLayer(this);
246 }
247
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000248 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700249 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700250
251 if (mDrawingState.sidebandStream != nullptr) {
252 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
253 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700254 if (mHadClonedChild) {
255 mFlinger->mNumClones--;
256 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700257}
258
Mathias Agopian13127d82013-03-05 17:47:11 -0800259// ---------------------------------------------------------------------------
260// callbacks
261// ---------------------------------------------------------------------------
262
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700263void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700264 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700265 return;
266 }
Robert Carr2e102c92018-10-23 12:11:15 -0700267
Robert Carr6a160312021-05-17 12:08:20 -0700268 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700269 if (strongRelative == nullptr) {
270 setZOrderRelativeOf(nullptr);
271 return;
272 }
273
274 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700275 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700276 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800277 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700278 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700279}
280
281void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700282 if (!mRemovedFromDrawingState) {
283 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700284 mFlinger->mScheduler->deregisterLayer(this);
285 }
Rob Carr4bba3702018-10-08 21:53:30 +0000286
Ady Abrahamd11bade2022-08-01 16:18:03 -0700287 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700288}
Chia-I Wu38512252017-05-17 14:36:16 -0700289
chaviw68d4dab2020-06-08 15:07:32 -0700290sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000291 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700292 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700293 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700294 }
295 return parent->getRootLayer();
296}
297
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700298void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700299 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
300 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700301 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700302
303 traverse(LayerVector::StateSet::Current, [&](Layer* layer) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700304 layer->removeFromCurrentState();
305 layer->removeRelativeZ(layersInTree);
chaviw68d4dab2020-06-08 15:07:32 -0700306 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700307}
308
chaviw61626f22018-11-15 16:26:27 -0800309void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700310 if (mRemovedFromDrawingState) {
311 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700312 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700313 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700314 }
chaviw61626f22018-11-15 16:26:27 -0800315
316 for (const auto& child : mCurrentChildren) {
317 child->addToCurrentState();
318 }
319}
320
Mathias Agopian13127d82013-03-05 17:47:11 -0800321// ---------------------------------------------------------------------------
322// set-up
323// ---------------------------------------------------------------------------
324
chaviw13fdc492017-06-27 12:40:18 -0700325bool Layer::getPremultipledAlpha() const {
326 return mPremultipliedAlpha;
327}
328
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700329sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800330 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700331 if (mGetHandleCalled) {
332 ALOGE("Get handle called twice" );
333 return nullptr;
334 }
335 mGetHandleCalled = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000336 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800337}
338
339// ---------------------------------------------------------------------------
340// h/w composer set-up
341// ---------------------------------------------------------------------------
342
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700343static Rect reduce(const Rect& win, const Region& exclude) {
344 if (CC_LIKELY(exclude.isEmpty())) {
345 return win;
346 }
347 if (exclude.isRect()) {
348 return win.reduce(exclude.getBounds());
349 }
350 return Region(win).subtract(exclude).getBounds();
351}
352
Dan Stoza80d61162017-12-20 15:57:52 -0800353static FloatRect reduce(const FloatRect& win, const Region& exclude) {
354 if (CC_LIKELY(exclude.isEmpty())) {
355 return win;
356 }
357 // Convert through Rect (by rounding) for lack of FloatRegion
358 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
359}
360
Vishnu Nair4351ad52019-02-11 14:13:02 -0800361Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800362 if (!reduceTransparentRegion) {
363 return Rect{mScreenBounds};
364 }
365
366 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800367 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800368 // Transform to screen space.
369 bounds = t.transform(bounds);
370 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700371}
372
Vishnu Nair4351ad52019-02-11 14:13:02 -0800373FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000374 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800375 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700376}
377
Vishnu Nairf0c28512019-02-08 12:40:28 -0800378FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
379 // Subtract the transparent region and snap to the bounds.
380 return reduce(mBounds, activeTransparentRegion);
381}
382
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700383void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
384 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800385 const State& s(getDrawingState());
386
387 // Calculate effective layer transform
388 mEffectiveTransform = parentTransform * getActiveTransform(s);
389
Garfield Tan2c1782c2022-02-16 15:25:05 -0800390 if (CC_UNLIKELY(!isTransformValid())) {
391 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
392 getDebugName());
393 return;
394 }
395
Vishnu Nair4351ad52019-02-11 14:13:02 -0800396 // Transform parent bounds to layer space
397 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
398
Vishnu Nairc652ff82019-03-15 12:48:54 -0700399 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800400 mSourceBounds = computeSourceBounds(parentBounds);
401
402 // Calculate bounds by croping diplay frame with layer crop and parent bounds
403 FloatRect bounds = mSourceBounds;
404 const Rect layerCrop = getCrop(s);
405 if (!layerCrop.isEmpty()) {
406 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
407 }
408 bounds = bounds.intersect(parentBounds);
409
410 mBounds = bounds;
411 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700412
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700413 // Use the layer's own shadow radius if set. Otherwise get the radius from
414 // parent.
415 if (s.shadowRadius > 0.f) {
416 mEffectiveShadowRadius = s.shadowRadius;
417 } else {
418 mEffectiveShadowRadius = parentShadowRadius;
419 }
420
421 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
422 // don't pass it to its children.
423 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
424
Vishnu Nair4351ad52019-02-11 14:13:02 -0800425 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700426 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800427 }
Vishnu Nairba354102022-08-01 00:14:18 +0000428
429 if (mPotentialCursor) {
430 prepareCursorCompositionState();
431 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800432}
433
Vishnu Nair60356342018-11-13 13:00:45 -0800434Rect Layer::getCroppedBufferSize(const State& s) const {
435 Rect size = getBufferSize(s);
436 Rect crop = getCrop(s);
437 if (!crop.isEmpty() && size.isValid()) {
438 size.intersect(crop, &size);
439 } else if (!crop.isEmpty()) {
440 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700441 }
Vishnu Nair60356342018-11-13 13:00:45 -0800442 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800443}
444
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700445void Layer::setupRoundedCornersCropCoordinates(Rect win,
446 const FloatRect& roundedCornersCrop) const {
447 // Translate win by the rounded corners rect coordinates, to have all values in
448 // layer coordinate space.
449 win.left -= roundedCornersCrop.left;
450 win.right -= roundedCornersCrop.left;
451 win.top -= roundedCornersCrop.top;
452 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700453}
454
Lloyd Piquede196652020-01-22 17:29:58 -0800455void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800456 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800457 const auto alpha = static_cast<float>(getAlpha());
458 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700459 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800460
461 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
462 if (!opaque || alpha != 1.0f) {
463 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
464 : Hwc2::IComposerClient::BlendMode::COVERAGE;
465 }
466
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000467 auto* snapshot = editLayerSnapshot();
468 snapshot->outputFilter = getOutputFilter();
469 snapshot->isVisible = isVisible();
470 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
471 snapshot->shadowRadius = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800472
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000473 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800474 contentDirty = false;
475
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000476 snapshot->geomLayerBounds = mBounds;
477 snapshot->geomLayerTransform = getTransform();
478 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
479 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Lloyd Piquec6687342019-03-07 21:34:57 -0800480
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000481 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
482 snapshot->alpha = alpha;
483 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
484 snapshot->blurRegions = drawingState.blurRegions;
485 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800486}
487
Lloyd Piquede196652020-01-22 17:29:58 -0800488void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800489 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000490 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700491
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000492 snapshot->geomBufferSize = getBufferSize(drawingState);
493 snapshot->geomContentCrop = getBufferCrop();
494 snapshot->geomCrop = getCrop(drawingState);
495 snapshot->geomBufferTransform = getBufferTransform();
496 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
497 snapshot->geomUsesSourceCrop = usesSourceCrop();
498 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800499
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000500 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800501 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
502 for (const auto& [key, mandatory] : supportedMetadata) {
503 const auto& genericLayerMetadataCompatibilityMap =
504 mFlinger->getGenericLayerMetadataKeyMap();
505 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
506 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
507 continue;
508 }
509 const uint32_t id = compatIter->second;
510
511 auto it = drawingState.metadata.mMap.find(id);
512 if (it == std::end(drawingState.metadata.mMap)) {
513 continue;
514 }
515
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000516 snapshot->metadata.emplace(key,
517 compositionengine::GenericLayerMetadataEntry{mandatory,
518 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800519 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800520}
David Sodmanba340492018-08-05 21:51:33 -0700521
Lloyd Piquede196652020-01-22 17:29:58 -0800522void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800523 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000524 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800525
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000526 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800527
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000528 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
529 snapshot->dataspace = getDataSpace();
530 snapshot->colorTransform = getColorTransform();
531 snapshot->colorTransformIsIdentity = !hasColorTransform();
532 snapshot->surfaceDamage = surfaceDamageRegion;
533 snapshot->hasProtectedContent = isProtected();
534 snapshot->dimmingEnabled = isDimmingEnabled();
Lloyd Pique688abd42019-02-15 15:42:24 -0800535
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700536 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700537
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000538 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800539
540 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400541 // Rounded corners no longer force client composition, since we may use a
542 // hole punch so that the layer will appear to have rounded corners.
543 if (isHdrY410() || drawShadows() || drawingState.blurRegions.size() > 0 ||
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000544 snapshot->stretchEffect.hasEffect()) {
545 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800546 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700547 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000548 snapshot->blurRegions = drawingState.blurRegions;
549 snapshot->backgroundBlurRadius = drawingState.backgroundBlurRadius;
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400550
551 // Layer framerate is used in caching decisions.
552 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
553 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000554 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000555
556 if (hasBufferOrSidebandStream()) {
557 preparePerFrameBufferCompositionState();
558 } else {
559 preparePerFrameEffectsCompositionState();
560 }
561}
562
563void Layer::preparePerFrameBufferCompositionState() {
564 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000565 auto* snapshot = editLayerSnapshot();
566 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
567 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000568 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
569 return;
570 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000571 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000572 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
573 } else {
574 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000575 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
576 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000577 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
578 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
579 }
580
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000581 snapshot->buffer = getBuffer();
582 snapshot->bufferSlot = (mBufferInfo.mBufferSlot == BufferQueue::INVALID_BUFFER_SLOT)
Patrick Williamsbb25f802022-08-30 23:02:34 +0000583 ? 0
584 : mBufferInfo.mBufferSlot;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000585 snapshot->acquireFence = mBufferInfo.mFence;
586 snapshot->frameNumber = mBufferInfo.mFrameNumber;
587 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000588}
589
590void Layer::preparePerFrameEffectsCompositionState() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000591 auto* snapshot = editLayerSnapshot();
592 snapshot->color = getColor();
593 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000594 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800595}
596
Lloyd Piquede196652020-01-22 17:29:58 -0800597void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800598 const State& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000599 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800600
601 // Apply the layer's transform, followed by the display's global transform
602 // Here we're guaranteed that the layer's transform preserves rects
603 Rect win = getCroppedBufferSize(drawingState);
604 // Subtract the transparent region and snap to the bounds
605 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
606 Rect frame(getTransform().transform(bounds));
607
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000608 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800609}
610
Lloyd Piquea83776c2019-01-29 18:42:32 -0800611const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700612 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800613}
614
Mathias Agopian13127d82013-03-05 17:47:11 -0800615// ---------------------------------------------------------------------------
616// drawing...
617// ---------------------------------------------------------------------------
618
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500619aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
620 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700621 const auto outputLayer = findOutputLayerForDisplay(&display);
Alec Mouri6b9e9912020-01-21 10:50:24 -0800622 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500623 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800624 }
625 if (outputLayer->getState().hwc) {
626 return (*outputLayer->getState().hwc).hwcCompositionType;
627 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500628 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800629 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800630}
631
Mathias Agopian13127d82013-03-05 17:47:11 -0800632// ----------------------------------------------------------------------------
633// local state
634// ----------------------------------------------------------------------------
635
David Sodman41fdfc92017-11-06 16:09:56 -0800636bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800637 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700638 if (s.flags & layer_state_t::eLayerSecure) {
639 return true;
640 }
641
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000642 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700643 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700644}
645
Mathias Agopian13127d82013-03-05 17:47:11 -0800646// ----------------------------------------------------------------------------
647// transaction
648// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800649
Marissa Wall61c58622018-07-18 10:12:20 -0700650uint32_t Layer::doTransaction(uint32_t flags) {
651 ATRACE_CALL();
652
Robert Carr0758e5d2021-03-11 22:15:04 -0800653 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700654 mDrawingStateModified = mDrawingState.modified;
655 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700656
Alec Mourib416efd2018-09-06 21:01:59 +0000657 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700658
Robert Carr6a160312021-05-17 12:08:20 -0700659 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800660 // invalidate and recompute the visible regions if needed
661 flags |= Layer::eVisibleRegion;
662 }
663
Robert Carr6a160312021-05-17 12:08:20 -0700664 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800665 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000666 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800667 flags |= eVisibleRegion;
668 this->contentDirty = true;
669
670 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700671 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800672 }
673
Arthur Hung9ed43392022-05-27 06:31:57 +0000674 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
675 mFlinger->mUpdateInputInfo = true;
676 }
677
Robert Carr6a160312021-05-17 12:08:20 -0700678 commitTransaction(mDrawingState);
Robert Carra1257842020-01-31 13:48:28 -0800679
Mathias Agopian13127d82013-03-05 17:47:11 -0800680 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800681}
682
Robert Carr6a160312021-05-17 12:08:20 -0700683void Layer::commitTransaction(State&) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000684 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
685 // bufferSurfaceFrameTX will be presented in latchBuffer.
686 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
687 if (surfaceFrame->getPresentState() != PresentState::Presented) {
688 // With applyPendingStates, we could end up having presented surfaceframes from previous
689 // states
690 surfaceFrame->setPresentState(PresentState::Presented);
691 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
692 }
693 }
Robert Carr6a160312021-05-17 12:08:20 -0700694 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700695}
696
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700697uint32_t Layer::clearTransactionFlags(uint32_t mask) {
698 const auto flags = mTransactionFlags & mask;
699 mTransactionFlags &= ~mask;
700 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800701}
702
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700703void Layer::setTransactionFlags(uint32_t mask) {
704 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800705}
706
Robert Carr1f0a16a2016-10-24 16:27:39 -0700707bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
708 ssize_t idx = mCurrentChildren.indexOf(childLayer);
709 if (idx < 0) {
710 return false;
711 }
712 if (childLayer->setLayer(z)) {
713 mCurrentChildren.removeAt(idx);
714 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800715 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700716 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800717 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700718}
719
Robert Carr503c7042017-09-27 15:06:08 -0700720bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
721 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
722 ssize_t idx = mCurrentChildren.indexOf(childLayer);
723 if (idx < 0) {
724 return false;
725 }
726 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
727 mCurrentChildren.removeAt(idx);
728 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800729 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700730 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800731 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700732}
733
Robert Carrae060832016-11-28 10:51:00 -0800734bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700735 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
736 mDrawingState.sequence++;
737 mDrawingState.z = z;
738 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700739
Robert Carra70e91c2021-06-11 13:59:52 -0700740 mFlinger->mSomeChildrenChanged = true;
741
Robert Carrdb66e622017-04-10 16:55:57 -0700742 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700743 if (mDrawingState.zOrderRelativeOf != nullptr) {
744 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700745 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700746 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700747 }
chaviw606e5cf2019-03-01 10:12:10 -0800748 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700749 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800750 setTransactionFlags(eTransactionNeeded);
751 return true;
752}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700753
Robert Carrdb66e622017-04-10 16:55:57 -0700754void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700755 mDrawingState.zOrderRelatives.remove(relative);
756 mDrawingState.sequence++;
757 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700758 setTransactionFlags(eTransactionNeeded);
759}
760
761void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700762 mDrawingState.zOrderRelatives.add(relative);
763 mDrawingState.modified = true;
764 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700765 setTransactionFlags(eTransactionNeeded);
766}
767
chaviw606e5cf2019-03-01 10:12:10 -0800768void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700769 mDrawingState.zOrderRelativeOf = relativeOf;
770 mDrawingState.sequence++;
771 mDrawingState.modified = true;
772 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700773
chaviw606e5cf2019-03-01 10:12:10 -0800774 setTransactionFlags(eTransactionNeeded);
775}
776
Robert Carr503d2bd2017-12-04 15:49:47 -0800777bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000778 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700779 if (relative == nullptr) {
780 return false;
781 }
782
Robert Carr6a160312021-05-17 12:08:20 -0700783 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
784 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800785 return false;
786 }
787
Robert Carr88b85e12022-03-21 15:47:35 -0700788 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
789 (relative->mDrawingState.zOrderRelativeOf == this)) {
790 ALOGE("Detected relative layer loop between %s and %s",
791 mName.c_str(), relative->mName.c_str());
792 ALOGE("Ignoring new call to set relative layer");
793 return false;
794 }
795
Robert Carra70e91c2021-06-11 13:59:52 -0700796 mFlinger->mSomeChildrenChanged = true;
797
Robert Carr6a160312021-05-17 12:08:20 -0700798 mDrawingState.sequence++;
799 mDrawingState.modified = true;
800 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700801
Robert Carr6a160312021-05-17 12:08:20 -0700802 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700803 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700804 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700805 }
chaviw606e5cf2019-03-01 10:12:10 -0800806 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700807 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700808
809 setTransactionFlags(eTransactionNeeded);
810
811 return true;
812}
813
Winson Chunga30f7c92021-06-29 15:42:56 -0700814bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
815 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
816 mDrawingState.isTrustedOverlay = isTrustedOverlay;
817 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000818 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700819 setTransactionFlags(eTransactionNeeded);
820 return true;
821}
822
823bool Layer::isTrustedOverlay() const {
824 if (getDrawingState().isTrustedOverlay) {
825 return true;
826 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000827 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700828 return (p != nullptr) && p->isTrustedOverlay();
829}
830
Dan Stoza9e56aa02015-11-02 13:00:03 -0800831bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700832 if (mDrawingState.color.a == alpha) return false;
833 mDrawingState.sequence++;
834 mDrawingState.color.a = alpha;
835 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800836 setTransactionFlags(eTransactionNeeded);
837 return true;
838}
chaviw13fdc492017-06-27 12:40:18 -0700839
Valerie Haudd0b7572019-01-29 14:59:27 -0800840bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700841 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700842 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800843 }
Robert Carr6a160312021-05-17 12:08:20 -0700844 mDrawingState.sequence++;
845 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800846 setTransactionFlags(eTransactionNeeded);
847
Robert Carr6a160312021-05-17 12:08:20 -0700848 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -0800849 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -0800850 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700851 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -0700852 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Vishnu Nair7fb9e5a2021-11-08 12:44:05 -0800853 LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700854 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -0700855
Valerie Haudd0b7572019-01-29 14:59:27 -0800856 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -0700857 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -0800858 mFlinger->mLayersAdded = true;
859 // set up SF to handle added color layer
860 if (isRemovedFromCurrentState()) {
Robert Carr6a160312021-05-17 12:08:20 -0700861 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -0800862 }
863 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -0700864 } else if (mDrawingState.bgColorLayer && alpha == 0) {
865 mDrawingState.bgColorLayer->reparent(nullptr);
866 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -0800867 return true;
868 }
869
Robert Carr6a160312021-05-17 12:08:20 -0700870 mDrawingState.bgColorLayer->setColor(color);
871 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
872 mDrawingState.bgColorLayer->setAlpha(alpha);
873 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -0800874
chaviw13fdc492017-06-27 12:40:18 -0700875 return true;
876}
877
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700878bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -0700879 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700880
Robert Carr6a160312021-05-17 12:08:20 -0700881 mDrawingState.sequence++;
882 mDrawingState.cornerRadius = cornerRadius;
883 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700884 setTransactionFlags(eTransactionNeeded);
885 return true;
886}
887
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800888bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -0700889 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -0700890 // If we start or stop drawing blur then the layer's visibility state may change so increment
891 // the magic sequence number.
892 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
893 mDrawingState.sequence++;
894 }
Robert Carr6a160312021-05-17 12:08:20 -0700895 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
896 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800897 setTransactionFlags(eTransactionNeeded);
898 return true;
899}
Marissa Wall61c58622018-07-18 10:12:20 -0700900
Mathias Agopian13127d82013-03-05 17:47:11 -0800901bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +0000902 mDrawingState.sequence++;
903 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -0700904 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800905 setTransactionFlags(eTransactionNeeded);
906 return true;
907}
Ana Krulecc84d09b2019-11-02 23:10:29 +0100908
Lucas Dupinc3800b82020-10-02 16:24:48 -0700909bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -0700910 // If we start or stop drawing blur then the layer's visibility state may change so increment
911 // the magic sequence number.
912 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
913 mDrawingState.sequence++;
914 }
Robert Carr6a160312021-05-17 12:08:20 -0700915 mDrawingState.blurRegions = blurRegions;
916 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -0700917 setTransactionFlags(eTransactionNeeded);
918 return true;
919}
920
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800921bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -0700922 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
923 if (mDrawingState.flags == newFlags) return false;
924 mDrawingState.sequence++;
925 mDrawingState.flags = newFlags;
926 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800927 setTransactionFlags(eTransactionNeeded);
928 return true;
929}
Robert Carr99e27f02016-06-16 15:18:02 -0700930
chaviw25714502021-02-11 10:01:08 -0800931bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +0000932 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -0700933 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -0700934 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -0700935
Robert Carr6a160312021-05-17 12:08:20 -0700936 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800937 setTransactionFlags(eTransactionNeeded);
938 return true;
939}
Robert Carr8d5227b2017-03-16 15:41:03 -0700940
Evan Roskyef876c92019-01-25 17:46:06 -0800941bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -0700942 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
943 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -0800944 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -0800945 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500946}
947
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700948bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -0700949 if (mDrawingState.layerStack == layerStack) return false;
950 mDrawingState.sequence++;
951 mDrawingState.layerStack = layerStack;
952 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800953 setTransactionFlags(eTransactionNeeded);
954 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700955}
956
Peiyong Linc502cb72019-03-01 15:00:23 -0800957bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -0700958 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -0800959 return false;
960 }
Robert Carr6a160312021-05-17 12:08:20 -0700961 mDrawingState.sequence++;
962 mDrawingState.colorSpaceAgnostic = agnostic;
963 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -0800964 setTransactionFlags(eTransactionNeeded);
965 return true;
966}
967
Sally Qi81d95e62022-03-21 19:41:33 -0700968bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
969 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
970
971 mDrawingState.sequence++;
972 mDrawingState.dimmingEnabled = dimmingEnabled;
973 mDrawingState.modified = true;
974 setTransactionFlags(eTransactionNeeded);
975 return true;
976}
977
Ana Krulecc84d09b2019-11-02 23:10:29 +0100978bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -0700979 if (mDrawingState.frameRateSelectionPriority == priority) return false;
980 mDrawingState.frameRateSelectionPriority = priority;
981 mDrawingState.sequence++;
982 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +0100983 setTransactionFlags(eTransactionNeeded);
984 return true;
985}
986
987int32_t Layer::getFrameRateSelectionPriority() const {
988 // Check if layer has priority set.
989 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
990 return mDrawingState.frameRateSelectionPriority;
991 }
992 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000993 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +0100994 if (parent != nullptr) {
995 return parent->getFrameRateSelectionPriority();
996 }
997
998 return Layer::PRIORITY_UNSET;
999}
1000
Andy Labrada096227e2022-06-15 16:58:11 +00001001bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1002 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1003 mDrawingState.defaultFrameRateCompatibility = compatibility;
1004 mDrawingState.modified = true;
1005 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1006 setTransactionFlags(eTransactionNeeded);
1007 return true;
1008}
1009
1010scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1011 return mDrawingState.defaultFrameRateCompatibility;
1012}
1013
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001014bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1015 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1016};
1017
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001018ui::LayerStack Layer::getLayerStack() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001019 if (const auto parent = mDrawingParent.promote()) {
1020 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001021 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001022 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001023}
1024
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001025bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001026 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001027 return false;
1028 }
1029
Robert Carr6a160312021-05-17 12:08:20 -07001030 mDrawingState.sequence++;
1031 mDrawingState.shadowRadius = shadowRadius;
1032 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001033 setTransactionFlags(eTransactionNeeded);
1034 return true;
1035}
1036
Vishnu Nair6213bd92020-05-08 17:42:25 -07001037bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001038 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001039 return false;
1040 }
1041
Robert Carr6a160312021-05-17 12:08:20 -07001042 mDrawingState.sequence++;
1043 mDrawingState.fixedTransformHint = fixedTransformHint;
1044 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001045 setTransactionFlags(eTransactionNeeded);
1046 return true;
1047}
1048
John Reckcdb4ed72021-02-04 13:39:33 -05001049bool Layer::setStretchEffect(const StretchEffect& effect) {
1050 StretchEffect temp = effect;
1051 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001052 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001053 return false;
1054 }
Robert Carr6a160312021-05-17 12:08:20 -07001055 mDrawingState.sequence++;
1056 mDrawingState.stretchEffect = temp;
1057 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001058 setTransactionFlags(eTransactionNeeded);
1059 return true;
1060}
1061
John Reckc00c6692021-02-16 11:37:33 -05001062StretchEffect Layer::getStretchEffect() const {
1063 if (mDrawingState.stretchEffect.hasEffect()) {
1064 return mDrawingState.stretchEffect;
1065 }
1066
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001067 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001068 if (parent != nullptr) {
1069 auto effect = parent->getStretchEffect();
1070 if (effect.hasEffect()) {
1071 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1072 return effect;
1073 }
1074 }
1075 return StretchEffect{};
1076}
1077
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001078bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1079 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001080 return false;
1081 }
1082 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001083 mBorderWidth = width;
1084 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001085 return true;
1086}
1087
1088bool Layer::isBorderEnabled() {
1089 return mBorderEnabled;
1090}
1091
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001092float Layer::getBorderWidth() {
1093 return mBorderWidth;
1094}
1095
1096const half4& Layer::getBorderColor() {
1097 return mBorderColor;
1098}
1099
Ady Abrahama850c182021-08-04 13:04:37 -07001100bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1101 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1102 const auto frameRate = [&] {
1103 if (mDrawingState.frameRate.rate.isValid() ||
1104 mDrawingState.frameRate.type == FrameRateCompatibility::NoVote) {
1105 return mDrawingState.frameRate;
1106 }
1107
1108 return parentFrameRate;
1109 }();
1110
1111 *transactionNeeded |= setFrameRateForLayerTree(frameRate);
1112
1113 // The frame rate is propagated to the children
1114 bool childrenHaveFrameRate = false;
1115 for (const sp<Layer>& child : mCurrentChildren) {
1116 childrenHaveFrameRate |=
1117 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1118 }
1119
1120 // If we don't have a valid frame rate, but the children do, we set this
1121 // layer as NoVote to allow the children to control the refresh rate
1122 if (!frameRate.rate.isValid() && frameRate.type != FrameRateCompatibility::NoVote &&
1123 childrenHaveFrameRate) {
1124 *transactionNeeded |=
Dominik Laskowski6eab42d2021-09-13 14:34:13 -07001125 setFrameRateForLayerTree(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001126 }
1127
1128 // We return whether this layer ot its children has a vote. We ignore ExactOrMultiple votes for
1129 // the same reason we are allowing touch boost for those layers. See
1130 // RefreshRateConfigs::getBestRefreshRate for more details.
1131 const auto layerVotedWithDefaultCompatibility =
1132 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Default;
1133 const auto layerVotedWithNoVote = frameRate.type == FrameRateCompatibility::NoVote;
1134 const auto layerVotedWithExactCompatibility =
1135 frameRate.rate.isValid() && frameRate.type == FrameRateCompatibility::Exact;
1136 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote ||
1137 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1138}
1139
Ady Abraham60e42ea2020-03-09 19:17:31 -07001140void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001141 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001142 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001143 while (auto parent = layer->getParent()) {
1144 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001145 }
Ady Abrahama850c182021-08-04 13:04:37 -07001146 return layer;
1147 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001148
Ady Abraham60e42ea2020-03-09 19:17:31 -07001149 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001150 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001151
Ady Abrahama850c182021-08-04 13:04:37 -07001152 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001153 if (transactionNeeded) {
1154 mFlinger->setTransactionFlags(eTraversalNeeded);
1155 }
1156}
1157
Ady Abraham71c437d2020-01-31 15:56:57 -08001158bool Layer::setFrameRate(FrameRate frameRate) {
Robert Carr6a160312021-05-17 12:08:20 -07001159 if (mDrawingState.frameRate == frameRate) {
Steven Thomas3172e202020-01-06 19:25:30 -08001160 return false;
1161 }
1162
Robert Carr6a160312021-05-17 12:08:20 -07001163 mDrawingState.sequence++;
1164 mDrawingState.frameRate = frameRate;
1165 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001166
1167 updateTreeHasFrameRateVote();
1168
Steven Thomas3172e202020-01-06 19:25:30 -08001169 setTransactionFlags(eTransactionNeeded);
1170 return true;
1171}
1172
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001173void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1174 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001175 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001176
1177 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1178 // there are two transactions with the same token, the first one without a buffer and the
1179 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1180 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001181 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1182 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001183 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001184 mDrawingState.bufferSurfaceFrameTX = it->second;
1185 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1186 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1187 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001188 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001189 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001190 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1191 }
1192}
1193
1194void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1195 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001196 mDrawingState.frameTimelineInfo = info;
1197 mDrawingState.postTime = postTime;
1198 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001199 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001200
Robert Carr6a160312021-05-17 12:08:20 -07001201 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001202 bufferSurfaceFrameTX != nullptr) {
1203 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1204 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1205 // being used for BufferSurfaceFrame, don't create a new one.
1206 return;
1207 }
1208 }
1209 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1210 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1211 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001212 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1213 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001214 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001215 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001216 } else {
1217 if (it->second->getPresentState() == PresentState::Presented) {
1218 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1219 // have been from previous vsync.
1220 it->second = createSurfaceFrameForTransaction(info, postTime);
1221 }
1222 }
1223}
1224
1225void Layer::addSurfaceFrameDroppedForBuffer(
1226 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001227 surfaceFrame->setDropTime(systemTime());
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001228 surfaceFrame->setPresentState(PresentState::Dropped);
1229 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1230}
1231
1232void Layer::addSurfaceFramePresentedForBuffer(
1233 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1234 nsecs_t currentLatchTime) {
1235 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1236 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1237 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1238 mLastLatchTime = currentLatchTime;
1239}
1240
1241std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1242 const FrameTimelineInfo& info, nsecs_t postTime) {
1243 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001244 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1245 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001246 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001247 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001248 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001249 // For Transactions, the post time is considered to be both queue and acquire fence time.
1250 surfaceFrame->setActualQueueTime(postTime);
1251 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001252 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1253 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001254 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001255 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001256 onSurfaceFrameCreated(surfaceFrame);
1257 return surfaceFrame;
1258}
1259
1260std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1261 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1262 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001263 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001264 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001265 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001266 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001267 // For buffers, acquire fence time will set during latch.
1268 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001269 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1270 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001271 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001272 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001273 onSurfaceFrameCreated(surfaceFrame);
1274 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001275}
1276
Ady Abrahama850c182021-08-04 13:04:37 -07001277bool Layer::setFrameRateForLayerTree(FrameRate frameRate) {
1278 if (mDrawingState.frameRateForLayerTree == frameRate) {
1279 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001280 }
1281
Ady Abrahama850c182021-08-04 13:04:37 -07001282 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001283
Ady Abrahama850c182021-08-04 13:04:37 -07001284 // TODO(b/195668952): we probably don't need to dirty visible regions here
1285 // or even store frameRateForLayerTree in mDrawingState
1286 mDrawingState.sequence++;
1287 mDrawingState.modified = true;
1288 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001289
Dominik Laskowski068173d2021-08-11 17:22:59 -07001290 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
1291 mFlinger->mScheduler->recordLayerHistory(this, systemTime(), LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001292
1293 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001294}
1295
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001296Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1297 return getDrawingState().frameRateForLayerTree;
1298}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001299
Robert Carr1f0a16a2016-10-24 16:27:39 -07001300bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001301 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001302 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001303 if (parent != nullptr && parent->isHiddenByPolicy()) {
1304 return true;
1305 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001306 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1307 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1308 if (zOrderRelativeOf != nullptr) {
1309 if (zOrderRelativeOf->isHiddenByPolicy()) {
1310 return true;
1311 }
1312 }
1313 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001314 if (CC_UNLIKELY(!isTransformValid())) {
1315 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1316 return true;
1317 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001318 return s.flags & layer_state_t::eLayerHidden;
1319}
1320
David Sodman41fdfc92017-11-06 16:09:56 -08001321uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001322 // TODO: should we do something special if mSecure is set?
1323 if (mProtectedByApp) {
1324 // need a hardware-protected path to external video sink
1325 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001326 }
Riley Andrews03414a12014-07-01 14:22:59 -07001327 if (mPotentialCursor) {
1328 usage |= GraphicBuffer::USAGE_CURSOR;
1329 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001330 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001331 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001332}
1333
Vishnu Nair71fcf912022-10-18 09:14:20 -07001334void Layer::skipReportingTransformHint() {
1335 mSkipReportingTransformHint = true;
1336}
1337
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001338void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1339 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1340 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001341 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001342
Vishnu Nair6213bd92020-05-08 17:42:25 -07001343 setTransformHint(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001344}
1345
Mathias Agopian13127d82013-03-05 17:47:11 -08001346// ----------------------------------------------------------------------------
1347// debugging
1348// ----------------------------------------------------------------------------
1349
Marissa Wall61c58622018-07-18 10:12:20 -07001350// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001351gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001352 using namespace std::string_literals;
1353
Huihong Luo05539a12022-02-23 10:29:40 -08001354 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001355 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001356 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001357 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001358 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001359 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001360
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001361 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001362 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001363 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001364 info.mX = ds.transform.tx();
1365 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001366 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001367 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001368 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001369 info.mFlags = ds.flags;
1370 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001371 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001372 info.mMatrix[0][0] = ds.transform[0][0];
1373 info.mMatrix[0][1] = ds.transform[0][1];
1374 info.mMatrix[1][0] = ds.transform[1][0];
1375 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001376 {
chaviwd62d3062019-09-04 14:48:02 -07001377 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001378 if (buffer != 0) {
1379 info.mActiveBufferWidth = buffer->getWidth();
1380 info.mActiveBufferHeight = buffer->getHeight();
1381 info.mActiveBufferStride = buffer->getStride();
1382 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001383 } else {
1384 info.mActiveBufferWidth = 0;
1385 info.mActiveBufferHeight = 0;
1386 info.mActiveBufferStride = 0;
1387 info.mActiveBufferFormat = 0;
1388 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001389 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001390 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001391 info.mIsOpaque = isOpaque(ds);
1392 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001393 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001394 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001395}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001396
Yiwei Zhang5434a782018-12-05 18:06:32 -08001397void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001398 result.append(kDumpTableRowLength, '-');
1399 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001400 result.append(" Layer name\n");
1401 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001402 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001403 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001404 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001405 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001406 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001407 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1408 result.append(kDumpTableRowLength, '-');
1409 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001410}
1411
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001412void Layer::miniDump(std::string& result, const DisplayDevice& display) const {
1413 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001414 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001415 return;
1416 }
1417
Yiwei Zhang5434a782018-12-05 18:06:32 -08001418 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001419 if (mName.length() > 77) {
1420 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001421 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001422 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001423 shortened.append(mName, mName.length() - 36);
1424 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001425 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001426 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001427 }
1428
Yiwei Zhang5434a782018-12-05 18:06:32 -08001429 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001430
Alec Mourib416efd2018-09-06 21:01:59 +00001431 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001432 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001433
Chia-I Wu1e043612018-03-01 09:45:09 -08001434 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001435 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001436 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001437 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001438 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001439 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001440 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001441 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1442 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001443 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001444 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001445 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001446 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001447 const auto frameRate = getFrameRateForLayerTree();
1448 if (frameRate.rate.isValid() || frameRate.type != FrameRateCompatibility::Default) {
1449 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.rate).c_str(),
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001450 ftl::enum_string(frameRate.type).c_str(),
1451 ftl::enum_string(frameRate.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001452 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001453 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001454 }
Dan Stozae22aec72016-08-01 13:20:59 -07001455
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001456 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1457 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1458
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001459 result.append(kDumpTableRowLength, '-');
1460 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001461}
Dan Stozae22aec72016-08-01 13:20:59 -07001462
Yiwei Zhang5434a782018-12-05 18:06:32 -08001463void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001464 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001465}
1466
Svetoslavd85084b2014-03-20 10:28:31 -07001467void Layer::clearFrameStats() {
1468 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001469}
1470
Jamie Gennis6547ff42013-07-16 20:12:42 -07001471void Layer::logFrameStats() {
1472 mFrameTracker.logAndResetStats(mName);
1473}
1474
Svetoslavd85084b2014-03-20 10:28:31 -07001475void Layer::getFrameStats(FrameStats* outStats) const {
1476 mFrameTracker.getStats(outStats);
1477}
1478
Vishnu Nair0f085c62019-08-30 08:49:12 -07001479void Layer::dumpCallingUidPid(std::string& result) const {
Vishnu Naircb8be502022-10-12 19:03:23 +00001480 StringAppendF(&result, "Layer %s (%s) ownerPid:%d ownerUid:%d\n", getName().c_str(), getType(),
1481 mOwnerPid, mOwnerUid);
Vishnu Nair0f085c62019-08-30 08:49:12 -07001482}
1483
Brian Anderson5ea5e592016-12-01 16:54:33 -08001484void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001485 const int32_t layerId = getSequence();
1486 mFlinger->mTimeStats->onDestroy(layerId);
1487 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001488}
1489
Chia-I Wu98f1c102017-05-30 14:54:08 -07001490size_t Layer::getChildrenCount() const {
1491 size_t count = 0;
1492 for (const sp<Layer>& child : mCurrentChildren) {
1493 count += 1 + child->getChildrenCount();
1494 }
1495 return count;
1496}
1497
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001498void Layer::setGameModeForTree(GameMode gameMode) {
1499 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001500 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1501 gameMode =
1502 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001503 }
1504 setGameMode(gameMode);
1505 for (const sp<Layer>& child : mCurrentChildren) {
1506 child->setGameModeForTree(gameMode);
1507 }
1508}
1509
Robert Carr1f0a16a2016-10-24 16:27:39 -07001510void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001511 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001512 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001513
Robert Carr1f0a16a2016-10-24 16:27:39 -07001514 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001515 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001516 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001517 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001518}
1519
1520ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001521 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001522 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001523
Robert Carr1323c952019-01-28 18:13:27 -08001524 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001525 const auto removeResult = mCurrentChildren.remove(layer);
1526
1527 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001528 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001529 layer->updateTreeHasFrameRateVote();
1530
1531 return removeResult;
1532}
1533
Robert Carr15eae092018-03-23 13:43:53 -07001534void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001535 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001536 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001537 const float parentShadowRadius =
1538 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001539 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001540 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001541 }
1542}
1543
chaviwf1961f72017-09-18 16:41:07 -07001544bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001545 sp<Layer> newParent;
1546 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001547 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001548 if (newParent == nullptr) {
1549 ALOGE("Unable to promote Layer handle");
1550 return false;
1551 }
1552 if (newParent == this) {
1553 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1554 return false;
1555 }
1556 }
1557
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001558 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001559 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001560 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001561 }
1562
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001563 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001564 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001565 if (!newParent->isRemovedFromCurrentState()) {
1566 addToCurrentState();
1567 } else {
1568 onRemovedFromCurrentState();
1569 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001570 } else {
1571 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001572 }
1573
chaviw06178942017-07-27 10:25:59 -07001574 return true;
1575}
1576
Peiyong Lind3788632018-09-18 16:01:31 -07001577bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001578 static const mat4 identityMatrix = mat4();
1579
Robert Carr6a160312021-05-17 12:08:20 -07001580 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001581 return false;
1582 }
Robert Carr6a160312021-05-17 12:08:20 -07001583 ++mDrawingState.sequence;
1584 mDrawingState.colorTransform = matrix;
1585 mDrawingState.hasColorTransform = matrix != identityMatrix;
1586 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001587 setTransactionFlags(eTransactionNeeded);
1588 return true;
1589}
1590
chaviwf66724d2018-11-28 16:35:21 -08001591mat4 Layer::getColorTransform() const {
1592 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001593 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001594 colorTransform = parent->getColorTransform() * colorTransform;
1595 }
1596 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001597}
1598
1599bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001600 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001601 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001602 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1603 }
1604 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001605}
1606
Chia-I Wu11481472018-05-04 10:43:19 -07001607bool Layer::isLegacyDataSpace() const {
1608 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001609 return !(getDataSpace() &
1610 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1611 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001612}
1613
Robert Carr1f0a16a2016-10-24 16:27:39 -07001614void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001615 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001616}
1617
Robert Carr6a160312021-05-17 12:08:20 -07001618int32_t Layer::getZ(LayerVector::StateSet) const {
1619 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001620}
1621
Robert Carr1c5481e2019-07-01 14:42:27 -07001622bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001623 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001624 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001625 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001626}
1627
David Sodman41fdfc92017-11-06 16:09:56 -08001628__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001629 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001630 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1631 "makeTraversalList received invalid stateSet");
1632 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1633 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001634 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001635
Robert Carr29abff82017-12-04 13:51:20 -08001636 if (state.zOrderRelatives.size() == 0) {
1637 *outSkipRelativeZUsers = true;
1638 return children;
1639 }
1640
chaviwfd462612018-05-31 16:11:27 -07001641 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001642 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001643 sp<Layer> strongRelative = weakRelative.promote();
1644 if (strongRelative != nullptr) {
1645 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001646 }
1647 }
1648
Dan Stoza412903f2017-04-27 13:42:17 -07001649 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001650 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001651 continue;
1652 }
Robert Carrdb66e622017-04-10 16:55:57 -07001653 traverse.add(child);
1654 }
1655
1656 return traverse;
1657}
1658
Robert Carr1f0a16a2016-10-24 16:27:39 -07001659/**
Robert Carrdb66e622017-04-10 16:55:57 -07001660 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001661 */
Dan Stoza412903f2017-04-27 13:42:17 -07001662void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001663 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1664 // produce a new list for traversing, including our relatives, and not including our children
1665 // who are relatives of another surface. In the case that there are no relative Z,
1666 // makeTraversalList returns our children directly to avoid significant overhead.
1667 // However in this case we need to take the responsibility for filtering children which
1668 // are relatives of another surface here.
1669 bool skipRelativeZUsers = false;
1670 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001671
Robert Carr1f0a16a2016-10-24 16:27:39 -07001672 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001673 for (; i < list.size(); i++) {
1674 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001675 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1676 continue;
1677 }
1678
chaviw301b1d82019-11-06 13:15:09 -08001679 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001680 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001681 }
Dan Stoza412903f2017-04-27 13:42:17 -07001682 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001683 }
Robert Carr29abff82017-12-04 13:51:20 -08001684
Dan Stoza412903f2017-04-27 13:42:17 -07001685 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001686 for (; i < list.size(); i++) {
1687 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001688
Robert Carr29abff82017-12-04 13:51:20 -08001689 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1690 continue;
1691 }
Dan Stoza412903f2017-04-27 13:42:17 -07001692 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001693 }
1694}
1695
1696/**
Robert Carrdb66e622017-04-10 16:55:57 -07001697 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001698 */
Dan Stoza412903f2017-04-27 13:42:17 -07001699void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1700 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001701 // See traverseInZOrder for documentation.
1702 bool skipRelativeZUsers = false;
1703 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001704
Robert Carr1f0a16a2016-10-24 16:27:39 -07001705 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001706 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001707 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001708
1709 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1710 continue;
1711 }
1712
chaviw301b1d82019-11-06 13:15:09 -08001713 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001714 break;
1715 }
Dan Stoza412903f2017-04-27 13:42:17 -07001716 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001717 }
Dan Stoza412903f2017-04-27 13:42:17 -07001718 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001719 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001720 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001721
1722 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1723 continue;
1724 }
1725
Dan Stoza412903f2017-04-27 13:42:17 -07001726 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001727 }
1728}
1729
Edgar Arriaga844fa672020-01-16 14:21:42 -08001730void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1731 visitor(this);
1732 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001733 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001734 for (const sp<Layer>& child : children) {
1735 child->traverse(state, visitor);
1736 }
1737}
1738
chaviw4b129c22018-04-09 16:19:43 -07001739LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1740 const std::vector<Layer*>& layersInTree) {
1741 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1742 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001743 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1744 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001745 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001746
chaviwfd462612018-05-31 16:11:27 -07001747 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001748 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1749 sp<Layer> strongRelative = weakRelative.promote();
1750 // Only add relative layers that are also descendents of the top most parent of the tree.
1751 // If a relative layer is not a descendent, then it should be ignored.
1752 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1753 traverse.add(strongRelative);
1754 }
1755 }
1756
1757 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001758 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001759 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1760 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1761 // the child here since it won't be added later as a relative.
1762 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1763 childState.zOrderRelativeOf.promote().get())) {
1764 continue;
1765 }
1766 traverse.add(child);
1767 }
1768
1769 return traverse;
1770}
1771
1772void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1773 LayerVector::StateSet stateSet,
1774 const LayerVector::Visitor& visitor) {
1775 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001776
1777 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001778 for (; i < list.size(); i++) {
1779 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001780 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001781 break;
1782 }
chaviw4b129c22018-04-09 16:19:43 -07001783 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001784 }
chaviw4b129c22018-04-09 16:19:43 -07001785
chaviwa76b2712017-09-20 12:02:26 -07001786 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001787 for (; i < list.size(); i++) {
1788 const auto& relative = list[i];
1789 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001790 }
1791}
1792
chaviw4b129c22018-04-09 16:19:43 -07001793std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1794 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1795 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1796
1797 std::vector<Layer*> layersInTree = {this};
1798 for (size_t i = 0; i < children.size(); i++) {
1799 const auto& child = children[i];
1800 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1801 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1802 }
1803
1804 return layersInTree;
1805}
1806
1807void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1808 const LayerVector::Visitor& visitor) {
1809 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1810 std::sort(layersInTree.begin(), layersInTree.end());
1811 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1812}
1813
Peiyong Linefefaac2018-08-17 12:27:51 -07001814ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001815 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001816}
1817
Garfield Tan2c1782c2022-02-16 15:25:05 -08001818bool Layer::isTransformValid() const {
1819 float transformDet = getTransform().det();
1820 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1821}
1822
chaviw13fdc492017-06-27 12:40:18 -07001823half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001824 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001825
chaviw13fdc492017-06-27 12:40:18 -07001826 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1827 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07001828}
Robert Carr6452f122017-03-21 10:41:29 -07001829
Vishnu Nair6213bd92020-05-08 17:42:25 -07001830ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07001831 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001832 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
1833 return fixedTransformHint;
1834 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001835 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07001836 if (!p) return fixedTransformHint;
1837 return p->getFixedTransformHint();
1838}
1839
chaviw13fdc492017-06-27 12:40:18 -07001840half4 Layer::getColor() const {
1841 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001842 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07001843}
Robert Carr6452f122017-03-21 10:41:29 -07001844
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001845int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00001846 if (getDrawingState().backgroundBlurRadius == 0) {
1847 return 0;
1848 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01001849
Vishnu Nair29810f72022-07-01 16:38:41 +00001850 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01001851 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1852 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001853}
1854
Galia Peychevae0acf382021-04-12 21:22:34 +02001855const std::vector<BlurRegion> Layer::getBlurRegions() const {
1856 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02001857 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02001858 for (auto& region : regionsCopy) {
1859 region.alpha = region.alpha * layerAlpha;
1860 }
1861 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001862}
1863
Vishnu Naire14c6b32022-08-06 04:20:15 +00001864RoundedCornerState Layer::getRoundedCornerState() const {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001865 // Get parent settings
1866 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001867 const auto& parent = mDrawingParent.promote();
1868 if (parent != nullptr) {
1869 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001870 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001871 ui::Transform t = getActiveTransform(getDrawingState());
1872 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001873 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001874 parentSettings.radius.x *= t.getScaleX();
1875 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001876 }
1877 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001878
1879 // Get layer settings
1880 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001881 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001882 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001883 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001884
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001885 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001886 // If the parent and the layer have rounded corner settings, use the parent settings if the
1887 // parent crop is entirely inside the layer crop.
1888 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
1889 if (parentSettings.cropRect.left > layerCropRect.left &&
1890 parentSettings.cropRect.top > layerCropRect.top &&
1891 parentSettings.cropRect.right < layerCropRect.right &&
1892 parentSettings.cropRect.bottom < layerCropRect.bottom) {
1893 return parentSettings;
1894 } else {
1895 return layerSettings;
1896 }
Vishnu Nairb1845592021-10-07 12:17:57 -07001897 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001898 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001899 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001900 return parentSettings;
1901 }
1902 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001903}
1904
Robert Carr88b85e12022-03-21 15:47:35 -07001905bool Layer::findInHierarchy(const sp<Layer>& l) {
1906 if (l == this) {
1907 return true;
1908 }
1909 for (auto& child : mDrawingChildren) {
1910 if (child->findInHierarchy(l)) {
1911 return true;
1912 }
1913 }
1914 return false;
1915}
1916
Robert Carr1f0a16a2016-10-24 16:27:39 -07001917void Layer::commitChildList() {
1918 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
1919 const auto& child = mCurrentChildren[i];
1920 child->commitChildList();
1921 }
1922 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07001923 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07001924 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
1925 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1926 if (zOrderRelativeOf == nullptr) return;
1927 if (findInHierarchy(zOrderRelativeOf)) {
1928 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
1929 zOrderRelativeOf->mName.c_str());
1930 ALOGE("Severing rel Z loop, potentially dangerous");
1931 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07001932 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07001933 }
1934 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001935}
1936
Vishnu Nair6fabeec2019-03-12 13:42:49 -07001937
chaviw3277faf2021-05-19 16:45:23 -05001938void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07001939 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00001940 mDrawingState.touchableRegionCrop =
1941 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07001942 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00001943 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07001944 setTransactionFlags(eTransactionNeeded);
1945}
1946
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08001947LayerProto* Layer::writeToProto(LayersProto& layersProto, uint32_t traceFlags) {
chaviw08f3cb22020-01-13 13:17:21 -08001948 LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08001949 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08001950 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
1951
Vishnu Nair00b90132021-11-05 14:03:40 -07001952 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001953 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
1954
Vishnu Nair60db8c02020-04-02 11:55:16 -07001955 // Only populate for the primary display.
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001956 if (const auto display = mFlinger->getDefaultDisplayDeviceLocked()) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -05001957 const auto compositionType = getCompositionType(*display);
Vishnu Nair60db8c02020-04-02 11:55:16 -07001958 layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08001959 LayerProtoHelper::writeToProto(getVisibleRegion(display.get()),
1960 [&]() { return layerProto->mutable_visible_region(); });
Vishnu Nair60db8c02020-04-02 11:55:16 -07001961 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08001962 }
1963
chaviw08f3cb22020-01-13 13:17:21 -08001964 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08001965 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08001966 }
chaviw6d89e2d2020-01-14 14:42:01 -08001967
1968 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08001969}
1970
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08001971void Layer::writeToProtoDrawingState(LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07001972 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08001973 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07001974 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08001975 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07001976 [&]() { return layerInfo->mutable_active_buffer(); });
1977 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
1978 layerInfo->mutable_buffer_transform());
1979 }
1980 layerInfo->set_invalidate(contentDirty);
1981 layerInfo->set_is_protected(isProtected());
1982 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
1983 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07001984 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07001985 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001986 layerInfo->set_corner_radius(
1987 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07001988 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
1989 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
1990 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
1991 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
1992 [&]() { return layerInfo->mutable_position(); });
1993 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07001994 LayerProtoHelper::writeToProto(surfaceDamageRegion,
1995 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07001996
Vishnu Nair00b90132021-11-05 14:03:40 -07001997 if (hasColorTransform()) {
1998 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07001999 }
2000
Vishnu Nair60db8c02020-04-02 11:55:16 -07002001 LayerProtoHelper::writeToProto(mSourceBounds,
2002 [&]() { return layerInfo->mutable_source_bounds(); });
2003 LayerProtoHelper::writeToProto(mScreenBounds,
2004 [&]() { return layerInfo->mutable_screen_bounds(); });
2005 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2006 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2007 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002008}
2009
2010void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
chaviw4c34a092020-07-08 11:30:06 -07002011 uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002012 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2013 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002014 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002015
chaviw766c9c52021-02-10 17:36:47 -08002016 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002017
Vishnu Nair00b90132021-11-05 14:03:40 -07002018 layerInfo->set_id(sequence);
2019 layerInfo->set_name(getName().c_str());
2020 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002021
Vishnu Nair00b90132021-11-05 14:03:40 -07002022 for (const auto& child : children) {
2023 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002024 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002025
Vishnu Nair00b90132021-11-05 14:03:40 -07002026 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2027 sp<Layer> strongRelative = weakRelative.promote();
2028 if (strongRelative != nullptr) {
2029 layerInfo->add_relatives(strongRelative->sequence);
2030 }
2031 }
2032
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002033 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002034 [&]() { return layerInfo->mutable_transparent_region(); });
2035
2036 layerInfo->set_layer_stack(getLayerStack().id);
2037 layerInfo->set_z(state.z);
2038
2039 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2040 return layerInfo->mutable_requested_position();
2041 });
2042
Vishnu Nair00b90132021-11-05 14:03:40 -07002043 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2044
2045 layerInfo->set_is_opaque(isOpaque(state));
2046
2047 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2048 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2049 LayerProtoHelper::writeToProto(state.color,
2050 [&]() { return layerInfo->mutable_requested_color(); });
2051 layerInfo->set_flags(state.flags);
2052
2053 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2054 layerInfo->mutable_requested_transform());
2055
2056 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2057 if (parent != nullptr) {
2058 layerInfo->set_parent(parent->sequence);
2059 } else {
2060 layerInfo->set_parent(-1);
2061 }
2062
2063 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2064 if (zOrderRelativeOf != nullptr) {
2065 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
2066 } else {
2067 layerInfo->set_z_order_relative_of(-1);
2068 }
2069
2070 layerInfo->set_is_relative_of(state.isRelativeOf);
2071
2072 layerInfo->set_owner_uid(mOwnerUid);
2073
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002074 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002075 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002076 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002077 info = fillInputInfo(
2078 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002079 } else {
2080 info = state.inputInfo;
2081 }
2082
2083 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002084 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002085 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002086
Vishnu Nair00b90132021-11-05 14:03:40 -07002087 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002088 auto protoMap = layerInfo->mutable_metadata();
2089 for (const auto& entry : state.metadata.mMap) {
2090 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2091 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002092 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002093
2094 LayerProtoHelper::writeToProto(state.destinationFrame,
2095 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002096}
2097
Robert Carr2e102c92018-10-23 12:11:15 -07002098bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002099 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002100}
2101
Prabir Pradhan33da9462022-06-14 14:55:57 +00002102// Applies the given transform to the region, while protecting against overflows caused by any
2103// offsets. If applying the offset in the transform to any of the Rects in the region would result
2104// in an overflow, they are not added to the output Region.
2105static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2106 const std::string& debugWindowName) {
2107 // Round the translation using the same rounding strategy used by ui::Transform.
2108 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2109 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2110
2111 ui::Transform transformWithoutOffset = t;
2112 transformWithoutOffset.set(0.f, 0.f);
2113
2114 const Region transformed = transformWithoutOffset.transform(r);
2115
2116 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2117 Region ret;
2118 for (const auto& rect : transformed) {
2119 Rect newRect;
2120 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2121 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2122 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2123 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2124 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2125 debugWindowName.c_str());
2126 continue;
2127 }
2128 ret.orSelf(newRect);
2129 }
2130 return ret;
2131}
2132
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002133void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
2134 Rect tmpBounds = getInputBounds();
2135 if (!tmpBounds.isValid()) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002136 info.touchableRegion.clear();
2137 // A layer could have invalid input bounds and still expect to receive touch input if it has
2138 // replaceTouchableRegionWithCrop. For that case, the input transform needs to be calculated
2139 // correctly to determine the coordinate space for input events. Use an empty rect so that
2140 // the layer will receive input in its own layer space.
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002141 tmpBounds = Rect::EMPTY_RECT;
chaviw7e72caf2020-12-02 16:50:43 -08002142 }
2143
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002144 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2145 // frame and transform used for the layer, which determines the bounds and the coordinate space
2146 // within which the layer will receive input.
2147 //
2148 // The coordinate space within which each of the bounds are specified is explicitly documented
2149 // in the variable name. For example "inputBoundsInLayer" is specified in layer space. A
2150 // Transform converts one coordinate space to another, which is apparent in its naming. For
2151 // example, "layerToDisplay" transforms layer space to display space.
2152 //
2153 // Coordinate space definitions:
2154 // - display: The display device's coordinate space. Correlates to pixels on the display.
2155 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2156 // - layer: The coordinate space of this layer.
2157 // - input: The coordinate space in which this layer will receive input events. This could be
2158 // different than layer space if a surfaceInset is used, which changes the origin
2159 // of the input space.
2160 const FloatRect inputBoundsInLayer = tmpBounds.toFloatRect();
chaviw7e72caf2020-12-02 16:50:43 -08002161
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002162 // Clamp surface inset to the input bounds.
2163 const auto surfaceInset = static_cast<float>(info.surfaceInset);
2164 const float xSurfaceInset =
2165 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getWidth() / 2.f));
2166 const float ySurfaceInset =
2167 std::max(0.f, std::min(surfaceInset, inputBoundsInLayer.getHeight() / 2.f));
chaviw1ff3d1e2020-07-01 15:53:47 -07002168
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002169 // Apply the insets to the input bounds.
2170 const FloatRect insetBoundsInLayer(inputBoundsInLayer.left + xSurfaceInset,
2171 inputBoundsInLayer.top + ySurfaceInset,
2172 inputBoundsInLayer.right - xSurfaceInset,
2173 inputBoundsInLayer.bottom - ySurfaceInset);
Ady Abraham282f1d72019-07-24 18:05:56 -07002174
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002175 // Crop the input bounds to ensure it is within the parent's bounds.
2176 const FloatRect croppedInsetBoundsInLayer = mBounds.intersect(insetBoundsInLayer);
Ady Abraham282f1d72019-07-24 18:05:56 -07002177
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002178 const ui::Transform layerToScreen = getInputTransform();
2179 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
Vishnu Nair8033a492018-12-05 07:27:23 -08002180
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002181 const Rect roundedFrameInDisplay{layerToDisplay.transform(croppedInsetBoundsInLayer)};
2182 info.frameLeft = roundedFrameInDisplay.left;
2183 info.frameTop = roundedFrameInDisplay.top;
2184 info.frameRight = roundedFrameInDisplay.right;
2185 info.frameBottom = roundedFrameInDisplay.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -07002186
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002187 ui::Transform inputToLayer;
2188 inputToLayer.set(insetBoundsInLayer.left, insetBoundsInLayer.top);
2189 const ui::Transform inputToDisplay = layerToDisplay * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002190
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002191 // InputDispatcher expects a display-to-input transform.
2192 info.transform = inputToDisplay.inverse();
2193
2194 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002195 info.touchableRegion =
2196 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002197}
2198
chaviw3277faf2021-05-19 16:45:23 -05002199void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002200 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002201 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002202 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002203 }
2204 if (p != nullptr) {
2205 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2206 }
2207}
2208
Vishnu Naira066d902021-09-13 18:40:17 -07002209gui::DropInputMode Layer::getDropInputMode() const {
2210 gui::DropInputMode mode = mDrawingState.dropInputMode;
2211 if (mode == gui::DropInputMode::ALL) {
2212 return mode;
2213 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002214 sp<Layer> parent = mDrawingParent.promote();
2215 if (parent) {
2216 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002217 if (parentMode != gui::DropInputMode::NONE) {
2218 return parentMode;
2219 }
2220 }
2221 return mode;
2222}
2223
2224void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002225 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002226 return;
2227 }
2228
2229 // Check if we need to drop input unconditionally
2230 gui::DropInputMode dropInputMode = getDropInputMode();
2231 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002232 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002233 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2234 return;
2235 }
2236
2237 // Check if we need to check if the window is obscured by parent
2238 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2239 return;
2240 }
2241
2242 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002243 sp<Layer> parent = mDrawingParent.promote();
2244 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002245 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002246 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2247 static_cast<float>(getAlpha()));
2248 }
2249
2250 // Check if the parent has cropped the buffer
2251 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2252 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002253 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002254 return;
2255 }
2256
2257 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2258 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2259 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2260 // match then the layer has not been cropped by its parents.
2261 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2262 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2263
2264 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002265 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002266 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2267 getDebugName());
2268 } else {
2269 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2270 // input if the window is obscured. This check should be done in surfaceflinger but the
2271 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2272 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002273 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002274 }
2275}
2276
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002277WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002278 if (!hasInputInfo()) {
2279 mDrawingState.inputInfo.name = getName();
2280 mDrawingState.inputInfo.ownerUid = mOwnerUid;
2281 mDrawingState.inputInfo.ownerPid = mOwnerPid;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002282 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002283 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002284 }
2285
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002286 const ui::Transform& displayTransform =
2287 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2288
chaviw3277faf2021-05-19 16:45:23 -05002289 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002290 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002291 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002292
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002293 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002294
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002295 if (displayArgs.transform == nullptr) {
2296 // Do not let the window receive touches if it is not associated with a valid display
2297 // transform. We still allow the window to receive keys and prevent ANRs.
2298 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2299 }
2300
Robert Carr5dc426e2020-06-10 14:29:14 -07002301 // For compatibility reasons we let layers which can receive input
2302 // receive input before they have actually submitted a buffer. Because
2303 // of this we use canReceiveInput instead of isVisible to check the
2304 // policy-visibility, ignoring the buffer state. However for layers with
2305 // hasInputInfo()==false we can use the real visibility state.
2306 // We are just using these layers for occlusion detection in
2307 // InputDispatcher, and obviously if they aren't visible they can't occlude
2308 // anything.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002309 const bool visible = hasInputInfo() ? canReceiveInput() : isVisible();
2310 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
2311
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002312 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002313 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002314 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002315
Vishnu Nair16a938f2021-09-24 07:14:54 -07002316 // If the window will be blacked out on a display because the display does not have the secure
2317 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002318 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002319 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002320 }
2321
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002322 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2323 if (info.replaceTouchableRegionWithCrop) {
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002324 const Rect bounds(cropLayer ? cropLayer->mScreenBounds : mScreenBounds);
2325 info.touchableRegion = Region(displayTransform.transform(bounds));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002326 } else if (cropLayer != nullptr) {
[1;3C2b9fc252021-02-04 16:16:50 -08002327 info.touchableRegion = info.touchableRegion.intersect(
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002328 displayTransform.transform(Rect{cropLayer->mScreenBounds}));
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002329 }
2330
Winson Chunga30f7c92021-06-29 15:42:56 -07002331 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2332 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002333 if (isTrustedOverlay()) {
2334 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2335 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002336
chaviwaf87b3e2019-10-01 16:59:28 -07002337 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2338 // touches from going outside the cloned area.
2339 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002340 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002341 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2342 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002343 info.touchableRegion = info.touchableRegion.intersect(rect);
2344 }
2345 }
2346
Robert Carr720e5062018-07-30 17:45:14 -07002347 return info;
2348}
2349
chaviwaf87b3e2019-10-01 16:59:28 -07002350sp<Layer> Layer::getClonedRoot() {
2351 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002352 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002353 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002354 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002355 return nullptr;
2356 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002357 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002358}
2359
Robert Carredd13602020-04-13 17:24:34 -07002360bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002361 return mDrawingState.inputInfo.token != nullptr ||
2362 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002363}
2364
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002365compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002366 const DisplayDevice* display) const {
2367 if (!display) return nullptr;
Lloyd Piquede196652020-01-22 17:29:58 -08002368 return display->getCompositionDisplay()->getOutputLayerForLayer(getCompositionEngineLayerFE());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002369}
2370
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002371Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2372 const auto outputLayer = findOutputLayerForDisplay(display);
2373 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002374}
2375
chaviwb4c6e582019-08-16 14:35:07 -07002376void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002377 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002378 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002379 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2380 mPotentialCursor = clonedFrom->mPotentialCursor;
2381 mProtectedByApp = clonedFrom->mProtectedByApp;
2382 updateCloneBufferInfo();
2383}
2384
2385void Layer::updateCloneBufferInfo() {
2386 if (!isClone() || !isClonedFromAlive()) {
2387 return;
2388 }
2389
2390 sp<Layer> clonedFrom = getClonedFrom();
2391 mBufferInfo = clonedFrom->mBufferInfo;
2392 mSidebandStream = clonedFrom->mSidebandStream;
2393 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2394 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2395 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2396
2397 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2398 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2399 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2400 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2401 // the cloned drawingState again.
2402 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2403 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2404 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2405 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2406
2407 cloneDrawingState(clonedFrom.get());
2408
2409 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2410 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2411 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2412 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002413}
chaviw74b03172019-08-19 11:09:03 -07002414
2415void Layer::updateMirrorInfo() {
2416 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2417 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2418 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2419 // that case, we want to delete the reference to the clone since we want it to get
2420 // destroyed. The root, this layer, will still be around since the client can continue
2421 // to hold a reference, but no cloned layers will be displayed.
2422 mClonedChild = nullptr;
2423 return;
2424 }
2425
2426 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2427 // If the real layer exists and is in current state, add the clone as a child of the root.
2428 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2429 // copied to drawingState for the root layer. So the clonedChild is always removed from
2430 // drawingState and then needs to be added back each traversal.
2431 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2432 addChildToDrawing(mClonedChild);
2433 }
2434
2435 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002436 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002437 mClonedChild->updateClonedRelatives(clonedLayersMap);
2438}
2439
2440void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2441 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2442 // to the clone. If the real layer is no longer alive, continue traversing the children
2443 // since we may be able to pull out other children that are still alive.
2444 if (isClonedFromAlive()) {
2445 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002446 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002447 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002448 }
2449
2450 // The clone layer may have children in drawingState since they may have been created and
2451 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2452 // that already exist, since we can just re-use them.
2453 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2454 // not updated in the regular traversal. They are skipped since the root will lose the
2455 // reference to them when it copies its currentChildren to drawing.
2456 for (sp<Layer>& child : mDrawingChildren) {
2457 child->updateClonedDrawingState(clonedLayersMap);
2458 }
2459}
2460
2461void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2462 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2463 mDrawingChildren.clear();
2464
2465 if (!isClonedFromAlive()) {
2466 return;
2467 }
2468
2469 sp<Layer> clonedFrom = getClonedFrom();
2470 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2471 if (child == mirrorRoot) {
2472 // This is to avoid cyclical mirroring.
2473 continue;
2474 }
2475 sp<Layer> clonedChild = clonedLayersMap[child];
2476 if (clonedChild == nullptr) {
2477 clonedChild = child->createClone();
2478 clonedLayersMap[child] = clonedChild;
2479 }
2480 addChildToDrawing(clonedChild);
2481 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2482 }
2483}
2484
chaviwaf87b3e2019-10-01 16:59:28 -07002485void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2486 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2487 if (cropLayer != nullptr) {
2488 if (clonedLayersMap.count(cropLayer) == 0) {
2489 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2490 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002491 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002492 } else {
2493 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2494 mDrawingState.touchableRegionCrop = clonedCropLayer;
2495 }
2496 }
2497 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2498 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002499 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002500}
2501
2502void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002503 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002504 mDrawingState.zOrderRelatives.clear();
2505
2506 if (!isClonedFromAlive()) {
2507 return;
2508 }
2509
chaviwaf87b3e2019-10-01 16:59:28 -07002510 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002511 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002512 const sp<Layer>& relative = relativeWeak.promote();
2513 if (clonedLayersMap.count(relative) > 0) {
2514 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002515 mDrawingState.zOrderRelatives.add(clonedRelative);
2516 }
2517 }
2518
2519 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2520 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2521 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2522 // still traverse the children, but the layer with the missing relativeOf will not be shown
2523 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002524 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2525 if (clonedLayersMap.count(relativeOf) > 0) {
2526 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002527 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2528 }
2529
chaviwaf87b3e2019-10-01 16:59:28 -07002530 updateClonedInputInfo(clonedLayersMap);
2531
chaviw74b03172019-08-19 11:09:03 -07002532 for (sp<Layer>& child : mDrawingChildren) {
2533 child->updateClonedRelatives(clonedLayersMap);
2534 }
2535}
2536
2537void Layer::addChildToDrawing(const sp<Layer>& layer) {
2538 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002539 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002540}
2541
Steven Thomas62a4cf82020-01-31 12:04:03 -08002542Layer::FrameRateCompatibility Layer::FrameRate::convertCompatibility(int8_t compatibility) {
2543 switch (compatibility) {
2544 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT:
2545 return FrameRateCompatibility::Default;
2546 case ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE:
2547 return FrameRateCompatibility::ExactOrMultiple;
Ady Abrahamdd5bfa92021-01-07 17:56:08 -08002548 case ANATIVEWINDOW_FRAME_RATE_EXACT:
2549 return FrameRateCompatibility::Exact;
Andy Labrada096227e2022-06-15 16:58:11 +00002550 case ANATIVEWINDOW_FRAME_RATE_MIN:
2551 return FrameRateCompatibility::Min;
Dominik Laskowski1f6fc702022-03-21 08:34:50 -07002552 case ANATIVEWINDOW_FRAME_RATE_NO_VOTE:
2553 return FrameRateCompatibility::NoVote;
Steven Thomas62a4cf82020-01-31 12:04:03 -08002554 default:
2555 LOG_ALWAYS_FATAL("Invalid frame rate compatibility value %d", compatibility);
2556 return FrameRateCompatibility::Default;
2557 }
2558}
2559
Marin Shalamanovc5986772021-03-16 16:09:49 +01002560scheduler::Seamlessness Layer::FrameRate::convertChangeFrameRateStrategy(int8_t strategy) {
2561 switch (strategy) {
2562 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS:
2563 return Seamlessness::OnlySeamless;
2564 case ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS:
2565 return Seamlessness::SeamedAndSeamless;
2566 default:
2567 LOG_ALWAYS_FATAL("Invalid change frame sate strategy value %d", strategy);
2568 return Seamlessness::Default;
2569 }
2570}
2571
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002572bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002573 const State& s(mDrawingState);
2574 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2575 return true;
2576 }
2577
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002578 sp<Layer> parent = mDrawingParent.promote();
2579 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002580}
2581
Robert Carr6a0382d2021-07-01 15:57:17 -07002582void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2583 mClonedChild = clonedChild;
2584 mHadClonedChild = true;
2585 mFlinger->mNumClones++;
2586}
2587
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002588bool Layer::setDropInputMode(gui::DropInputMode mode) {
2589 if (mDrawingState.dropInputMode == mode) {
2590 return false;
2591 }
2592 mDrawingState.dropInputMode = mode;
2593 return true;
2594}
2595
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002596void Layer::cloneDrawingState(const Layer* from) {
2597 mDrawingState = from->mDrawingState;
2598 // Skip callback info since they are not applicable for cloned layers.
2599 mDrawingState.releaseBufferListener = nullptr;
2600 mDrawingState.callbackHandles = {};
2601}
2602
Patrick Williamsbb25f802022-08-30 23:02:34 +00002603void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2604 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
2605 const sp<Fence>& releaseFence,
2606 uint32_t currentMaxAcquiredBufferCount) {
2607 if (!listener) {
2608 return;
2609 }
2610 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
2611 listener->onReleaseBuffer({buffer->getId(), framenumber},
2612 releaseFence ? releaseFence : Fence::NO_FENCE,
2613 currentMaxAcquiredBufferCount);
2614}
2615
2616void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
2617 // If we are displayed on multiple displays in a single composition cycle then we would
2618 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2619 // For example we can only use it if all the displays are client comp, and we need
2620 // to merge all the client comp fences. We could do this, but for now we just
2621 // disable the optimization when a layer is composed on multiple displays.
2622 if (mClearClientCompositionFenceOnLayerDisplayed) {
2623 mLastClientCompositionFence = nullptr;
2624 } else {
2625 mClearClientCompositionFenceOnLayerDisplayed = true;
2626 }
2627
2628 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2629 // buffer that was presented on this layer. The first transaction that came in this frame that
2630 // replaced the previous buffer on this layer needs this release fence, because the fence will
2631 // let the client know when that previous buffer is removed from the screen.
2632 //
2633 // Every other transaction on this layer does not need a release fence because no other
2634 // Transactions that were set on this layer this frame are going to have their preceding buffer
2635 // removed from the display this frame.
2636 //
2637 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2638 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2639 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2640 // the previous buffer will be released this frame. The third transaction also contains a
2641 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2642 // transaction will now no longer be presented so it is released immediately and the third
2643 // transaction doesn't need a previous release fence.
2644 sp<CallbackHandle> ch;
2645 for (auto& handle : mDrawingState.callbackHandles) {
2646 if (handle->releasePreviousBuffer &&
2647 mDrawingState.releaseBufferEndpoint == handle->listener) {
2648 ch = handle;
2649 break;
2650 }
2651 }
2652
2653 // Prevent tracing the same release multiple times.
2654 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2655 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2656 }
2657
2658 if (ch != nullptr) {
2659 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2660 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2661 ch->name = mName;
2662 }
2663}
2664
2665void Layer::onSurfaceFrameCreated(
2666 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Vishnu Nair22491b82022-10-18 14:59:14 -07002667 if (!hasBufferOrSidebandStreamInDrawing()) {
2668 return;
2669 }
2670
Patrick Williamsbb25f802022-08-30 23:02:34 +00002671 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2672 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2673 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2674 // leak.
2675 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2676 mName.c_str());
2677 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2678 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2679 mPendingJankClassifications.pop_front();
2680 }
2681 mPendingJankClassifications.emplace_back(surfaceFrame);
2682}
2683
2684void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2685 for (const auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair71fcf912022-10-18 09:14:20 -07002686 handle->transformHint = mSkipReportingTransformHint
2687 ? std::nullopt
2688 : std::make_optional<uint32_t>(mTransformHint);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002689 handle->dequeueReadyTime = dequeueReadyTime;
2690 handle->currentMaxAcquiredBufferCount =
2691 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2692 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2693 handle->previousReleaseCallbackId.framenumber);
2694 }
2695
2696 for (auto& handle : mDrawingState.callbackHandles) {
2697 if (handle->releasePreviousBuffer &&
2698 mDrawingState.releaseBufferEndpoint == handle->listener) {
2699 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2700 break;
2701 }
2702 }
2703
2704 std::vector<JankData> jankData;
2705 jankData.reserve(mPendingJankClassifications.size());
2706 while (!mPendingJankClassifications.empty() &&
2707 mPendingJankClassifications.front()->getJankType()) {
2708 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
2709 mPendingJankClassifications.front();
2710 mPendingJankClassifications.pop_front();
2711 jankData.emplace_back(
2712 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
2713 }
2714
2715 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2716 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002717 mDrawingState.callbackHandles = {};
2718}
2719
2720bool Layer::willPresentCurrentTransaction() const {
2721 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2722 return (getSidebandStreamChanged() || getAutoRefresh() ||
2723 (mDrawingState.modified &&
2724 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2725}
2726
2727bool Layer::setTransform(uint32_t transform) {
2728 if (mDrawingState.bufferTransform == transform) return false;
2729 mDrawingState.bufferTransform = transform;
2730 mDrawingState.modified = true;
2731 setTransactionFlags(eTransactionNeeded);
2732 return true;
2733}
2734
2735bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2736 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2737 mDrawingState.sequence++;
2738 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2739 mDrawingState.modified = true;
2740 setTransactionFlags(eTransactionNeeded);
2741 return true;
2742}
2743
2744bool Layer::setBufferCrop(const Rect& bufferCrop) {
2745 if (mDrawingState.bufferCrop == bufferCrop) return false;
2746
2747 mDrawingState.sequence++;
2748 mDrawingState.bufferCrop = bufferCrop;
2749
2750 mDrawingState.modified = true;
2751 setTransactionFlags(eTransactionNeeded);
2752 return true;
2753}
2754
2755bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2756 if (mDrawingState.destinationFrame == destinationFrame) return false;
2757
2758 mDrawingState.sequence++;
2759 mDrawingState.destinationFrame = destinationFrame;
2760
2761 mDrawingState.modified = true;
2762 setTransactionFlags(eTransactionNeeded);
2763 return true;
2764}
2765
2766// Translate destination frame into scale and position. If a destination frame is not set, use the
2767// provided scale and position
2768bool Layer::updateGeometry() {
2769 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2770 mDrawingState.destinationFrame.isEmpty()) {
2771 // If destination frame is not set, use the requested transform set via
2772 // Layer::setPosition and Layer::setMatrix.
2773 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2774 }
2775
2776 Rect destRect = mDrawingState.destinationFrame;
2777 int32_t destW = destRect.width();
2778 int32_t destH = destRect.height();
2779 if (destRect.left < 0) {
2780 destRect.left = 0;
2781 destRect.right = destW;
2782 }
2783 if (destRect.top < 0) {
2784 destRect.top = 0;
2785 destRect.bottom = destH;
2786 }
2787
2788 if (!mDrawingState.buffer) {
2789 ui::Transform t;
2790 t.set(destRect.left, destRect.top);
2791 return assignTransform(&mDrawingState.transform, t);
2792 }
2793
2794 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2795 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2796 // Undo any transformations on the buffer.
2797 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2798 std::swap(bufferWidth, bufferHeight);
2799 }
2800 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
2801 if (mDrawingState.transformToDisplayInverse) {
2802 if (invTransform & ui::Transform::ROT_90) {
2803 std::swap(bufferWidth, bufferHeight);
2804 }
2805 }
2806
2807 float sx = destW / static_cast<float>(bufferWidth);
2808 float sy = destH / static_cast<float>(bufferHeight);
2809 ui::Transform t;
2810 t.set(sx, 0, 0, sy);
2811 t.set(destRect.left, destRect.top);
2812 return assignTransform(&mDrawingState.transform, t);
2813}
2814
2815bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
2816 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
2817 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
2818 return false;
2819 }
2820
2821 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
2822
2823 mDrawingState.sequence++;
2824 mDrawingState.modified = true;
2825 setTransactionFlags(eTransactionNeeded);
2826
2827 return true;
2828}
2829
2830bool Layer::setPosition(float x, float y) {
2831 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
2832 return false;
2833 }
2834
2835 mRequestedTransform.set(x, y);
2836
2837 mDrawingState.sequence++;
2838 mDrawingState.modified = true;
2839 setTransactionFlags(eTransactionNeeded);
2840
2841 return true;
2842}
2843
2844bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
2845 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
2846 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
2847 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00002848 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00002849 if (!buffer) {
2850 return false;
2851 }
2852
2853 const bool frameNumberChanged =
2854 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
2855 const uint64_t frameNumber =
2856 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00002857 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002858
2859 if (mDrawingState.buffer) {
2860 mReleasePreviousBuffer = true;
2861 if (!mBufferInfo.mBuffer ||
2862 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
2863 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
2864 // If mDrawingState has a buffer, and we are about to update again
2865 // before swapping to drawing state, then the first buffer will be
2866 // dropped and we should decrement the pending buffer count and
2867 // call any release buffer callbacks if set.
2868 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
2869 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
2870 mDrawingState.acquireFence,
2871 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
2872 mOwnerUid));
2873 decrementPendingBufferCount();
2874 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
2875 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
2876 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
2877 mDrawingState.bufferSurfaceFrameTX.reset();
2878 }
2879 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
2880 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
2881 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
2882 mLastClientCompositionFence,
2883 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
2884 mOwnerUid));
2885 mLastClientCompositionFence = nullptr;
2886 }
2887 }
2888
2889 mDrawingState.frameNumber = frameNumber;
2890 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
2891 mDrawingState.buffer = std::move(buffer);
2892 mDrawingState.clientCacheId = bufferData.cachedBuffer;
2893
2894 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
2895 ? bufferData.acquireFence
2896 : Fence::NO_FENCE;
2897 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
2898 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
2899 // We latched this buffer unsiganled, so we need to pass the acquire fence
2900 // on the callback instead of just the acquire time, since it's unknown at
2901 // this point.
2902 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
2903 } else {
2904 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
2905 }
2906
2907 mDrawingState.modified = true;
2908 setTransactionFlags(eTransactionNeeded);
2909
2910 const int32_t layerId = getSequence();
2911 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
2912 mOwnerUid, postTime, getGameMode());
2913 mDrawingState.desiredPresentTime = desiredPresentTime;
2914 mDrawingState.isAutoTimestamp = isAutoTimestamp;
2915
2916 const nsecs_t presentTime = [&] {
2917 if (!isAutoTimestamp) return desiredPresentTime;
2918
2919 const auto prediction =
2920 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
2921 if (prediction.has_value()) return prediction->presentTime;
2922
2923 return static_cast<nsecs_t>(0);
2924 }();
2925
2926 using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
2927 mFlinger->mScheduler->recordLayerHistory(this, presentTime, LayerUpdateType::Buffer);
2928
2929 setFrameTimelineVsyncForBufferTransaction(info, postTime);
2930
2931 if (dequeueTime && *dequeueTime != 0) {
2932 const uint64_t bufferId = mDrawingState.buffer->getId();
2933 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
2934 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
2935 FrameTracer::FrameEvent::DEQUEUE);
2936 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
2937 FrameTracer::FrameEvent::QUEUE);
2938 }
2939
2940 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
2941 return true;
2942}
2943
2944bool Layer::setDataspace(ui::Dataspace dataspace) {
2945 mDrawingState.dataspaceRequested = true;
2946 if (mDrawingState.dataspace == dataspace) return false;
2947 mDrawingState.dataspace = dataspace;
2948 mDrawingState.modified = true;
2949 setTransactionFlags(eTransactionNeeded);
2950 return true;
2951}
2952
2953bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
2954 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
2955 mDrawingState.hdrMetadata = hdrMetadata;
2956 mDrawingState.modified = true;
2957 setTransactionFlags(eTransactionNeeded);
2958 return true;
2959}
2960
2961bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
2962 mDrawingState.surfaceDamageRegion = surfaceDamage;
2963 mDrawingState.modified = true;
2964 setTransactionFlags(eTransactionNeeded);
2965 return true;
2966}
2967
2968bool Layer::setApi(int32_t api) {
2969 if (mDrawingState.api == api) return false;
2970 mDrawingState.api = api;
2971 mDrawingState.modified = true;
2972 setTransactionFlags(eTransactionNeeded);
2973 return true;
2974}
2975
2976bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
2977 if (mDrawingState.sidebandStream == sidebandStream) return false;
2978
2979 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
2980 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
2981 } else if (sidebandStream != nullptr) {
2982 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
2983 }
2984
2985 mDrawingState.sidebandStream = sidebandStream;
2986 mDrawingState.modified = true;
2987 setTransactionFlags(eTransactionNeeded);
2988 if (!mSidebandStreamChanged.exchange(true)) {
2989 // mSidebandStreamChanged was false
2990 mFlinger->onLayerUpdate();
2991 }
2992 return true;
2993}
2994
2995bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles) {
2996 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
2997 if (handles.empty()) {
2998 mReleasePreviousBuffer = false;
2999 return false;
3000 }
3001
3002 const bool willPresent = willPresentCurrentTransaction();
3003
3004 for (const auto& handle : handles) {
3005 // If this transaction set a buffer on this layer, release its previous buffer
3006 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3007
3008 // If this layer will be presented in this frame
3009 if (willPresent) {
3010 // If this transaction set an acquire fence on this layer, set its acquire time
3011 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3012 handle->frameNumber = mDrawingState.frameNumber;
3013
3014 // Store so latched time and release fence can be set
3015 mDrawingState.callbackHandles.push_back(handle);
3016
3017 } else { // If this layer will NOT need to be relatched and presented this frame
3018 // Notify the transaction completed thread this handle is done
3019 mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
3020 }
3021 }
3022
3023 mReleasePreviousBuffer = false;
3024 mCallbackHandleAcquireTimeOrFence = -1;
3025
3026 return willPresent;
3027}
3028
3029Rect Layer::getBufferSize(const State& /*s*/) const {
3030 // for buffer state layers we use the display frame size as the buffer size.
3031
3032 if (mBufferInfo.mBuffer == nullptr) {
3033 return Rect::INVALID_RECT;
3034 }
3035
3036 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3037 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3038
3039 // Undo any transformations on the buffer and return the result.
3040 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3041 std::swap(bufWidth, bufHeight);
3042 }
3043
3044 if (getTransformToDisplayInverse()) {
3045 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3046 if (invTransform & ui::Transform::ROT_90) {
3047 std::swap(bufWidth, bufHeight);
3048 }
3049 }
3050
3051 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3052}
3053
3054FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3055 if (mBufferInfo.mBuffer == nullptr) {
3056 return parentBounds;
3057 }
3058
3059 return getBufferSize(getDrawingState()).toFloatRect();
3060}
3061
3062bool Layer::fenceHasSignaled() const {
3063 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3064 return true;
3065 }
3066
3067 const bool fenceSignaled =
3068 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3069 if (!fenceSignaled) {
3070 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3071 TimeStats::LatchSkipReason::LateAcquire);
3072 }
3073
3074 return fenceSignaled;
3075}
3076
Vishnu Naire14c6b32022-08-06 04:20:15 +00003077bool Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003078 for (const auto& handle : mDrawingState.callbackHandles) {
3079 handle->refreshStartTime = refreshStartTime;
3080 }
3081 return hasReadyFrame();
3082}
3083
3084void Layer::setAutoRefresh(bool autoRefresh) {
3085 mDrawingState.autoRefresh = autoRefresh;
3086}
3087
3088bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3089 // We need to update the sideband stream if the layer has both a buffer and a sideband stream.
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003090 auto* snapshot = editLayerSnapshot();
3091 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003092
3093 if (mSidebandStreamChanged.exchange(false)) {
3094 const State& s(getDrawingState());
3095 // mSidebandStreamChanged was true
3096 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003097 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003098 if (mSidebandStream != nullptr) {
3099 setTransactionFlags(eTransactionNeeded);
3100 mFlinger->setTransactionFlags(eTraversalNeeded);
3101 }
3102 recomputeVisibleRegions = true;
3103
3104 return true;
3105 }
3106 return false;
3107}
3108
3109bool Layer::hasFrameUpdate() const {
3110 const State& c(getDrawingState());
3111 return (mDrawingStateModified || mDrawingState.modified) &&
3112 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3113}
3114
3115void Layer::updateTexImage(nsecs_t latchTime) {
3116 const State& s(getDrawingState());
3117
3118 if (!s.buffer) {
3119 if (s.bgColorLayer) {
3120 for (auto& handle : mDrawingState.callbackHandles) {
3121 handle->latchTime = latchTime;
3122 }
3123 }
3124 return;
3125 }
3126
3127 for (auto& handle : mDrawingState.callbackHandles) {
3128 if (handle->frameNumber == mDrawingState.frameNumber) {
3129 handle->latchTime = latchTime;
3130 }
3131 }
3132
3133 const int32_t layerId = getSequence();
3134 const uint64_t bufferId = mDrawingState.buffer->getId();
3135 const uint64_t frameNumber = mDrawingState.frameNumber;
3136 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3137 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3138 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3139
3140 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3141 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3142 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3143 FrameTracer::FrameEvent::LATCH);
3144
3145 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3146 if (bufferSurfaceFrame != nullptr &&
3147 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3148 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3149 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3150 // are processing the next state.
3151 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3152 mDrawingState.acquireFenceTime->getSignalTime(),
3153 latchTime);
3154 mDrawingState.bufferSurfaceFrameTX.reset();
3155 }
3156
3157 std::deque<sp<CallbackHandle>> remainingHandles;
3158 mFlinger->getTransactionCallbackInvoker()
3159 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3160 mDrawingState.callbackHandles = remainingHandles;
3161
3162 mDrawingStateModified = false;
3163}
3164
3165void Layer::gatherBufferInfo() {
3166 if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
3167 decrementPendingBufferCount();
3168 }
3169
3170 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3171 mBufferInfo.mBuffer = mDrawingState.buffer;
3172 mBufferInfo.mFence = mDrawingState.acquireFence;
3173 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3174 mBufferInfo.mPixelFormat =
3175 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3176 mBufferInfo.mFrameLatencyNeeded = true;
3177 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3178 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3179 mBufferInfo.mFence = mDrawingState.acquireFence;
3180 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3181 auto lastDataspace = mBufferInfo.mDataspace;
3182 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
3183 if (lastDataspace != mBufferInfo.mDataspace) {
3184 mFlinger->mSomeDataspaceChanged = true;
3185 }
3186 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3187 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3188 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3189 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3190 mBufferInfo.mApi = mDrawingState.api;
3191 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
3192 mBufferInfo.mBufferSlot = mHwcSlotGenerator->getHwcCacheSlot(mDrawingState.clientCacheId);
3193}
3194
3195Rect Layer::computeBufferCrop(const State& s) {
3196 if (s.buffer && !s.bufferCrop.isEmpty()) {
3197 Rect bufferCrop;
3198 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3199 return bufferCrop;
3200 } else if (s.buffer) {
3201 return s.buffer->getBounds();
3202 } else {
3203 return s.bufferCrop;
3204 }
3205}
3206
3207sp<Layer> Layer::createClone() {
3208 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
3209 args.textureName = mTextureName;
Patrick Williams83f36b22022-09-14 17:57:35 +00003210 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003211 layer->mHwcSlotGenerator = mHwcSlotGenerator;
3212 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
3213 return layer;
3214}
3215
3216bool Layer::bufferNeedsFiltering() const {
3217 const State& s(getDrawingState());
3218 if (!s.buffer) {
3219 return false;
3220 }
3221
3222 int32_t bufferWidth = static_cast<int32_t>(s.buffer->getWidth());
3223 int32_t bufferHeight = static_cast<int32_t>(s.buffer->getHeight());
3224
3225 // Undo any transformations on the buffer and return the result.
3226 if (s.bufferTransform & ui::Transform::ROT_90) {
3227 std::swap(bufferWidth, bufferHeight);
3228 }
3229
3230 if (s.transformToDisplayInverse) {
3231 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
3232 if (invTransform & ui::Transform::ROT_90) {
3233 std::swap(bufferWidth, bufferHeight);
3234 }
3235 }
3236
3237 const Rect layerSize{getBounds()};
3238 int32_t layerWidth = layerSize.getWidth();
3239 int32_t layerHeight = layerSize.getHeight();
3240
3241 // Align the layer orientation with the buffer before comparism
3242 if (mTransformHint & ui::Transform::ROT_90) {
3243 std::swap(layerWidth, layerHeight);
3244 }
3245
3246 return layerWidth != bufferWidth || layerHeight != bufferHeight;
3247}
3248
3249void Layer::decrementPendingBufferCount() {
3250 int32_t pendingBuffers = --mPendingBufferTransactions;
3251 tracePendingBufferCount(pendingBuffers);
3252}
3253
3254void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3255 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3256}
3257
3258/*
3259 * We don't want to send the layer's transform to input, but rather the
3260 * parent's transform. This is because Layer's transform is
3261 * information about how the buffer is placed on screen. The parent's
3262 * transform makes more sense to send since it's information about how the
3263 * layer is placed on screen. This transform is used by input to determine
3264 * how to go from screen space back to window space.
3265 */
3266ui::Transform Layer::getInputTransform() const {
3267 if (!hasBufferOrSidebandStream()) {
3268 return getTransform();
3269 }
3270 sp<Layer> parent = mDrawingParent.promote();
3271 if (parent == nullptr) {
3272 return ui::Transform();
3273 }
3274
3275 return parent->getTransform();
3276}
3277
3278/**
3279 * Similar to getInputTransform, we need to update the bounds to include the transform.
3280 * This is because bounds don't include the buffer transform, where the input assumes
3281 * that's already included.
3282 */
3283Rect Layer::getInputBounds() const {
3284 if (!hasBufferOrSidebandStream()) {
3285 return getCroppedBufferSize(getDrawingState());
3286 }
3287
3288 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
3289 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
3290 return bufferBounds;
3291 }
3292 return mDrawingState.transform.transform(bufferBounds);
3293}
3294
3295bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
3296 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3297
3298 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3299 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3300 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3301 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3302 layer_state_t::eReparent;
3303
3304 const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
3305 layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
3306 layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
3307 layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
3308 layer_state_t::eInputInfoChanged;
3309
3310 if ((s.what & requiredFlags) != requiredFlags) {
3311 ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3312 (s.what | requiredFlags) & ~s.what);
3313 return false;
3314 }
3315
3316 if (s.what & deniedFlags) {
3317 ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
3318 return false;
3319 }
3320
3321 if (s.what & allowedFlags) {
3322 ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
3323 }
3324
3325 if (s.what & layer_state_t::ePositionChanged) {
3326 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
3327 ALOGV("%s: false [ePositionChanged changed]", __func__);
3328 return false;
3329 }
3330 }
3331
3332 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003333 if (mDrawingState.color.a != s.color.a) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003334 ALOGV("%s: false [eAlphaChanged changed]", __func__);
3335 return false;
3336 }
3337 }
3338
3339 if (s.what & layer_state_t::eColorTransformChanged) {
3340 if (mDrawingState.colorTransform != s.colorTransform) {
3341 ALOGV("%s: false [eColorTransformChanged changed]", __func__);
3342 return false;
3343 }
3344 }
3345
3346 if (s.what & layer_state_t::eBackgroundColorChanged) {
3347 if (mDrawingState.bgColorLayer || s.bgColorAlpha != 0) {
3348 ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
3349 return false;
3350 }
3351 }
3352
3353 if (s.what & layer_state_t::eMatrixChanged) {
3354 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3355 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3356 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3357 mRequestedTransform.dsdy() != s.matrix.dsdy) {
3358 ALOGV("%s: false [eMatrixChanged changed]", __func__);
3359 return false;
3360 }
3361 }
3362
3363 if (s.what & layer_state_t::eCornerRadiusChanged) {
3364 if (mDrawingState.cornerRadius != s.cornerRadius) {
3365 ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
3366 return false;
3367 }
3368 }
3369
3370 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3371 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
3372 ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
3373 return false;
3374 }
3375 }
3376
Vishnu Nairbbceb462022-10-10 04:52:13 +00003377 if (s.what & layer_state_t::eBufferTransformChanged) {
3378 if (mDrawingState.bufferTransform != s.bufferTransform) {
3379 ALOGV("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003380 return false;
3381 }
3382 }
3383
3384 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3385 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
3386 ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
3387 return false;
3388 }
3389 }
3390
3391 if (s.what & layer_state_t::eCropChanged) {
3392 if (mDrawingState.crop != s.crop) {
3393 ALOGV("%s: false [eCropChanged changed]", __func__);
3394 return false;
3395 }
3396 }
3397
3398 if (s.what & layer_state_t::eDataspaceChanged) {
3399 if (mDrawingState.dataspace != s.dataspace) {
3400 ALOGV("%s: false [eDataspaceChanged changed]", __func__);
3401 return false;
3402 }
3403 }
3404
3405 if (s.what & layer_state_t::eHdrMetadataChanged) {
3406 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
3407 ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
3408 return false;
3409 }
3410 }
3411
3412 if (s.what & layer_state_t::eSidebandStreamChanged) {
3413 if (mDrawingState.sidebandStream != s.sidebandStream) {
3414 ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
3415 return false;
3416 }
3417 }
3418
3419 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3420 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
3421 ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
3422 return false;
3423 }
3424 }
3425
3426 if (s.what & layer_state_t::eShadowRadiusChanged) {
3427 if (mDrawingState.shadowRadius != s.shadowRadius) {
3428 ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
3429 return false;
3430 }
3431 }
3432
3433 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3434 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
3435 ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
3436 return false;
3437 }
3438 }
3439
3440 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3441 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
3442 ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
3443 return false;
3444 }
3445 }
3446
3447 if (s.what & layer_state_t::eStretchChanged) {
3448 StretchEffect temp = s.stretchEffect;
3449 temp.sanitize();
3450 if (mDrawingState.stretchEffect != temp) {
3451 ALOGV("%s: false [eStretchChanged changed]", __func__);
3452 return false;
3453 }
3454 }
3455
3456 if (s.what & layer_state_t::eBufferCropChanged) {
3457 if (mDrawingState.bufferCrop != s.bufferCrop) {
3458 ALOGV("%s: false [eBufferCropChanged changed]", __func__);
3459 return false;
3460 }
3461 }
3462
3463 if (s.what & layer_state_t::eDestinationFrameChanged) {
3464 if (mDrawingState.destinationFrame != s.destinationFrame) {
3465 ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
3466 return false;
3467 }
3468 }
3469
3470 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3471 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
3472 ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
3473 return false;
3474 }
3475 }
3476
3477 ALOGV("%s: true", __func__);
3478 return true;
3479}
3480
3481bool Layer::isHdrY410() const {
3482 // pixel format is HDR Y410 masquerading as RGBA_1010102
3483 return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
3484 mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
3485 mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
3486}
3487
Vishnu Naire14c6b32022-08-06 04:20:15 +00003488sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003489 // There's no need to get a CE Layer if the layer isn't going to draw anything.
Vishnu Naire14c6b32022-08-06 04:20:15 +00003490 return hasSomethingToDraw() ? mLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003491}
3492
Vishnu Naire14c6b32022-08-06 04:20:15 +00003493const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003494 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003495}
3496
Vishnu Naire14c6b32022-08-06 04:20:15 +00003497LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003498 return mSnapshot.get();
3499}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003500
Patrick Williamsbb25f802022-08-30 23:02:34 +00003501const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003502 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003503}
3504
3505void Layer::useSurfaceDamage() {
3506 if (mFlinger->mForceFullDamage) {
3507 surfaceDamageRegion = Region::INVALID_REGION;
3508 } else {
3509 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3510 }
3511}
3512
3513void Layer::useEmptyDamage() {
3514 surfaceDamageRegion.clear();
3515}
3516
3517bool Layer::isOpaque(const Layer::State& s) const {
3518 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3519 // layer's opaque flag.
3520 if (!hasSomethingToDraw()) {
3521 return false;
3522 }
3523
3524 // if the layer has the opaque flag, then we're always opaque
3525 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3526 return true;
3527 }
3528
3529 // If the buffer has no alpha channel, then we are opaque
3530 if (hasBufferOrSidebandStream() && isOpaqueFormat(getPixelFormat())) {
3531 return true;
3532 }
3533
3534 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3535 return fillsColor() && getAlpha() == 1.0_hf;
3536}
3537
3538bool Layer::canReceiveInput() const {
3539 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3540}
3541
3542bool Layer::isVisible() const {
3543 if (!hasSomethingToDraw()) {
3544 return false;
3545 }
3546
3547 if (isHiddenByPolicy()) {
3548 return false;
3549 }
3550
3551 return getAlpha() > 0.0f || hasBlur();
3552}
3553
3554void Layer::onPostComposition(const DisplayDevice* display,
3555 const std::shared_ptr<FenceTime>& glDoneFence,
3556 const std::shared_ptr<FenceTime>& presentFence,
3557 const CompositorTiming& compositorTiming) {
3558 // mFrameLatencyNeeded is true when a new frame was latched for the
3559 // composition.
3560 if (!mBufferInfo.mFrameLatencyNeeded) return;
3561
3562 for (const auto& handle : mDrawingState.callbackHandles) {
3563 handle->gpuCompositionDoneFence = glDoneFence;
3564 handle->compositorTiming = compositorTiming;
3565 }
3566
3567 // Update mFrameTracker.
3568 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3569 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3570
3571 const int32_t layerId = getSequence();
3572 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3573
3574 const auto outputLayer = findOutputLayerForDisplay(display);
3575 if (outputLayer && outputLayer->requiresClientComposition()) {
3576 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3577 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3578 clientCompositionTimestamp,
3579 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3580 // Update the SurfaceFrames in the drawing state
3581 if (mDrawingState.bufferSurfaceFrameTX) {
3582 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3583 }
3584 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3585 surfaceFrame->setGpuComposition();
3586 }
3587 }
3588
3589 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3590 if (frameReadyFence->isValid()) {
3591 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3592 } else {
3593 // There was no fence for this frame, so assume that it was ready
3594 // to be presented at the desired present time.
3595 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3596 }
3597
3598 if (display) {
Dominik Laskowskif8734e02022-08-26 09:06:59 -07003599 const Fps refreshRate = display->refreshRateConfigs().getActiveModePtr()->getFps();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003600 const std::optional<Fps> renderRate =
3601 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3602
3603 const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
3604 const auto gameMode = getGameMode();
3605
3606 if (presentFence->isValid()) {
3607 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3608 refreshRate, renderRate, vote, gameMode);
3609 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3610 presentFence,
3611 FrameTracer::FrameEvent::PRESENT_FENCE);
3612 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3613 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3614 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003615 // The HWC doesn't support present fences, so use the present timestamp instead.
3616 const nsecs_t presentTimestamp =
3617 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3618
3619 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
3620 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
3621 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3622
Patrick Williamsbb25f802022-08-30 23:02:34 +00003623 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3624 refreshRate, renderRate, vote, gameMode);
3625 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3626 mCurrentFrameNumber, actualPresentTime,
3627 FrameTracer::FrameEvent::PRESENT_FENCE);
3628 mFrameTracker.setActualPresentTime(actualPresentTime);
3629 }
3630 }
3631
3632 mFrameTracker.advanceFrame();
3633 mBufferInfo.mFrameLatencyNeeded = false;
3634}
3635
3636bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
3637 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3638 getDrawingState().frameNumber);
3639
3640 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3641
3642 if (refreshRequired) {
3643 return refreshRequired;
3644 }
3645
3646 // If the head buffer's acquire fence hasn't signaled yet, return and
3647 // try again later
3648 if (!fenceHasSignaled()) {
3649 ATRACE_NAME("!fenceHasSignaled()");
3650 mFlinger->onLayerUpdate();
3651 return false;
3652 }
3653
3654 updateTexImage(latchTime);
3655 if (mDrawingState.buffer == nullptr) {
3656 return false;
3657 }
3658
3659 // Capture the old state of the layer for comparisons later
3660 BufferInfo oldBufferInfo = mBufferInfo;
3661 const bool oldOpacity = isOpaque(mDrawingState);
3662 mPreviousFrameNumber = mCurrentFrameNumber;
3663 mCurrentFrameNumber = mDrawingState.frameNumber;
3664 gatherBufferInfo();
3665
3666 if (oldBufferInfo.mBuffer == nullptr) {
3667 // the first time we receive a buffer, we need to trigger a
3668 // geometry invalidation.
3669 recomputeVisibleRegions = true;
3670 }
3671
3672 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3673 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3674 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3675 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3676 recomputeVisibleRegions = true;
3677 }
3678
3679 if (oldBufferInfo.mBuffer != nullptr) {
3680 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3681 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3682 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3683 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3684 recomputeVisibleRegions = true;
3685 }
3686 }
3687
3688 if (oldOpacity != isOpaque(mDrawingState)) {
3689 recomputeVisibleRegions = true;
3690 }
3691
3692 return true;
3693}
3694
3695bool Layer::hasReadyFrame() const {
3696 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
3697}
3698
3699bool Layer::isProtected() const {
3700 return (mBufferInfo.mBuffer != nullptr) &&
3701 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
3702}
3703
3704// As documented in libhardware header, formats in the range
3705// 0x100 - 0x1FF are specific to the HAL implementation, and
3706// are known to have no alpha channel
3707// TODO: move definition for device-specific range into
3708// hardware.h, instead of using hard-coded values here.
3709#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
3710
3711bool Layer::isOpaqueFormat(PixelFormat format) {
3712 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
3713 return true;
3714 }
3715 switch (format) {
3716 case PIXEL_FORMAT_RGBA_8888:
3717 case PIXEL_FORMAT_BGRA_8888:
3718 case PIXEL_FORMAT_RGBA_FP16:
3719 case PIXEL_FORMAT_RGBA_1010102:
3720 case PIXEL_FORMAT_R_8:
3721 return false;
3722 }
3723 // in all other case, we have no blending (also for unknown formats)
3724 return true;
3725}
3726
3727bool Layer::needsFiltering(const DisplayDevice* display) const {
3728 if (!hasBufferOrSidebandStream()) {
3729 return false;
3730 }
3731 const auto outputLayer = findOutputLayerForDisplay(display);
3732 if (outputLayer == nullptr) {
3733 return false;
3734 }
3735
3736 // We need filtering if the sourceCrop rectangle size does not match the
3737 // displayframe rectangle size (not a 1:1 render)
3738 const auto& compositionState = outputLayer->getState();
3739 const auto displayFrame = compositionState.displayFrame;
3740 const auto sourceCrop = compositionState.sourceCrop;
3741 return sourceCrop.getHeight() != displayFrame.getHeight() ||
3742 sourceCrop.getWidth() != displayFrame.getWidth();
3743}
3744
3745bool Layer::needsFilteringForScreenshots(const DisplayDevice* display,
3746 const ui::Transform& inverseParentTransform) const {
3747 if (!hasBufferOrSidebandStream()) {
3748 return false;
3749 }
3750 const auto outputLayer = findOutputLayerForDisplay(display);
3751 if (outputLayer == nullptr) {
3752 return false;
3753 }
3754
3755 // We need filtering if the sourceCrop rectangle size does not match the
3756 // viewport rectangle size (not a 1:1 render)
3757 const auto& compositionState = outputLayer->getState();
3758 const ui::Transform& displayTransform = display->getTransform();
3759 const ui::Transform inverseTransform = inverseParentTransform * displayTransform.inverse();
3760 // Undo the transformation of the displayFrame so that we're back into
3761 // layer-stack space.
3762 const Rect frame = inverseTransform.transform(compositionState.displayFrame);
3763 const FloatRect sourceCrop = compositionState.sourceCrop;
3764
3765 int32_t frameHeight = frame.getHeight();
3766 int32_t frameWidth = frame.getWidth();
3767 // If the display transform had a rotational component then undo the
3768 // rotation so that the orientation matches the source crop.
3769 if (displayTransform.getOrientation() & ui::Transform::ROT_90) {
3770 std::swap(frameHeight, frameWidth);
3771 }
3772 return sourceCrop.getHeight() != frameHeight || sourceCrop.getWidth() != frameWidth;
3773}
3774
3775void Layer::latchAndReleaseBuffer() {
3776 if (hasReadyFrame()) {
3777 bool ignored = false;
3778 latchBuffer(ignored, systemTime());
3779 }
3780 releasePendingBuffer(systemTime());
3781}
3782
3783PixelFormat Layer::getPixelFormat() const {
3784 return mBufferInfo.mPixelFormat;
3785}
3786
3787bool Layer::getTransformToDisplayInverse() const {
3788 return mBufferInfo.mTransformToDisplayInverse;
3789}
3790
3791Rect Layer::getBufferCrop() const {
3792 // this is the crop rectangle that applies to the buffer
3793 // itself (as opposed to the window)
3794 if (!mBufferInfo.mCrop.isEmpty()) {
3795 // if the buffer crop is defined, we use that
3796 return mBufferInfo.mCrop;
3797 } else if (mBufferInfo.mBuffer != nullptr) {
3798 // otherwise we use the whole buffer
3799 return mBufferInfo.mBuffer->getBounds();
3800 } else {
3801 // if we don't have a buffer yet, we use an empty/invalid crop
3802 return Rect();
3803 }
3804}
3805
3806uint32_t Layer::getBufferTransform() const {
3807 return mBufferInfo.mTransform;
3808}
3809
3810ui::Dataspace Layer::getDataSpace() const {
3811 return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
3812}
3813
3814ui::Dataspace Layer::getRequestedDataSpace() const {
3815 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
3816}
3817
3818ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
3819 ui::Dataspace updatedDataspace = dataspace;
3820 // translate legacy dataspaces to modern dataspaces
3821 switch (dataspace) {
3822 case ui::Dataspace::SRGB:
3823 updatedDataspace = ui::Dataspace::V0_SRGB;
3824 break;
3825 case ui::Dataspace::SRGB_LINEAR:
3826 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
3827 break;
3828 case ui::Dataspace::JFIF:
3829 updatedDataspace = ui::Dataspace::V0_JFIF;
3830 break;
3831 case ui::Dataspace::BT601_625:
3832 updatedDataspace = ui::Dataspace::V0_BT601_625;
3833 break;
3834 case ui::Dataspace::BT601_525:
3835 updatedDataspace = ui::Dataspace::V0_BT601_525;
3836 break;
3837 case ui::Dataspace::BT709:
3838 updatedDataspace = ui::Dataspace::V0_BT709;
3839 break;
3840 default:
3841 break;
3842 }
3843
3844 return updatedDataspace;
3845}
3846
3847sp<GraphicBuffer> Layer::getBuffer() const {
3848 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
3849}
3850
Patrick Williamsbb25f802022-08-30 23:02:34 +00003851void Layer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
3852 mTransformHint = getFixedTransformHint();
3853 if (mTransformHint == ui::Transform::ROT_INVALID) {
3854 mTransformHint = displayTransformHint;
3855 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07003856 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003857}
3858
3859const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
3860 return mBufferInfo.mBuffer;
3861}
3862
3863bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003864 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003865 return false;
3866 }
3867
3868 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00003869 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003870 mDrawingState.modified = true;
3871 setTransactionFlags(eTransactionNeeded);
3872 return true;
3873}
3874
3875bool Layer::fillsColor() const {
3876 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
3877 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
3878}
3879
3880bool Layer::hasBlur() const {
3881 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
3882}
3883
Vishnu Nairba354102022-08-01 00:14:18 +00003884void Layer::updateSnapshot(bool updateGeometry) {
3885 if (!getCompositionEngineLayerFE()) {
3886 return;
3887 }
3888
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003889 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00003890 if (updateGeometry) {
3891 prepareBasicGeometryCompositionState();
3892 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003893 snapshot->roundedCorner = getRoundedCornerState();
3894 snapshot->stretchEffect = getStretchEffect();
3895 snapshot->transformedBounds = mScreenBounds;
3896 if (mEffectiveShadowRadius > 0.f) {
3897 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
3898
3899 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
3900 // it if transparent regions are present. This may not be necessary since shadows are
3901 // typically cast by layers without transparent regions.
3902 snapshot->shadowSettings.boundaries = mBounds;
3903
3904 const float casterAlpha = snapshot->alpha;
3905 const bool casterIsOpaque =
3906 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
3907
3908 // If the casting layer is translucent, we need to fill in the shadow underneath the
3909 // layer. Otherwise the generated shadow will only be shown around the casting layer.
3910 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
3911 snapshot->shadowSettings.ambientColor *= casterAlpha;
3912 snapshot->shadowSettings.spotColor *= casterAlpha;
3913 }
3914 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00003915 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003916 snapshot->contentOpaque = isOpaque(mDrawingState);
3917 snapshot->isHdrY410 = isHdrY410();
3918 snapshot->bufferNeedsFiltering = bufferNeedsFiltering();
3919 sp<Layer> p = mDrawingParent.promote();
3920 if (p != nullptr) {
3921 snapshot->transform = p->getTransform();
3922 } else {
3923 snapshot->transform.reset();
3924 }
3925 snapshot->bufferSize = getBufferSize(mDrawingState);
3926 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00003927 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00003928 preparePerFrameCompositionState();
3929}
3930
Vishnu Naire14c6b32022-08-06 04:20:15 +00003931void Layer::updateChildrenSnapshots(bool updateGeometry) {
3932 for (const sp<Layer>& child : mDrawingChildren) {
3933 child->updateSnapshot(updateGeometry);
3934 child->updateChildrenSnapshots(updateGeometry);
3935 }
3936}
3937
Vishnu Nair0a4fb002022-08-08 02:40:42 +00003938void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
3939 mSnapshot->layerMetadata = parentMetadata;
3940 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
3941 for (const sp<Layer>& child : mDrawingChildren) {
3942 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
3943 }
3944}
3945
3946void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
3947 std::unordered_set<Layer*>& visited) {
3948 if (visited.find(this) != visited.end()) {
3949 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
3950 return;
3951 }
3952 visited.insert(this);
3953
3954 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
3955
3956 if (mDrawingState.zOrderRelatives.empty()) {
3957 return;
3958 }
3959 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
3960 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
3961 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
3962 sp<Layer> relative = weakRelative.promote();
3963 if (!relative) {
3964 continue;
3965 }
3966 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
3967 }
3968}
3969
Patrick Williams377c0142022-10-13 17:33:38 +00003970LayerSnapshotGuard::LayerSnapshotGuard(Layer* layer) : mLayer(layer) {
3971 if (mLayer) {
3972 mLayer->mLayerFE->mSnapshot = std::move(mLayer->mSnapshot);
3973 }
3974}
3975
3976LayerSnapshotGuard::~LayerSnapshotGuard() {
3977 if (mLayer) {
3978 mLayer->mSnapshot = std::move(mLayer->mLayerFE->mSnapshot);
3979 }
3980}
3981
3982LayerSnapshotGuard::LayerSnapshotGuard(LayerSnapshotGuard&& other) : mLayer(other.mLayer) {
3983 other.mLayer = nullptr;
3984}
3985
3986LayerSnapshotGuard& LayerSnapshotGuard::operator=(LayerSnapshotGuard&& other) {
3987 mLayer = other.mLayer;
3988 other.mLayer = nullptr;
3989 return *this;
3990}
3991
Mathias Agopian13127d82013-03-05 17:47:11 -08003992// ---------------------------------------------------------------------------
3993
Marin Shalamanov46084422020-10-13 12:33:42 +02003994std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07003995 return stream << "{rate=" << rate.rate << " type=" << ftl::enum_string(rate.type)
3996 << " seamlessness=" << ftl::enum_string(rate.seamlessness) << '}';
Marin Shalamanov46084422020-10-13 12:33:42 +02003997}
3998
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07003999} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004000
4001#if defined(__gl_h_)
4002#error "don't include gl/gl.h in this file"
4003#endif
4004
4005#if defined(__gl2_h_)
4006#error "don't include gl2/gl2.h in this file"
4007#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004008
4009// TODO(b/129481165): remove the #pragma below and fix conversion issues
4010#pragma clang diagnostic pop // ignored "-Wconversion"