blob: 2e312827f2a8ebb001bdf65b57e7f6847f7422ad [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
Melody Hsue4ef87f2024-03-26 23:54:45 +000018
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080019#pragma clang diagnostic push
20#pragma clang diagnostic ignored "-Wconversion"
21
Dan Stoza9e56aa02015-11-02 13:00:03 -080022//#define LOG_NDEBUG 0
23#undef LOG_TAG
24#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080025#define ATRACE_TAG ATRACE_TAG_GRAPHICS
26
[1;3C2b9fc252021-02-04 16:16:50 -080027#include <android-base/properties.h>
Yiwei Zhang5434a782018-12-05 18:06:32 -080028#include <android-base/stringprintf.h>
Vishnu Nair0f085c62019-08-30 08:49:12 -070029#include <binder/IPCThreadState.h>
Vishnu Nairbe0ad902024-06-27 23:38:43 +000030#include <common/trace.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000031#include <compositionengine/CompositionEngine.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080032#include <compositionengine/Display.h>
Lloyd Piquea83776c2019-01-29 18:42:32 -080033#include <compositionengine/LayerFECompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080034#include <compositionengine/OutputLayer.h>
35#include <compositionengine/impl/OutputLayerCompositionState.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070036#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070037#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070038#include <cutils/properties.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070039#include <ftl/enum.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080040#include <ftl/fake_guard.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080041#include <gui/BufferItem.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080042#include <gui/Surface.h>
Alec Mourie60041e2019-06-14 18:59:51 -070043#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070044#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080045#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070046#include <stdint.h>
47#include <stdlib.h>
48#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000049#include <system/graphics-base-v1.0.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080050#include <ui/DebugUtils.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000051#include <ui/FloatRect.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080052#include <ui/GraphicBuffer.h>
Sally Qif6918d42023-08-07 15:28:30 -070053#include <ui/HdrRenderTypeUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080054#include <ui/PixelFormat.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000055#include <ui/Rect.h>
56#include <ui/Transform.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>
61
Alec Mourie60041e2019-06-14 18:59:51 -070062#include <algorithm>
Vishnu Nair71fcf912022-10-18 09:14:20 -070063#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070064
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070065#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080066#include "DisplayHardware/HWComposer.h"
Matt Buckley34953232025-02-06 06:32:09 -080067#include "FrameTimeline/FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070068#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +000069#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000070#include "FrontEnd/LayerHandle.h"
Melody Hsue4ef87f2024-03-26 23:54:45 +000071#include "Layer.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080072#include "LayerProtoHelper.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080074#include "TimeStats/TimeStats.h"
Melody Hsue4ef87f2024-03-26 23:54:45 +000075#include "TransactionCallbackInvoker.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070076#include "TunnelModeEnabledReporter.h"
Alec Mouri9892aac2023-12-11 21:16:59 +000077#include "Utils/FenceUtils.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 {
Alec Mouri9892aac2023-12-11 21:16:59 +000083using namespace std::chrono_literals;
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010084namespace {
85constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000086
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000087const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000088
Patrick Williamsbb25f802022-08-30 23:02:34 +000089TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
90 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
91 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
92 const auto frameRateCompatibility = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -070093 switch (frameRate.vote.type) {
Patrick Williamsbb25f802022-08-30 23:02:34 +000094 case Layer::FrameRateCompatibility::Default:
95 return FrameRateCompatibility::Default;
96 case Layer::FrameRateCompatibility::ExactOrMultiple:
97 return FrameRateCompatibility::ExactOrMultiple;
98 default:
99 return FrameRateCompatibility::Undefined;
100 }
101 }();
102
103 const auto seamlessness = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700104 switch (frameRate.vote.seamlessness) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000105 case scheduler::Seamlessness::OnlySeamless:
106 return Seamlessness::ShouldBeSeamless;
107 case scheduler::Seamlessness::SeamedAndSeamless:
108 return Seamlessness::NotRequired;
109 default:
110 return Seamlessness::Undefined;
111 }
112 }();
113
Rachel Leece6e0042023-06-27 11:22:54 -0700114 return TimeStats::SetFrameRateVote{.frameRate = frameRate.vote.rate.getValue(),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000115 .frameRateCompatibility = frameRateCompatibility,
116 .seamlessness = seamlessness};
117}
118
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100119} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800120
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700121using namespace ftl::flag_operators;
122
Yiwei Zhang5434a782018-12-05 18:06:32 -0800123using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000124using frontend::LayerSnapshot;
125using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800126using gui::GameMode;
127using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500128using gui::WindowInfo;
Vishnu Nair494a2e42023-11-10 17:21:19 -0800129using ui::Size;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800130
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700131using PresentState = frametimeline::SurfaceFrame::PresentState;
132
Kean Mariotti4ba343c2023-04-19 13:31:02 +0000133Layer::Layer(const surfaceflinger::LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000134 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700135 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000136 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800137 mWindowType(static_cast<WindowInfo::Type>(
Vishnu Nairdc83d4b2024-08-15 16:29:20 +0000138 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000139 ALOGV("Creating Layer %s", getDebugName());
140
Vishnu Naira9123c82024-10-03 03:56:44 +0000141 mDrawingState.crop = {0, 0, -1, -1};
Robert Carr6a160312021-05-17 12:08:20 -0700142 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700143 mDrawingState.transform.set(0, 0);
144 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +0000145 mDrawingState.previousFrameNumber = 0;
Vishnu Nair63221212023-04-06 15:17:37 -0700146 mDrawingState.barrierFrameNumber = 0;
147 mDrawingState.producerId = 0;
148 mDrawingState.barrierProducerId = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700149 mDrawingState.bufferTransform = 0;
150 mDrawingState.transformToDisplayInverse = false;
Robert Carr6a160312021-05-17 12:08:20 -0700151 mDrawingState.acquireFence = sp<Fence>::make(-1);
152 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
Alec Mouri74c7ae12023-03-26 02:57:47 +0000153 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Robert Carr6a160312021-05-17 12:08:20 -0700154 mDrawingState.metadata = args.metadata;
Robert Carr6a160312021-05-17 12:08:20 -0700155 mDrawingState.frameTimelineInfo = {};
156 mDrawingState.postTime = -1;
Ben Widawskyebdbead2024-10-24 11:47:50 -0700157 mDeprecatedFrameTracker.setDisplayRefreshPeriod(
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500158 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700159
Vishnu Naircb8be502022-10-12 19:03:23 +0000160 mOwnerUid = args.ownerUid;
161 mOwnerPid = args.ownerPid;
Tony Huangf3621102023-09-04 17:14:22 +0800162 mOwnerAppId = mOwnerUid % PER_USER_RANGE;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000163
Patrick Williamsbb25f802022-08-30 23:02:34 +0000164 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
Vishnu Nairdc83d4b2024-08-15 16:29:20 +0000165 mLayerFEs.emplace_back(frontend::LayerHierarchy::TraversalPath{static_cast<uint32_t>(sequence)},
166 args.flinger->getFactory().createLayerFE(mName, this));
Dominik Laskowski75848362019-11-11 17:57:20 -0800167}
168
169void Layer::onFirstRef() {
170 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700171}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700172
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700173Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000174 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
175 "Layer destructor called off the main thread.");
176
Patrick Williamsbb25f802022-08-30 23:02:34 +0000177 if (mBufferInfo.mBuffer != nullptr) {
178 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
179 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800180 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000181 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000182 const int32_t layerId = getSequence();
183 mFlinger->mTimeStats->onDestroy(layerId);
184 mFlinger->mFrameTracer->onDestroy(layerId);
185
chaviw74d90ad2019-04-26 14:45:26 -0700186 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700187
Alec Mourid05a7452024-09-20 13:44:02 +0000188 const auto currentTime = std::chrono::steady_clock::now();
189 if (mBufferInfo.mTimeSinceDataspaceUpdate > std::chrono::steady_clock::time_point::min()) {
190 mFlinger->mLayerEvents.emplace_back(mOwnerUid, getSequence(), mBufferInfo.mDataspace,
191 std::chrono::duration_cast<std::chrono::milliseconds>(
192 currentTime -
193 mBufferInfo.mTimeSinceDataspaceUpdate));
194 }
195
Robert Carr3e2a2992021-06-11 13:42:55 -0700196 if (mDrawingState.sidebandStream != nullptr) {
197 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
198 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000199 if (hasTrustedPresentationListener()) {
200 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000201 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000202 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700203}
204
Mathias Agopian13127d82013-03-05 17:47:11 -0800205// ---------------------------------------------------------------------------
Mathias Agopian13127d82013-03-05 17:47:11 -0800206// set-up
207// ---------------------------------------------------------------------------
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700208sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800209 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700210 if (mGetHandleCalled) {
211 ALOGE("Get handle called twice" );
212 return nullptr;
213 }
214 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700215 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000216 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800217}
218
219// ---------------------------------------------------------------------------
220// h/w composer set-up
221// ---------------------------------------------------------------------------
222
Chavi Weingarten076acac2023-01-19 17:20:43 +0000223// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000224void Layer::updateTrustedPresentationState(const DisplayDevice* display,
225 const frontend::LayerSnapshot* snapshot,
226 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000227 if (!hasTrustedPresentationListener()) {
228 return;
229 }
230 const bool lastState = mLastComputedTrustedPresentationState;
231 mLastComputedTrustedPresentationState = false;
232
233 if (!leaveState) {
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000234 const auto outputLayer = findOutputLayerForDisplay(display, snapshot->path);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000235 if (outputLayer != nullptr) {
236 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
237 Region coveredRegion =
238 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
239 mLastComputedTrustedPresentationState =
240 computeTrustedPresentationState(snapshot->geomLayerBounds,
241 snapshot->sourceBounds(), coveredRegion,
242 snapshot->transformedBounds,
243 snapshot->alpha,
244 snapshot->geomLayerTransform,
245 mTrustedPresentationThresholds);
246 } else {
247 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
248 "TrustedPresentationState",
249 getDebugName());
250 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000251 }
252 }
253 const bool newState = mLastComputedTrustedPresentationState;
254 if (lastState && !newState) {
255 // We were in the trusted presentation state, but now we left it,
256 // emit the callback if needed
257 if (mLastReportedTrustedPresentationState) {
258 mLastReportedTrustedPresentationState = false;
259 mTrustedPresentationListener.invoke(false);
260 }
261 // Reset the timer
262 mEnteredTrustedPresentationStateTime = -1;
263 } else if (!lastState && newState) {
264 // We were not in the trusted presentation state, but we entered it, begin the timer
265 // and make sure this gets called at least once more!
266 mEnteredTrustedPresentationStateTime = time_in_ms;
267 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
268 }
269
270 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
271 if (!mLastReportedTrustedPresentationState && newState &&
272 (time_in_ms - mEnteredTrustedPresentationStateTime >
273 mTrustedPresentationThresholds.stabilityRequirementMs)) {
274 mLastReportedTrustedPresentationState = true;
275 mTrustedPresentationListener.invoke(true);
276 }
277}
278
279/**
280 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
281 * of how the parameters and thresholds are interpreted. The general spirit is
282 * to produce an upper bound on the amount of the buffer which was presented.
283 */
284bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
285 const Region& coveredRegion,
286 const FloatRect& screenBounds, float alpha,
287 const ui::Transform& effectiveTransform,
288 const TrustedPresentationThresholds& thresholds) {
289 if (alpha < thresholds.minAlpha) {
290 return false;
291 }
292 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
293 return false;
294 }
295 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
296 return false;
297 }
298
299 const float sx = effectiveTransform.dsdx();
300 const float sy = effectiveTransform.dsdy();
301 float fractionRendered = std::min(sx * sy, 1.0f);
302
303 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
304 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
305 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
306
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000307 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
308 // Compute the size of all the rects since they may be disconnected.
309 float coveredSize = 0;
310 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
311 float size = rect->width() * rect->height();
312 coveredSize += size;
313 }
314
315 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000316
317 if (fractionRendered < thresholds.minFractionRendered) {
318 return false;
319 }
320
321 return true;
322}
323
Vishnu Nair60356342018-11-13 13:00:45 -0800324Rect Layer::getCroppedBufferSize(const State& s) const {
325 Rect size = getBufferSize(s);
Vishnu Naira9123c82024-10-03 03:56:44 +0000326 Rect crop = Rect(getCrop(s));
Vishnu Nair60356342018-11-13 13:00:45 -0800327 if (!crop.isEmpty() && size.isValid()) {
328 size.intersect(crop, &size);
329 } else if (!crop.isEmpty()) {
330 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700331 }
Vishnu Nair60356342018-11-13 13:00:45 -0800332 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800333}
334
Lloyd Piquea83776c2019-01-29 18:42:32 -0800335const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700336 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800337}
338
Mathias Agopian13127d82013-03-05 17:47:11 -0800339// ---------------------------------------------------------------------------
340// drawing...
341// ---------------------------------------------------------------------------
342
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500343aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
344 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700345 const auto outputLayer = findOutputLayerForDisplay(&display);
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000346 return getCompositionType(outputLayer);
347}
348
349aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
350 const compositionengine::OutputLayer* outputLayer) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -0800351 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500352 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800353 }
354 if (outputLayer->getState().hwc) {
355 return (*outputLayer->getState().hwc).hwcCompositionType;
356 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500357 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800358 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800359}
360
Mathias Agopian13127d82013-03-05 17:47:11 -0800361// ----------------------------------------------------------------------------
Mathias Agopian13127d82013-03-05 17:47:11 -0800362// transaction
363// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800364
Ben Widawsky67346b92025-02-11 08:44:31 -0800365void Layer::commitTransaction() REQUIRES(mFlinger->mStateLock) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000366 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
367 // bufferSurfaceFrameTX will be presented in latchBuffer.
368 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
369 if (surfaceFrame->getPresentState() != PresentState::Presented) {
370 // With applyPendingStates, we could end up having presented surfaceframes from previous
371 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800372 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000373 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
374 }
375 }
Robert Carr6a160312021-05-17 12:08:20 -0700376 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700377}
378
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700379void Layer::setTransactionFlags(uint32_t mask) {
380 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800381}
382
Vishnu Naira9123c82024-10-03 03:56:44 +0000383bool Layer::setCrop(const FloatRect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +0000384 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -0700385 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -0700386 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -0700387
Sally Qi81d95e62022-03-21 19:41:33 -0700388 setTransactionFlags(eTransactionNeeded);
389 return true;
390}
391
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700392bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
393 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
394};
395
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000396void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
Ben Widawsky67346b92025-02-11 08:44:31 -0800397 nsecs_t postTime, gui::GameMode gameMode)
398 REQUIRES(mFlinger->mStateLock) {
Robert Carr6a160312021-05-17 12:08:20 -0700399 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000400
401 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
402 // there are two transactions with the same token, the first one without a buffer and the
403 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
404 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -0700405 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
406 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000407 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -0700408 mDrawingState.bufferSurfaceFrameTX = it->second;
409 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
410 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
411 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000412 } else {
Robert Carr6a160312021-05-17 12:08:20 -0700413 mDrawingState.bufferSurfaceFrameTX =
Vishnu Nair39a74a92024-07-29 19:01:50 +0000414 createSurfaceFrameForBuffer(info, postTime, mTransactionName, gameMode);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000415 }
Ady Abraham5a3e3562023-06-07 10:32:08 -0700416
Vishnu Nair39a74a92024-07-29 19:01:50 +0000417 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName, gameMode);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000418}
419
420void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
Vishnu Nair39a74a92024-07-29 19:01:50 +0000421 nsecs_t postTime,
422 gui::GameMode gameMode) {
Robert Carr6a160312021-05-17 12:08:20 -0700423 mDrawingState.frameTimelineInfo = info;
424 mDrawingState.postTime = postTime;
Ady Abraham22c7b5c2020-09-22 19:33:40 -0700425 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000426
Robert Carr6a160312021-05-17 12:08:20 -0700427 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000428 bufferSurfaceFrameTX != nullptr) {
429 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
430 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
431 // being used for BufferSurfaceFrame, don't create a new one.
432 return;
433 }
434 }
435 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
436 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
437 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -0700438 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
439 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Vishnu Nair39a74a92024-07-29 19:01:50 +0000440 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime, gameMode);
Robert Carr6a160312021-05-17 12:08:20 -0700441 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000442 } else {
443 if (it->second->getPresentState() == PresentState::Presented) {
444 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
445 // have been from previous vsync.
Vishnu Nair39a74a92024-07-29 19:01:50 +0000446 it->second = createSurfaceFrameForTransaction(info, postTime, gameMode);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000447 }
448 }
Ady Abraham5a3e3562023-06-07 10:32:08 -0700449
Vishnu Nair39a74a92024-07-29 19:01:50 +0000450 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName, gameMode);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000451}
452
453void Layer::addSurfaceFrameDroppedForBuffer(
Ady Abraham5a3e3562023-06-07 10:32:08 -0700454 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t dropTime) {
455 surfaceFrame->setDropTime(dropTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000456 surfaceFrame->setPresentState(PresentState::Dropped);
457 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
458}
459
460void Layer::addSurfaceFramePresentedForBuffer(
461 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
Ben Widawsky67346b92025-02-11 08:44:31 -0800462 nsecs_t currentLatchTime) REQUIRES(mFlinger->mStateLock) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000463 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
464 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
465 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +0000466 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000467}
468
469std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
Ben Widawsky67346b92025-02-11 08:44:31 -0800470 const FrameTimelineInfo& info, nsecs_t postTime, gui::GameMode gameMode)
471 REQUIRES(mFlinger->mStateLock) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000472 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -0800473 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
474 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000475 mTransactionName,
Vishnu Nair39a74a92024-07-29 19:01:50 +0000476 /*isBuffer*/ false, gameMode);
Ben Widawskyebdbead2024-10-24 11:47:50 -0700477 // Buffer hasn't yet been latched, so use mDrawingState
478 surfaceFrame->setDesiredPresentTime(mDrawingState.desiredPresentTime);
479
Rachel Leeed511ef2021-10-11 15:09:51 -0700480 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000481 // For Transactions, the post time is considered to be both queue and acquire fence time.
482 surfaceFrame->setActualQueueTime(postTime);
483 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800484 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
485 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -0800486 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800487 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000488 return surfaceFrame;
489}
490
491std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
Vishnu Nair39a74a92024-07-29 19:01:50 +0000492 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName,
Ben Widawsky67346b92025-02-11 08:44:31 -0800493 gui::GameMode gameMode) REQUIRES(mFlinger->mStateLock) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000494 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -0800495 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000496 getSequence(), mName, debugName,
Vishnu Nair39a74a92024-07-29 19:01:50 +0000497 /*isBuffer*/ true, gameMode);
Ben Widawskyebdbead2024-10-24 11:47:50 -0700498 // Buffer hasn't yet been latched, so use mDrawingState
499 surfaceFrame->setDesiredPresentTime(mDrawingState.desiredPresentTime);
Rachel Leeed511ef2021-10-11 15:09:51 -0700500 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000501 // For buffers, acquire fence time will set during latch.
502 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800503 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
504 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -0800505 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800506 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000507 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -0700508}
509
Ady Abraham5a3e3562023-06-07 10:32:08 -0700510void Layer::setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
Ben Widawsky67346b92025-02-11 08:44:31 -0800511 std::string debugName, gui::GameMode gameMode)
512 REQUIRES(mFlinger->mStateLock) {
Ady Abraham5a3e3562023-06-07 10:32:08 -0700513 if (info.skippedFrameVsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
514 return;
515 }
516
517 FrameTimelineInfo skippedFrameTimelineInfo = info;
518 skippedFrameTimelineInfo.vsyncId = info.skippedFrameVsyncId;
519
520 auto surfaceFrame =
521 mFlinger->mFrameTimeline->createSurfaceFrameForToken(skippedFrameTimelineInfo,
522 mOwnerPid, mOwnerUid,
523 getSequence(), mName, debugName,
Vishnu Nair39a74a92024-07-29 19:01:50 +0000524 /*isBuffer*/ false, gameMode);
Ben Widawskyebdbead2024-10-24 11:47:50 -0700525 // Buffer hasn't yet been latched, so use mDrawingState
526 surfaceFrame->setDesiredPresentTime(mDrawingState.desiredPresentTime);
Ady Abraham5a3e3562023-06-07 10:32:08 -0700527 surfaceFrame->setActualStartTime(skippedFrameTimelineInfo.skippedFrameStartTimeNanos);
528 // For Transactions, the post time is considered to be both queue and acquire fence time.
529 surfaceFrame->setActualQueueTime(postTime);
530 surfaceFrame->setAcquireFenceTime(postTime);
531 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
532 if (fps) {
533 surfaceFrame->setRenderRate(*fps);
534 }
Ady Abraham5a3e3562023-06-07 10:32:08 -0700535 addSurfaceFrameDroppedForBuffer(surfaceFrame, postTime);
536}
537
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700538bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps,
539 nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000540 if (mDrawingState.frameRateForLayerTree == frameRate) {
541 return false;
542 }
543
544 mDrawingState.frameRateForLayerTree = frameRate;
545 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700546 ->recordLayerHistory(sequence, layerProps, now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000547 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -0700548 return true;
Steven Thomas3172e202020-01-06 19:25:30 -0800549}
550
Ady Abraham59fd8ff2021-04-15 20:13:30 -0700551Layer::FrameRate Layer::getFrameRateForLayerTree() const {
552 return getDrawingState().frameRateForLayerTree;
553}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800554
Mathias Agopian13127d82013-03-05 17:47:11 -0800555// ----------------------------------------------------------------------------
556// debugging
557// ----------------------------------------------------------------------------
558
Yiwei Zhang5434a782018-12-05 18:06:32 -0800559void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100560 result.append(kDumpTableRowLength, '-');
561 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -0700562 result.append(" Layer name\n");
563 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700564 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -0700565 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +0800566 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -0700567 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -0700568 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100569 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
570 result.append(kDumpTableRowLength, '-');
571 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -0700572}
573
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000574void Layer::miniDump(std::string& result, const frontend::LayerSnapshot& snapshot,
575 const DisplayDevice& display) const {
576 const auto outputLayer = findOutputLayerForDisplay(&display, snapshot.path);
577 if (!outputLayer) {
578 return;
579 }
580
581 StringAppendF(&result, " %s\n", snapshot.debugName.c_str());
582 StringAppendF(&result, " %10zu | ", snapshot.globalZ);
583 StringAppendF(&result, " %10d | ",
584 snapshot.layerMetadata.getInt32(gui::METADATA_WINDOW_TYPE, 0));
585 StringAppendF(&result, "%10s | ", toString(getCompositionType(outputLayer)).c_str());
586 const auto& outputLayerState = outputLayer->getState();
587 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
588 const Rect& frame = outputLayerState.displayFrame;
589 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
590 const FloatRect& crop = outputLayerState.sourceCrop;
591 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
592 crop.bottom);
593 const auto frameRate = snapshot.frameRate;
Ady Abraham77d406d2023-11-22 15:00:23 -0800594 std::string frameRateStr;
595 if (frameRate.vote.rate.isValid()) {
596 StringAppendF(&frameRateStr, "%.2f", frameRate.vote.rate.getValue());
597 }
Rachel Leece6e0042023-06-27 11:22:54 -0700598 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
Ady Abraham77d406d2023-11-22 15:00:23 -0800599 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
Rachel Leece6e0042023-06-27 11:22:54 -0700600 ftl::enum_string(frameRate.vote.type).c_str(),
601 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abraham77d406d2023-11-22 15:00:23 -0800602 } else if (frameRate.category != FrameRateCategory::Default) {
603 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
604 (std::string("Cat::") + ftl::enum_string(frameRate.category)).c_str(),
605 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000606 } else {
607 result.append(41, ' ');
608 }
609
610 const auto focused = isLayerFocusedBasedOnPriority(snapshot.frameRateSelectionPriority);
611 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
612
613 result.append(kDumpTableRowLength, '-');
614 result.append("\n");
615}
616
Yiwei Zhang5434a782018-12-05 18:06:32 -0800617void Layer::dumpFrameStats(std::string& result) const {
Ben Widawskyebdbead2024-10-24 11:47:50 -0700618 if (FlagManager::getInstance().deprecate_frame_tracker()) {
619 FrameStats fs = FrameStats();
620 getFrameStats(&fs);
621 for (auto desired = fs.desiredPresentTimesNano.begin(),
622 actual = fs.actualPresentTimesNano.begin(),
623 ready = fs.frameReadyTimesNano.begin();
624 desired != fs.desiredPresentTimesNano.end() &&
625 actual != fs.actualPresentTimesNano.end() && ready != fs.frameReadyTimesNano.end();
626 ++desired, ++actual, ++ready) {
627 result.append(std::format("{}\t{}\t{}\n", *desired, *actual, *ready));
628 }
629
630 result.push_back('\n');
631 } else {
632 mDeprecatedFrameTracker.dumpStats(result);
633 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800634}
635
Svetoslavd85084b2014-03-20 10:28:31 -0700636void Layer::clearFrameStats() {
Ben Widawskyebdbead2024-10-24 11:47:50 -0700637 if (FlagManager::getInstance().deprecate_frame_tracker()) {
638 mFrameStatsHistorySize = 0;
639 } else {
640 mDeprecatedFrameTracker.clearStats();
641 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800642}
643
Svetoslavd85084b2014-03-20 10:28:31 -0700644void Layer::getFrameStats(FrameStats* outStats) const {
Ben Widawskyebdbead2024-10-24 11:47:50 -0700645 if (FlagManager::getInstance().deprecate_frame_tracker()) {
646 if (auto ftl = getTimeline()) {
647 float fps = ftl->get().computeFps({getSequence()});
648 ftl->get().generateFrameStats(getSequence(), mFrameStatsHistorySize, outStats);
649 outStats->refreshPeriodNano = Fps::fromValue(fps).getPeriodNsecs();
650 }
651 } else {
652 mDeprecatedFrameTracker.getStats(outStats);
653 }
Svetoslavd85084b2014-03-20 10:28:31 -0700654}
655
Brian Anderson5ea5e592016-12-01 16:54:33 -0800656void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800657 const int32_t layerId = getSequence();
658 mFlinger->mTimeStats->onDestroy(layerId);
659 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -0800660}
661
Kean Mariotti4ba343c2023-04-19 13:31:02 +0000662void Layer::writeCompositionStateToProto(perfetto::protos::LayerProto* layerProto,
663 ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +0000664 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +0000665 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +0000666
667 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +0000668 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +0000669 const auto compositionType = getCompositionType(*display);
Kean Mariotti4ba343c2023-04-19 13:31:02 +0000670 layerProto->set_hwc_composition_type(
671 static_cast<perfetto::protos::HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +0000672 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +0000673 [&]() { return layerProto->mutable_visible_region(); });
674 }
675}
676
Lloyd Pique37c2c9b2018-12-04 17:25:10 -0800677compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700678 const DisplayDevice* display) const {
679 if (!display) return nullptr;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000680 sp<LayerFE> layerFE;
681 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
682 for (auto& [p, layer] : mLayerFEs) {
683 if (p == path) {
684 layerFE = layer;
685 }
686 }
687
688 if (!layerFE) return nullptr;
689 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -0800690}
691
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000692compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
693 const DisplayDevice* display, const frontend::LayerHierarchy::TraversalPath& path) const {
694 if (!display) return nullptr;
695 sp<LayerFE> layerFE;
696 for (auto& [p, layer] : mLayerFEs) {
697 if (p == path) {
698 layerFE = layer;
699 }
700 }
701
702 if (!layerFE) return nullptr;
703 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
704}
705
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700706Region Layer::getVisibleRegion(const DisplayDevice* display) const {
707 const auto outputLayer = findOutputLayerForDisplay(display);
708 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -0800709}
710
Patrick Williamsbb25f802022-08-30 23:02:34 +0000711void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
712 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +0800713 const sp<Fence>& releaseFence) {
Patrick Williams7c9fa272024-08-30 12:38:43 +0000714 if (!listener && !mBufferReleaseChannel) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000715 return;
716 }
Patrick Williams7c9fa272024-08-30 12:38:43 +0000717
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000718 SFTRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
Patrick Williams7c9fa272024-08-30 12:38:43 +0000719
720 ReleaseCallbackId callbackId{buffer->getId(), framenumber};
721 const sp<Fence>& fence = releaseFence ? releaseFence : Fence::NO_FENCE;
liulijuneb489f62022-10-17 22:02:14 +0800722 uint32_t currentMaxAcquiredBufferCount =
723 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Patrick Williams7c9fa272024-08-30 12:38:43 +0000724
Alec Mouridf868ba2025-02-25 16:08:19 -0800725 if (FlagManager::getInstance().monitor_buffer_fences()) {
726 buffer->getDependencyMonitor().addEgress(FenceTime::makeValid(fence), "Layer release");
727 }
728
Patrick Williams7c9fa272024-08-30 12:38:43 +0000729 if (listener) {
730 listener->onReleaseBuffer(callbackId, fence, currentMaxAcquiredBufferCount);
731 }
732
Patrick Williamsbb504472024-10-25 13:20:32 -0500733 if (!mBufferReleaseChannel) {
734 return;
735 }
736
737 status_t status = mBufferReleaseChannel->writeReleaseFence(callbackId, fence,
738 currentMaxAcquiredBufferCount);
739 if (status != OK) {
740 int error = -status;
741 // callReleaseBufferCallback is called during Layer's destructor. In this case, it's
742 // expected to receive connection errors.
743 if (error != EPIPE && error != ECONNRESET) {
744 ALOGD("[%s] writeReleaseFence failed. error %d (%s)", getDebugName(), error,
745 strerror(error));
746 }
Patrick Williams7c9fa272024-08-30 12:38:43 +0000747 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000748}
749
Melody Hsu793f8362024-01-08 20:00:35 +0000750sp<CallbackHandle> Layer::findCallbackHandle() {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000751 // If we are displayed on multiple displays in a single composition cycle then we would
752 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
753 // For example we can only use it if all the displays are client comp, and we need
754 // to merge all the client comp fences. We could do this, but for now we just
755 // disable the optimization when a layer is composed on multiple displays.
756 if (mClearClientCompositionFenceOnLayerDisplayed) {
757 mLastClientCompositionFence = nullptr;
758 } else {
759 mClearClientCompositionFenceOnLayerDisplayed = true;
760 }
761
762 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
763 // buffer that was presented on this layer. The first transaction that came in this frame that
764 // replaced the previous buffer on this layer needs this release fence, because the fence will
765 // let the client know when that previous buffer is removed from the screen.
766 //
767 // Every other transaction on this layer does not need a release fence because no other
768 // Transactions that were set on this layer this frame are going to have their preceding buffer
769 // removed from the display this frame.
770 //
771 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
772 // buffer so it doesn't need a previous release fence because the layer still needs the previous
773 // buffer. The second transaction contains a buffer so it needs a previous release fence because
774 // the previous buffer will be released this frame. The third transaction also contains a
775 // buffer. It replaces the buffer in the second transaction. The buffer in the second
776 // transaction will now no longer be presented so it is released immediately and the third
777 // transaction doesn't need a previous release fence.
778 sp<CallbackHandle> ch;
779 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -0700780 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000781 ch = handle;
782 break;
783 }
784 }
Melody Hsu793f8362024-01-08 20:00:35 +0000785 return ch;
786}
787
788void Layer::prepareReleaseCallbacks(ftl::Future<FenceResult> futureFenceResult,
789 ui::LayerStack layerStack) {
790 sp<CallbackHandle> ch = findCallbackHandle();
791
792 if (ch != nullptr) {
793 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
794 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
795 ch->name = mName;
796 } else {
Melody Hsue4ef87f2024-03-26 23:54:45 +0000797 // If we didn't get a release callback yet (e.g. some scenarios when capturing
798 // screenshots asynchronously) then make sure we don't drop the fence.
799 // Older fences for the same layer stack can be dropped when a new fence arrives.
800 // An assumption here is that RenderEngine performs work sequentially, so an
801 // incoming fence will not fire before an existing fence.
802 mAdditionalPreviousReleaseFences.emplace_or_replace(layerStack,
803 std::move(futureFenceResult));
Melody Hsu793f8362024-01-08 20:00:35 +0000804 }
805
806 if (mBufferInfo.mBuffer) {
807 mPreviouslyPresentedLayerStacks.push_back(layerStack);
808 }
809
810 if (mDrawingState.frameNumber > 0) {
811 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
812 }
813}
814
Patrick Williamsbb25f802022-08-30 23:02:34 +0000815void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
816 for (const auto& handle : mDrawingState.callbackHandles) {
Patrick Williams7c9fa272024-08-30 12:38:43 +0000817 handle->bufferReleaseChannel = mBufferReleaseChannel;
Melody Hsu9af30702024-04-17 18:23:43 +0000818 handle->transformHint = mTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000819 handle->dequeueReadyTime = dequeueReadyTime;
820 handle->currentMaxAcquiredBufferCount =
821 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000822 SFTRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
823 handle->previousReleaseCallbackId.framenumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000824 }
825
826 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -0700827 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000828 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
829 break;
830 }
831 }
832
Pascal Mütschardd56514e2024-05-24 17:37:13 +0200833 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000834 mDrawingState.callbackHandles = {};
835}
836
Patrick Williamsbb25f802022-08-30 23:02:34 +0000837bool Layer::setTransform(uint32_t transform) {
838 if (mDrawingState.bufferTransform == transform) return false;
839 mDrawingState.bufferTransform = transform;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000840 setTransactionFlags(eTransactionNeeded);
841 return true;
842}
843
844bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
845 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
846 mDrawingState.sequence++;
847 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000848 setTransactionFlags(eTransactionNeeded);
849 return true;
850}
851
Ben Widawsky67346b92025-02-11 08:44:31 -0800852void Layer::releasePreviousBuffer() REQUIRES(mFlinger->mStateLock) {
Dorin Drimuse5374e52023-08-02 17:52:43 +0000853 mReleasePreviousBuffer = true;
854 if (!mBufferInfo.mBuffer ||
855 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
856 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
857 // If mDrawingState has a buffer, and we are about to update again
858 // before swapping to drawing state, then the first buffer will be
859 // dropped and we should decrement the pending buffer count and
860 // call any release buffer callbacks if set.
861 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
862 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
863 mDrawingState.acquireFence);
Dominic Lemire95c4ecc2024-07-09 12:06:18 -0700864 const int32_t layerId = getSequence();
865 mFlinger->mTimeStats->removeTimeRecord(layerId, mDrawingState.frameNumber);
Dorin Drimuse5374e52023-08-02 17:52:43 +0000866 decrementPendingBufferCount();
867 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
868 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
869 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX, systemTime());
870 mDrawingState.bufferSurfaceFrameTX.reset();
871 }
872 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
873 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
874 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
875 mLastClientCompositionFence);
876 mLastClientCompositionFence = nullptr;
877 }
878}
879
Vishnu Nair7ee4f462023-04-19 09:54:09 -0700880void Layer::resetDrawingStateBufferInfo() {
881 mDrawingState.producerId = 0;
882 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +0000883 mDrawingState.previousFrameNumber = 0;
Vishnu Nair7ee4f462023-04-19 09:54:09 -0700884 mDrawingState.releaseBufferListener = nullptr;
885 mDrawingState.buffer = nullptr;
886 mDrawingState.acquireFence = sp<Fence>::make(-1);
887 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
888 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
889 mDrawingState.releaseBufferEndpoint = nullptr;
890}
891
Patrick Williamsbb25f802022-08-30 23:02:34 +0000892bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
893 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
Ben Widawsky67346b92025-02-11 08:44:31 -0800894 bool isAutoTimestamp, const FrameTimelineInfo& info, gui::GameMode gameMode)
895 REQUIRES(mFlinger->mStateLock) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000896 SFTRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +0000897
898 const bool frameNumberChanged =
899 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
900 const uint64_t frameNumber =
901 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000902 SFTRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000903
904 if (mDrawingState.buffer) {
Dorin Drimuse5374e52023-08-02 17:52:43 +0000905 releasePreviousBuffer();
Vishnu Nair7ee4f462023-04-19 09:54:09 -0700906 } else if (buffer) {
Vishnu Nairc09c0232023-03-02 03:22:35 +0000907 // if we are latching a buffer for the first time then clear the mLastLatchTime since
908 // we don't want to incorrectly classify a frame if we miss the desired present time.
909 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000910 }
911
Vishnu Nair7ee4f462023-04-19 09:54:09 -0700912 mDrawingState.desiredPresentTime = desiredPresentTime;
913 mDrawingState.isAutoTimestamp = isAutoTimestamp;
914 mDrawingState.latchedVsyncId = info.vsyncId;
Ady Abraham55269162023-05-09 11:26:06 -0700915 mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
Vishnu Nair7ee4f462023-04-19 09:54:09 -0700916 if (!buffer) {
917 resetDrawingStateBufferInfo();
918 setTransactionFlags(eTransactionNeeded);
919 mDrawingState.bufferSurfaceFrameTX = nullptr;
Vishnu Nair39a74a92024-07-29 19:01:50 +0000920 setFrameTimelineVsyncForBufferlessTransaction(info, postTime, gameMode);
Vishnu Nair7ee4f462023-04-19 09:54:09 -0700921 return true;
Dorin Drimuse5374e52023-08-02 17:52:43 +0000922 } else {
923 // release sideband stream if it exists and a non null buffer is being set
924 if (mDrawingState.sidebandStream != nullptr) {
Vishnu Nair39a74a92024-07-29 19:01:50 +0000925 setSidebandStream(nullptr, info, postTime, gameMode);
Dorin Drimuse5374e52023-08-02 17:52:43 +0000926 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -0700927 }
928
Vishnu Naird1f74982023-06-15 20:16:51 -0700929 if ((mDrawingState.producerId > bufferData.producerId) ||
930 ((mDrawingState.producerId == bufferData.producerId) &&
931 (mDrawingState.frameNumber > frameNumber))) {
932 ALOGE("Out of order buffers detected for %s producedId=%d frameNumber=%" PRIu64
933 " -> producedId=%d frameNumber=%" PRIu64,
934 getDebugName(), mDrawingState.producerId, mDrawingState.frameNumber,
935 bufferData.producerId, frameNumber);
936 TransactionTraceWriter::getInstance().invoke("out_of_order_buffers_", /*overwrite=*/false);
937 }
938
liulijuneb489f62022-10-17 22:02:14 +0800939 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -0700940 mDrawingState.barrierProducerId =
941 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000942 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -0700943 mDrawingState.barrierFrameNumber =
944 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
945
Patrick Williamsbb25f802022-08-30 23:02:34 +0000946 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
Alec Mouridf868ba2025-02-25 16:08:19 -0800947 mDrawingState.previousBuffer = std::move(mDrawingState.buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000948 mDrawingState.buffer = std::move(buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000949 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
950 ? bufferData.acquireFence
951 : Fence::NO_FENCE;
952 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
953 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
954 // We latched this buffer unsiganled, so we need to pass the acquire fence
955 // on the callback instead of just the acquire time, since it's unknown at
956 // this point.
957 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
958 } else {
959 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
960 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000961 setTransactionFlags(eTransactionNeeded);
962
963 const int32_t layerId = getSequence();
964 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
Vishnu Nair39a74a92024-07-29 19:01:50 +0000965 mOwnerUid, postTime, gameMode);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000966
Vishnu Nair39a74a92024-07-29 19:01:50 +0000967 setFrameTimelineVsyncForBufferTransaction(info, postTime, gameMode);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000968
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900969 if (bufferData.dequeueTime > 0) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000970 const uint64_t bufferId = mDrawingState.buffer->getId();
971 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900972 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber,
973 bufferData.dequeueTime,
Patrick Williamsbb25f802022-08-30 23:02:34 +0000974 FrameTracer::FrameEvent::DEQUEUE);
975 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
976 FrameTracer::FrameEvent::QUEUE);
977 }
978
979 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
Arthur Hungc70bee22023-06-02 01:35:52 +0000980
981 // If the layer had been updated a TextureView, this would make sure the present time could be
982 // same to TextureView update when it's a small dirty, and get the correct heuristic rate.
Jerry Chang36678002023-11-29 16:56:17 +0000983 if (mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +0000984 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
985 mUsedVsyncIdForRefreshRateSelection = true;
986 }
987 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000988 return true;
989}
990
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000991void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
992 mDrawingState.desiredPresentTime = desiredPresentTime;
993 mDrawingState.isAutoTimestamp = isAutoTimestamp;
994}
995
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700996void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps, nsecs_t now) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000997 SFTRACE_CALL();
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000998 const nsecs_t presentTime = [&] {
Ady Abraham55269162023-05-09 11:26:06 -0700999 if (!mDrawingState.isAutoTimestamp) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001000 SFTRACE_FORMAT_INSTANT("desiredPresentTime");
Ady Abraham55269162023-05-09 11:26:06 -07001001 return mDrawingState.desiredPresentTime;
1002 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001003
Ady Abraham55269162023-05-09 11:26:06 -07001004 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
1005 const auto prediction =
1006 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
1007 mDrawingState.latchedVsyncId);
1008 if (prediction.has_value()) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001009 SFTRACE_FORMAT_INSTANT("predictedPresentTime");
Arthur Hungc70bee22023-06-02 01:35:52 +00001010 mMaxTimeForUseVsyncId = prediction->presentTime +
1011 scheduler::LayerHistory::kMaxPeriodForHistory.count();
Ady Abraham55269162023-05-09 11:26:06 -07001012 return prediction->presentTime;
1013 }
1014 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001015
Jerry Chang36678002023-11-29 16:56:17 +00001016 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00001017 return static_cast<nsecs_t>(0);
1018 }
1019
1020 // If the layer is not an application and didn't set an explicit rate or desiredPresentTime,
1021 // return "0" to tell the layer history that it will use the max refresh rate without
1022 // calculating the adaptive rate.
1023 if (mWindowType != WindowInfo::Type::APPLICATION &&
1024 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
1025 return static_cast<nsecs_t>(0);
1026 }
1027
1028 // Return the valid present time only when the layer potentially updated a TextureView so
1029 // LayerHistory could heuristically calculate the rate if the UI is continually updating.
1030 if (mUsedVsyncIdForRefreshRateSelection) {
1031 const auto prediction =
1032 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
1033 mDrawingState.latchedVsyncId);
1034 if (prediction.has_value()) {
1035 if (mMaxTimeForUseVsyncId >= prediction->presentTime) {
1036 return prediction->presentTime;
1037 }
1038 mUsedVsyncIdForRefreshRateSelection = false;
1039 }
1040 }
1041
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001042 return static_cast<nsecs_t>(0);
1043 }();
Ady Abraham55269162023-05-09 11:26:06 -07001044
Vishnu Nair2665ca92024-07-09 22:08:15 +00001045 if (SFTRACE_ENABLED() && presentTime > 0) {
Ady Abraham55269162023-05-09 11:26:06 -07001046 const auto presentIn = TimePoint::fromNs(presentTime) - TimePoint::now();
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001047 SFTRACE_FORMAT_INSTANT("presentIn %s", to_string(presentIn).c_str());
Ady Abraham55269162023-05-09 11:26:06 -07001048 }
1049
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001050 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001051 scheduler::LayerHistory::LayerUpdateType::Buffer);
1052}
1053
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001054void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps, nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001055 const nsecs_t presentTime =
1056 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001057 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001058 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
1059}
1060
Patrick Williamsbb25f802022-08-30 23:02:34 +00001061bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00001062 if (mDrawingState.dataspace == dataspace) return false;
1063 mDrawingState.dataspace = dataspace;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001064 setTransactionFlags(eTransactionNeeded);
1065 return true;
1066}
1067
John Reck68796592023-01-25 13:47:12 -05001068bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07001069 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
1070 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05001071 return false;
Sally Qi963049b2023-03-23 14:06:21 -07001072 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
1073 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05001074 setTransactionFlags(eTransactionNeeded);
1075 return true;
1076}
1077
Alec Mouri1b0d4e12024-02-12 22:27:19 +00001078bool Layer::setDesiredHdrHeadroom(float desiredRatio) {
1079 if (mDrawingState.desiredHdrSdrRatio == desiredRatio) return false;
1080 mDrawingState.desiredHdrSdrRatio = desiredRatio;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001081 setTransactionFlags(eTransactionNeeded);
1082 return true;
1083}
1084
Dorin Drimuse5374e52023-08-02 17:52:43 +00001085bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream, const FrameTimelineInfo& info,
Ben Widawsky67346b92025-02-11 08:44:31 -08001086 nsecs_t postTime, gui::GameMode gameMode)
1087 REQUIRES(mFlinger->mStateLock) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00001088 if (mDrawingState.sidebandStream == sidebandStream) return false;
1089
1090 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
1091 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
1092 } else if (sidebandStream != nullptr) {
1093 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
1094 }
1095
1096 mDrawingState.sidebandStream = sidebandStream;
Dorin Drimuse5374e52023-08-02 17:52:43 +00001097 if (sidebandStream != nullptr && mDrawingState.buffer != nullptr) {
1098 releasePreviousBuffer();
1099 resetDrawingStateBufferInfo();
1100 mDrawingState.bufferSurfaceFrameTX = nullptr;
Vishnu Nair39a74a92024-07-29 19:01:50 +00001101 setFrameTimelineVsyncForBufferlessTransaction(info, postTime, gameMode);
Dorin Drimuse5374e52023-08-02 17:52:43 +00001102 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00001103 setTransactionFlags(eTransactionNeeded);
1104 if (!mSidebandStreamChanged.exchange(true)) {
1105 // mSidebandStreamChanged was false
1106 mFlinger->onLayerUpdate();
1107 }
1108 return true;
1109}
1110
Vishnu Nair3af0ec02023-02-10 04:13:48 +00001111bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
1112 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00001113 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
1114 if (handles.empty()) {
1115 mReleasePreviousBuffer = false;
1116 return false;
1117 }
1118
Pascal Muetschard81cef292023-02-06 12:18:52 +01001119 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001120 for (const auto& handle : handles) {
1121 // If this transaction set a buffer on this layer, release its previous buffer
1122 handle->releasePreviousBuffer = mReleasePreviousBuffer;
1123
1124 // If this layer will be presented in this frame
1125 if (willPresent) {
1126 // If this transaction set an acquire fence on this layer, set its acquire time
1127 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
1128 handle->frameNumber = mDrawingState.frameNumber;
Alec Mouri21d94322023-10-17 19:51:39 +00001129 handle->previousFrameNumber = mDrawingState.previousFrameNumber;
Alec Mouridf868ba2025-02-25 16:08:19 -08001130 handle->previousBuffer = mDrawingState.previousBuffer;
Melody Hsu0077fde2024-10-17 21:42:50 +00001131 if (mPreviousReleaseBufferEndpoint == handle->listener) {
Melody Hsue4ef87f2024-03-26 23:54:45 +00001132 // Add fence from previous screenshot now so that it can be dispatched to the
Alec Mouri9892aac2023-12-11 21:16:59 +00001133 // client.
Melody Hsue4ef87f2024-03-26 23:54:45 +00001134 for (auto& [_, future] : mAdditionalPreviousReleaseFences) {
1135 handle->previousReleaseFences.emplace_back(std::move(future));
Alec Mouri9892aac2023-12-11 21:16:59 +00001136 }
1137 mAdditionalPreviousReleaseFences.clear();
1138 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00001139 // Store so latched time and release fence can be set
1140 mDrawingState.callbackHandles.push_back(handle);
1141
1142 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01001143 // Queue this handle to be notified below.
1144 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00001145 }
1146 }
1147
Pascal Muetschard81cef292023-02-06 12:18:52 +01001148 if (!remainingHandles.empty()) {
1149 // Notify the transaction completed threads these handles are done. These are only the
1150 // handles that were not added to the mDrawingState, which will be notified later.
Pascal Mütschardd56514e2024-05-24 17:37:13 +02001151 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles);
Pascal Muetschard81cef292023-02-06 12:18:52 +01001152 }
1153
Patrick Williamsbb25f802022-08-30 23:02:34 +00001154 mReleasePreviousBuffer = false;
1155 mCallbackHandleAcquireTimeOrFence = -1;
1156
1157 return willPresent;
1158}
1159
1160Rect Layer::getBufferSize(const State& /*s*/) const {
1161 // for buffer state layers we use the display frame size as the buffer size.
1162
1163 if (mBufferInfo.mBuffer == nullptr) {
1164 return Rect::INVALID_RECT;
1165 }
1166
1167 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
1168 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
1169
1170 // Undo any transformations on the buffer and return the result.
1171 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
1172 std::swap(bufWidth, bufHeight);
1173 }
1174
1175 if (getTransformToDisplayInverse()) {
Leon Scroggins III85d4b222023-05-09 13:58:18 -04001176 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00001177 if (invTransform & ui::Transform::ROT_90) {
1178 std::swap(bufWidth, bufHeight);
1179 }
1180 }
1181
1182 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
1183}
1184
Patrick Williamsbb25f802022-08-30 23:02:34 +00001185bool Layer::fenceHasSignaled() const {
1186 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
1187 return true;
1188 }
1189
1190 const bool fenceSignaled =
1191 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
1192 if (!fenceSignaled) {
1193 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
1194 TimeStats::LatchSkipReason::LateAcquire);
1195 }
1196
1197 return fenceSignaled;
1198}
1199
Vishnu Nair3af0ec02023-02-10 04:13:48 +00001200void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00001201 for (const auto& handle : mDrawingState.callbackHandles) {
1202 handle->refreshStartTime = refreshStartTime;
1203 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00001204}
1205
Patrick Williamsbb25f802022-08-30 23:02:34 +00001206bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00001207 if (mSidebandStreamChanged.exchange(false)) {
1208 const State& s(getDrawingState());
1209 // mSidebandStreamChanged was true
1210 mSidebandStream = s.sidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001211 if (mSidebandStream != nullptr) {
1212 setTransactionFlags(eTransactionNeeded);
1213 mFlinger->setTransactionFlags(eTraversalNeeded);
1214 }
1215 recomputeVisibleRegions = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001216 return true;
1217 }
1218 return false;
1219}
1220
Ben Widawsky67346b92025-02-11 08:44:31 -08001221void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) REQUIRES(mFlinger->mStateLock) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00001222 const State& s(getDrawingState());
1223
1224 if (!s.buffer) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07001225 if (bgColorOnly || mBufferInfo.mBuffer) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00001226 for (auto& handle : mDrawingState.callbackHandles) {
1227 handle->latchTime = latchTime;
1228 }
1229 }
1230 return;
1231 }
1232
1233 for (auto& handle : mDrawingState.callbackHandles) {
1234 if (handle->frameNumber == mDrawingState.frameNumber) {
1235 handle->latchTime = latchTime;
1236 }
1237 }
1238
1239 const int32_t layerId = getSequence();
1240 const uint64_t bufferId = mDrawingState.buffer->getId();
1241 const uint64_t frameNumber = mDrawingState.frameNumber;
1242 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
1243 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
1244 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
1245
1246 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
1247 FrameTracer::FrameEvent::ACQUIRE_FENCE);
1248 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
1249 FrameTracer::FrameEvent::LATCH);
1250
1251 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
1252 if (bufferSurfaceFrame != nullptr &&
1253 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
1254 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
1255 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
1256 // are processing the next state.
1257 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
1258 mDrawingState.acquireFenceTime->getSignalTime(),
1259 latchTime);
1260 mDrawingState.bufferSurfaceFrameTX.reset();
1261 }
1262
1263 std::deque<sp<CallbackHandle>> remainingHandles;
1264 mFlinger->getTransactionCallbackInvoker()
1265 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
1266 mDrawingState.callbackHandles = remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001267}
1268
1269void Layer::gatherBufferInfo() {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07001270 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
1271 mPreviousReleaseBufferEndpoint = mBufferInfo.mReleaseBufferEndpoint;
1272 if (!mDrawingState.buffer) {
1273 mBufferInfo = {};
1274 return;
1275 }
1276
1277 if ((!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer))) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00001278 decrementPendingBufferCount();
1279 }
1280
Patrick Williamsbb25f802022-08-30 23:02:34 +00001281 mBufferInfo.mBuffer = mDrawingState.buffer;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07001282 mBufferInfo.mReleaseBufferEndpoint = mDrawingState.releaseBufferEndpoint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001283 mBufferInfo.mFence = mDrawingState.acquireFence;
1284 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
1285 mBufferInfo.mPixelFormat =
1286 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
1287 mBufferInfo.mFrameLatencyNeeded = true;
1288 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
1289 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00001290 mBufferInfo.mTransform = mDrawingState.bufferTransform;
1291 auto lastDataspace = mBufferInfo.mDataspace;
1292 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00001293 if (mBufferInfo.mBuffer != nullptr) {
1294 auto& mapper = GraphicBufferMapper::get();
1295 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
1296 // and don't need to possibly remaps buffers.
1297 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
1298 status_t err = OK;
1299 {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001300 SFTRACE_NAME("getDataspace");
Alec Mouri74c7ae12023-03-26 02:57:47 +00001301 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
1302 }
1303 if (err != OK || dataspace != mBufferInfo.mDataspace) {
1304 {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001305 SFTRACE_NAME("setDataspace");
Alec Mouri74c7ae12023-03-26 02:57:47 +00001306 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
1307 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
1308 }
1309
1310 // Some GPU drivers may cache gralloc metadata which means before we composite we need
1311 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
1312 // compatible with old vendors, with a ticking clock.
1313 static const int32_t kVendorVersion =
Alec Mouri8a06fb72023-11-16 22:07:13 +00001314 base::GetIntProperty("ro.board.api_level", __ANDROID_API_FUTURE__);
Alec Mouri74c7ae12023-03-26 02:57:47 +00001315 if (const auto format =
1316 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
1317 mBufferInfo.mBuffer->getPixelFormat());
1318 err == OK && kVendorVersion < __ANDROID_API_U__ &&
1319 (format ==
1320 aidl::android::hardware::graphics::common::PixelFormat::
1321 IMPLEMENTATION_DEFINED ||
1322 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
1323 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
1324 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
1325 mBufferInfo.mBuffer->remapBuffer();
1326 }
1327 }
1328 }
Alec Mourid05a7452024-09-20 13:44:02 +00001329 if (lastDataspace != mBufferInfo.mDataspace ||
1330 mBufferInfo.mTimeSinceDataspaceUpdate == std::chrono::steady_clock::time_point::min()) {
John Reck68796592023-01-25 13:47:12 -05001331 mFlinger->mHdrLayerInfoChanged = true;
Alec Mourid05a7452024-09-20 13:44:02 +00001332 const auto currentTime = std::chrono::steady_clock::now();
1333 if (mBufferInfo.mTimeSinceDataspaceUpdate > std::chrono::steady_clock::time_point::min()) {
1334 mFlinger->mLayerEvents
1335 .emplace_back(mOwnerUid, getSequence(), lastDataspace,
1336 std::chrono::duration_cast<std::chrono::milliseconds>(
1337 currentTime - mBufferInfo.mTimeSinceDataspaceUpdate));
1338 }
1339 mBufferInfo.mTimeSinceDataspaceUpdate = currentTime;
John Reck68796592023-01-25 13:47:12 -05001340 }
Sally Qi963049b2023-03-23 14:06:21 -07001341 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
1342 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05001343 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001344 }
1345 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
Patrick Williamsbb25f802022-08-30 23:02:34 +00001346 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001347}
1348
1349Rect Layer::computeBufferCrop(const State& s) {
1350 if (s.buffer && !s.bufferCrop.isEmpty()) {
1351 Rect bufferCrop;
1352 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
1353 return bufferCrop;
1354 } else if (s.buffer) {
1355 return s.buffer->getBounds();
1356 } else {
1357 return s.bufferCrop;
1358 }
1359}
1360
Patrick Williamsbb25f802022-08-30 23:02:34 +00001361void Layer::decrementPendingBufferCount() {
Melody Hsu16355782024-10-09 08:56:28 +00001362 int32_t pendingBuffers = --mPendingBuffers;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001363 tracePendingBufferCount(pendingBuffers);
1364}
1365
1366void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001367 SFTRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
Patrick Williamsbb25f802022-08-30 23:02:34 +00001368}
1369
Vishnu Nair3af0ec02023-02-10 04:13:48 +00001370sp<LayerFE> Layer::getCompositionEngineLayerFE(
1371 const frontend::LayerHierarchy::TraversalPath& path) {
1372 for (auto& [p, layerFE] : mLayerFEs) {
1373 if (p == path) {
1374 return layerFE;
1375 }
1376 }
Lloyd Pique70ddc672024-04-30 18:20:40 -07001377 auto layerFE = mFlinger->getFactory().createLayerFE(mName, this);
Vishnu Nair3af0ec02023-02-10 04:13:48 +00001378 mLayerFEs.emplace_back(path, layerFE);
1379 return layerFE;
1380}
1381
Leon Scroggins III5b581492023-10-31 14:29:41 -04001382void Layer::onCompositionPresented(const DisplayDevice* display,
1383 const std::shared_ptr<FenceTime>& glDoneFence,
1384 const std::shared_ptr<FenceTime>& presentFence,
Vishnu Nair39a74a92024-07-29 19:01:50 +00001385 const CompositorTiming& compositorTiming,
1386 gui::GameMode gameMode) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00001387 // mFrameLatencyNeeded is true when a new frame was latched for the
1388 // composition.
1389 if (!mBufferInfo.mFrameLatencyNeeded) return;
1390
1391 for (const auto& handle : mDrawingState.callbackHandles) {
1392 handle->gpuCompositionDoneFence = glDoneFence;
1393 handle->compositorTiming = compositorTiming;
1394 }
1395
Ben Widawskyebdbead2024-10-24 11:47:50 -07001396 // Update mDeprecatedFrameTracker.
Patrick Williamsbb25f802022-08-30 23:02:34 +00001397 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
Ben Widawskyebdbead2024-10-24 11:47:50 -07001398 mDeprecatedFrameTracker.setDesiredPresentTime(desiredPresentTime);
Patrick Williamsbb25f802022-08-30 23:02:34 +00001399
1400 const int32_t layerId = getSequence();
1401 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
1402
1403 const auto outputLayer = findOutputLayerForDisplay(display);
1404 if (outputLayer && outputLayer->requiresClientComposition()) {
1405 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
1406 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
1407 clientCompositionTimestamp,
1408 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
1409 // Update the SurfaceFrames in the drawing state
1410 if (mDrawingState.bufferSurfaceFrameTX) {
1411 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
1412 }
1413 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
1414 surfaceFrame->setGpuComposition();
1415 }
1416 }
1417
Ben Widawskyebdbead2024-10-24 11:47:50 -07001418 // The SurfaceFrame's AcquireFence is the same as this.
Patrick Williamsbb25f802022-08-30 23:02:34 +00001419 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
1420 if (frameReadyFence->isValid()) {
Ben Widawskyebdbead2024-10-24 11:47:50 -07001421 mDeprecatedFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Patrick Williamsbb25f802022-08-30 23:02:34 +00001422 } else {
1423 // There was no fence for this frame, so assume that it was ready
1424 // to be presented at the desired present time.
Ben Widawskyebdbead2024-10-24 11:47:50 -07001425 mDeprecatedFrameTracker.setFrameReadyTime(desiredPresentTime);
Patrick Williamsbb25f802022-08-30 23:02:34 +00001426 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00001427 if (display) {
Dominik Laskowskife749dc2024-07-26 10:09:31 -04001428 const auto activeMode = display->refreshRateSelector().getActiveMode();
1429 const Fps refreshRate = activeMode.fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001430 const std::optional<Fps> renderRate =
1431 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1432
Alec Mouri7c1d8b52023-08-29 20:14:46 +00001433 const auto vote = frameRateToSetFrameRateVotePayload(getFrameRateForLayerTree());
Patrick Williamsbb25f802022-08-30 23:02:34 +00001434
1435 if (presentFence->isValid()) {
1436 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
1437 refreshRate, renderRate, vote, gameMode);
1438 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
1439 presentFence,
1440 FrameTracer::FrameEvent::PRESENT_FENCE);
Ben Widawskyebdbead2024-10-24 11:47:50 -07001441 mDeprecatedFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
Gil Dekel147626a2025-03-03 17:09:41 -05001442 } else if (const auto displayId = asPhysicalDisplayId(display->getDisplayIdVariant());
1443 displayId.has_value() && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04001444 // The HWC doesn't support present fences, so use the present timestamp instead.
1445 const nsecs_t presentTimestamp =
1446 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
1447
1448 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
Dominik Laskowskife749dc2024-07-26 10:09:31 -04001449 const nsecs_t vsyncPeriod =
1450 mFlinger->getHwComposer()
1451 .getDisplayVsyncPeriod(*displayId)
1452 .value_opt()
1453 .value_or(activeMode.modePtr->getVsyncRate().getPeriodNsecs());
1454
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04001455 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
1456
Patrick Williamsbb25f802022-08-30 23:02:34 +00001457 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
1458 refreshRate, renderRate, vote, gameMode);
1459 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
1460 mCurrentFrameNumber, actualPresentTime,
1461 FrameTracer::FrameEvent::PRESENT_FENCE);
Ben Widawskyebdbead2024-10-24 11:47:50 -07001462 mDeprecatedFrameTracker.setActualPresentTime(actualPresentTime);
Patrick Williamsbb25f802022-08-30 23:02:34 +00001463 }
1464 }
1465
Ben Widawskyebdbead2024-10-24 11:47:50 -07001466 mFrameStatsHistorySize++;
1467 mDeprecatedFrameTracker.advanceFrame();
Patrick Williamsbb25f802022-08-30 23:02:34 +00001468 mBufferInfo.mFrameLatencyNeeded = false;
1469}
1470
Ben Widawsky67346b92025-02-11 08:44:31 -08001471bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly)
1472 REQUIRES(mFlinger->mStateLock) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001473 SFTRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
1474 getDrawingState().frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00001475
1476 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
1477
1478 if (refreshRequired) {
1479 return refreshRequired;
1480 }
1481
1482 // If the head buffer's acquire fence hasn't signaled yet, return and
1483 // try again later
1484 if (!fenceHasSignaled()) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001485 SFTRACE_NAME("!fenceHasSignaled()");
Patrick Williamsbb25f802022-08-30 23:02:34 +00001486 mFlinger->onLayerUpdate();
1487 return false;
1488 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00001489 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00001490
1491 // Capture the old state of the layer for comparisons later
1492 BufferInfo oldBufferInfo = mBufferInfo;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001493 mPreviousFrameNumber = mCurrentFrameNumber;
1494 mCurrentFrameNumber = mDrawingState.frameNumber;
1495 gatherBufferInfo();
1496
Vishnu Nair7ee4f462023-04-19 09:54:09 -07001497 if (mBufferInfo.mBuffer) {
1498 // We latched a buffer that will be presented soon. Clear the previously presented layer
1499 // stack list.
1500 mPreviouslyPresentedLayerStacks.clear();
1501 }
1502
1503 if (mDrawingState.buffer == nullptr) {
1504 const bool bufferReleased = oldBufferInfo.mBuffer != nullptr;
1505 recomputeVisibleRegions = bufferReleased;
1506 return bufferReleased;
1507 }
1508
Patrick Williamsbb25f802022-08-30 23:02:34 +00001509 if (oldBufferInfo.mBuffer == nullptr) {
1510 // the first time we receive a buffer, we need to trigger a
1511 // geometry invalidation.
1512 recomputeVisibleRegions = true;
1513 }
1514
1515 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
1516 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
Patrick Williamsbb25f802022-08-30 23:02:34 +00001517 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
1518 recomputeVisibleRegions = true;
1519 }
1520
1521 if (oldBufferInfo.mBuffer != nullptr) {
1522 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
1523 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
1524 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
1525 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
1526 recomputeVisibleRegions = true;
1527 }
1528 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00001529 return true;
1530}
1531
Patrick Williamsbb25f802022-08-30 23:02:34 +00001532bool Layer::getTransformToDisplayInverse() const {
1533 return mBufferInfo.mTransformToDisplayInverse;
1534}
1535
Patrick Williamsbb25f802022-08-30 23:02:34 +00001536ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
1537 ui::Dataspace updatedDataspace = dataspace;
1538 // translate legacy dataspaces to modern dataspaces
1539 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00001540 // Treat unknown dataspaces as V0_sRGB
1541 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00001542 case ui::Dataspace::SRGB:
1543 updatedDataspace = ui::Dataspace::V0_SRGB;
1544 break;
1545 case ui::Dataspace::SRGB_LINEAR:
1546 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
1547 break;
1548 case ui::Dataspace::JFIF:
1549 updatedDataspace = ui::Dataspace::V0_JFIF;
1550 break;
1551 case ui::Dataspace::BT601_625:
1552 updatedDataspace = ui::Dataspace::V0_BT601_625;
1553 break;
1554 case ui::Dataspace::BT601_525:
1555 updatedDataspace = ui::Dataspace::V0_BT601_525;
1556 break;
1557 case ui::Dataspace::BT709:
1558 updatedDataspace = ui::Dataspace::V0_BT709;
1559 break;
1560 default:
1561 break;
1562 }
1563
1564 return updatedDataspace;
1565}
1566
1567sp<GraphicBuffer> Layer::getBuffer() const {
1568 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
1569}
1570
Chavi Weingarten328a8312023-01-26 21:17:52 +00001571bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00001572 TrustedPresentationListener const& listener) {
1573 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
1574 mTrustedPresentationListener = listener;
1575 mTrustedPresentationThresholds = thresholds;
1576 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
1577 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
1578 mFlinger->mNumTrustedPresentationListeners++;
1579 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
1580 mFlinger->mNumTrustedPresentationListeners--;
1581 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00001582
1583 // Reset trusted presentation states to ensure we start the time again.
1584 mEnteredTrustedPresentationStateTime = -1;
1585 mLastReportedTrustedPresentationState = false;
1586 mLastComputedTrustedPresentationState = false;
1587
1588 // If there's a new trusted presentation listener, the code needs to go through the composite
1589 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
1590 // we're already in the requested state.
1591 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00001592}
1593
Patrick Williams7c9fa272024-08-30 12:38:43 +00001594void Layer::setBufferReleaseChannel(
1595 const std::shared_ptr<gui::BufferReleaseChannel::ProducerEndpoint>& channel) {
1596 mBufferReleaseChannel = channel;
1597}
1598
Vishnu Naira156f482023-02-22 00:23:38 +00001599void Layer::updateLastLatchTime(nsecs_t latchTime) {
1600 mLastLatchTime = latchTime;
1601}
1602
Vishnu Nairdc83d4b2024-08-15 16:29:20 +00001603void Layer::setIsSmallDirty(frontend::LayerSnapshot* snapshot) {
Jerry Chang36678002023-11-29 16:56:17 +00001604 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Vishnu Nairdc83d4b2024-08-15 16:29:20 +00001605 snapshot->isSmallDirty = false;
Arthur Hungc70bee22023-06-02 01:35:52 +00001606 return;
1607 }
1608
1609 if (mWindowType != WindowInfo::Type::APPLICATION &&
1610 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
Vishnu Nairdc83d4b2024-08-15 16:29:20 +00001611 snapshot->isSmallDirty = false;
Arthur Hungc70bee22023-06-02 01:35:52 +00001612 return;
1613 }
Arthur Hung69f95222023-10-04 07:39:02 +00001614
Vishnu Nairdc83d4b2024-08-15 16:29:20 +00001615 Rect bounds = snapshot->surfaceDamage.getBounds();
Arthur Hungc70bee22023-06-02 01:35:52 +00001616 if (!bounds.isValid()) {
Vishnu Nairdc83d4b2024-08-15 16:29:20 +00001617 snapshot->isSmallDirty = false;
Arthur Hungc70bee22023-06-02 01:35:52 +00001618 return;
1619 }
1620
Arthur Hung69f95222023-10-04 07:39:02 +00001621 // Transform to screen space.
Vishnu Nairdc83d4b2024-08-15 16:29:20 +00001622 bounds = snapshot->localTransform.transform(bounds);
Arthur Hung69f95222023-10-04 07:39:02 +00001623
Arthur Hungc70bee22023-06-02 01:35:52 +00001624 // If the damage region is a small dirty, this could give the hint for the layer history that
1625 // it could suppress the heuristic rate when calculating.
Vishnu Nairdc83d4b2024-08-15 16:29:20 +00001626 snapshot->isSmallDirty =
1627 mFlinger->mScheduler->isSmallDirtyArea(mOwnerAppId,
1628 bounds.getWidth() * bounds.getHeight());
Arthur Hung69f95222023-10-04 07:39:02 +00001629}
1630
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001631} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07001632
1633#if defined(__gl_h_)
1634#error "don't include gl/gl.h in this file"
1635#endif
1636
1637#if defined(__gl2_h_)
1638#error "don't include gl2/gl2.h in this file"
1639#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08001640
1641// TODO(b/129481165): remove the #pragma below and fix conversion issues
1642#pragma clang diagnostic pop // ignored "-Wconversion"