blob: c14769e61e44761b097b8a052ddf3bca5ea6b0ae [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"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070067#include "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;
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500157 mFrameTracker.setDisplayRefreshPeriod(
158 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
188 if (mDrawingState.sidebandStream != nullptr) {
189 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
190 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000191 if (hasTrustedPresentationListener()) {
192 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000193 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000194 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700195}
196
Mathias Agopian13127d82013-03-05 17:47:11 -0800197// ---------------------------------------------------------------------------
Mathias Agopian13127d82013-03-05 17:47:11 -0800198// set-up
199// ---------------------------------------------------------------------------
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700200sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800201 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700202 if (mGetHandleCalled) {
203 ALOGE("Get handle called twice" );
204 return nullptr;
205 }
206 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700207 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000208 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800209}
210
211// ---------------------------------------------------------------------------
212// h/w composer set-up
213// ---------------------------------------------------------------------------
214
Chavi Weingarten076acac2023-01-19 17:20:43 +0000215// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000216void Layer::updateTrustedPresentationState(const DisplayDevice* display,
217 const frontend::LayerSnapshot* snapshot,
218 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000219 if (!hasTrustedPresentationListener()) {
220 return;
221 }
222 const bool lastState = mLastComputedTrustedPresentationState;
223 mLastComputedTrustedPresentationState = false;
224
225 if (!leaveState) {
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000226 const auto outputLayer = findOutputLayerForDisplay(display, snapshot->path);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000227 if (outputLayer != nullptr) {
228 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
229 Region coveredRegion =
230 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
231 mLastComputedTrustedPresentationState =
232 computeTrustedPresentationState(snapshot->geomLayerBounds,
233 snapshot->sourceBounds(), coveredRegion,
234 snapshot->transformedBounds,
235 snapshot->alpha,
236 snapshot->geomLayerTransform,
237 mTrustedPresentationThresholds);
238 } else {
239 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
240 "TrustedPresentationState",
241 getDebugName());
242 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000243 }
244 }
245 const bool newState = mLastComputedTrustedPresentationState;
246 if (lastState && !newState) {
247 // We were in the trusted presentation state, but now we left it,
248 // emit the callback if needed
249 if (mLastReportedTrustedPresentationState) {
250 mLastReportedTrustedPresentationState = false;
251 mTrustedPresentationListener.invoke(false);
252 }
253 // Reset the timer
254 mEnteredTrustedPresentationStateTime = -1;
255 } else if (!lastState && newState) {
256 // We were not in the trusted presentation state, but we entered it, begin the timer
257 // and make sure this gets called at least once more!
258 mEnteredTrustedPresentationStateTime = time_in_ms;
259 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
260 }
261
262 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
263 if (!mLastReportedTrustedPresentationState && newState &&
264 (time_in_ms - mEnteredTrustedPresentationStateTime >
265 mTrustedPresentationThresholds.stabilityRequirementMs)) {
266 mLastReportedTrustedPresentationState = true;
267 mTrustedPresentationListener.invoke(true);
268 }
269}
270
271/**
272 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
273 * of how the parameters and thresholds are interpreted. The general spirit is
274 * to produce an upper bound on the amount of the buffer which was presented.
275 */
276bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
277 const Region& coveredRegion,
278 const FloatRect& screenBounds, float alpha,
279 const ui::Transform& effectiveTransform,
280 const TrustedPresentationThresholds& thresholds) {
281 if (alpha < thresholds.minAlpha) {
282 return false;
283 }
284 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
285 return false;
286 }
287 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
288 return false;
289 }
290
291 const float sx = effectiveTransform.dsdx();
292 const float sy = effectiveTransform.dsdy();
293 float fractionRendered = std::min(sx * sy, 1.0f);
294
295 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
296 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
297 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
298
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000299 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
300 // Compute the size of all the rects since they may be disconnected.
301 float coveredSize = 0;
302 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
303 float size = rect->width() * rect->height();
304 coveredSize += size;
305 }
306
307 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000308
309 if (fractionRendered < thresholds.minFractionRendered) {
310 return false;
311 }
312
313 return true;
314}
315
Vishnu Nair60356342018-11-13 13:00:45 -0800316Rect Layer::getCroppedBufferSize(const State& s) const {
317 Rect size = getBufferSize(s);
Vishnu Naira9123c82024-10-03 03:56:44 +0000318 Rect crop = Rect(getCrop(s));
Vishnu Nair60356342018-11-13 13:00:45 -0800319 if (!crop.isEmpty() && size.isValid()) {
320 size.intersect(crop, &size);
321 } else if (!crop.isEmpty()) {
322 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700323 }
Vishnu Nair60356342018-11-13 13:00:45 -0800324 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800325}
326
Lloyd Piquea83776c2019-01-29 18:42:32 -0800327const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700328 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800329}
330
Mathias Agopian13127d82013-03-05 17:47:11 -0800331// ---------------------------------------------------------------------------
332// drawing...
333// ---------------------------------------------------------------------------
334
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500335aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
336 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700337 const auto outputLayer = findOutputLayerForDisplay(&display);
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000338 return getCompositionType(outputLayer);
339}
340
341aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
342 const compositionengine::OutputLayer* outputLayer) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -0800343 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500344 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800345 }
346 if (outputLayer->getState().hwc) {
347 return (*outputLayer->getState().hwc).hwcCompositionType;
348 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500349 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800350 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800351}
352
Mathias Agopian13127d82013-03-05 17:47:11 -0800353// ----------------------------------------------------------------------------
Mathias Agopian13127d82013-03-05 17:47:11 -0800354// transaction
355// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800356
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700357void Layer::commitTransaction() {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000358 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
359 // bufferSurfaceFrameTX will be presented in latchBuffer.
360 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
361 if (surfaceFrame->getPresentState() != PresentState::Presented) {
362 // With applyPendingStates, we could end up having presented surfaceframes from previous
363 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800364 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000365 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
366 }
367 }
Robert Carr6a160312021-05-17 12:08:20 -0700368 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700369}
370
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700371void Layer::setTransactionFlags(uint32_t mask) {
372 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800373}
374
Vishnu Naira9123c82024-10-03 03:56:44 +0000375bool Layer::setCrop(const FloatRect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +0000376 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -0700377 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -0700378 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -0700379
Sally Qi81d95e62022-03-21 19:41:33 -0700380 setTransactionFlags(eTransactionNeeded);
381 return true;
382}
383
Ady Abrahamaae5ed52020-06-26 09:32:43 -0700384bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
385 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
386};
387
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000388void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
Vishnu Nair39a74a92024-07-29 19:01:50 +0000389 nsecs_t postTime, gui::GameMode gameMode) {
Robert Carr6a160312021-05-17 12:08:20 -0700390 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000391
392 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
393 // there are two transactions with the same token, the first one without a buffer and the
394 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
395 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -0700396 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
397 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000398 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -0700399 mDrawingState.bufferSurfaceFrameTX = it->second;
400 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
401 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
402 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000403 } else {
Robert Carr6a160312021-05-17 12:08:20 -0700404 mDrawingState.bufferSurfaceFrameTX =
Vishnu Nair39a74a92024-07-29 19:01:50 +0000405 createSurfaceFrameForBuffer(info, postTime, mTransactionName, gameMode);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000406 }
Ady Abraham5a3e3562023-06-07 10:32:08 -0700407
Vishnu Nair39a74a92024-07-29 19:01:50 +0000408 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName, gameMode);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000409}
410
411void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
Vishnu Nair39a74a92024-07-29 19:01:50 +0000412 nsecs_t postTime,
413 gui::GameMode gameMode) {
Robert Carr6a160312021-05-17 12:08:20 -0700414 mDrawingState.frameTimelineInfo = info;
415 mDrawingState.postTime = postTime;
Ady Abraham22c7b5c2020-09-22 19:33:40 -0700416 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000417
Robert Carr6a160312021-05-17 12:08:20 -0700418 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000419 bufferSurfaceFrameTX != nullptr) {
420 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
421 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
422 // being used for BufferSurfaceFrame, don't create a new one.
423 return;
424 }
425 }
426 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
427 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
428 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -0700429 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
430 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Vishnu Nair39a74a92024-07-29 19:01:50 +0000431 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime, gameMode);
Robert Carr6a160312021-05-17 12:08:20 -0700432 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000433 } else {
434 if (it->second->getPresentState() == PresentState::Presented) {
435 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
436 // have been from previous vsync.
Vishnu Nair39a74a92024-07-29 19:01:50 +0000437 it->second = createSurfaceFrameForTransaction(info, postTime, gameMode);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000438 }
439 }
Ady Abraham5a3e3562023-06-07 10:32:08 -0700440
Vishnu Nair39a74a92024-07-29 19:01:50 +0000441 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName, gameMode);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000442}
443
444void Layer::addSurfaceFrameDroppedForBuffer(
Ady Abraham5a3e3562023-06-07 10:32:08 -0700445 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t dropTime) {
446 surfaceFrame->setDropTime(dropTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000447 surfaceFrame->setPresentState(PresentState::Dropped);
448 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
449}
450
451void Layer::addSurfaceFramePresentedForBuffer(
452 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
453 nsecs_t currentLatchTime) {
454 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
455 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
456 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +0000457 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000458}
459
460std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
Vishnu Nair39a74a92024-07-29 19:01:50 +0000461 const FrameTimelineInfo& info, nsecs_t postTime, gui::GameMode gameMode) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000462 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -0800463 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
464 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000465 mTransactionName,
Vishnu Nair39a74a92024-07-29 19:01:50 +0000466 /*isBuffer*/ false, gameMode);
Rachel Leeed511ef2021-10-11 15:09:51 -0700467 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000468 // For Transactions, the post time is considered to be both queue and acquire fence time.
469 surfaceFrame->setActualQueueTime(postTime);
470 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800471 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
472 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -0800473 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800474 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000475 return surfaceFrame;
476}
477
478std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
Vishnu Nair39a74a92024-07-29 19:01:50 +0000479 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName,
480 gui::GameMode gameMode) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000481 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -0800482 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000483 getSequence(), mName, debugName,
Vishnu Nair39a74a92024-07-29 19:01:50 +0000484 /*isBuffer*/ true, gameMode);
Rachel Leeed511ef2021-10-11 15:09:51 -0700485 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000486 // For buffers, acquire fence time will set during latch.
487 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800488 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
489 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -0800490 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800491 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000492 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -0700493}
494
Ady Abraham5a3e3562023-06-07 10:32:08 -0700495void Layer::setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
Vishnu Nair39a74a92024-07-29 19:01:50 +0000496 std::string debugName, gui::GameMode gameMode) {
Ady Abraham5a3e3562023-06-07 10:32:08 -0700497 if (info.skippedFrameVsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
498 return;
499 }
500
501 FrameTimelineInfo skippedFrameTimelineInfo = info;
502 skippedFrameTimelineInfo.vsyncId = info.skippedFrameVsyncId;
503
504 auto surfaceFrame =
505 mFlinger->mFrameTimeline->createSurfaceFrameForToken(skippedFrameTimelineInfo,
506 mOwnerPid, mOwnerUid,
507 getSequence(), mName, debugName,
Vishnu Nair39a74a92024-07-29 19:01:50 +0000508 /*isBuffer*/ false, gameMode);
Ady Abraham5a3e3562023-06-07 10:32:08 -0700509 surfaceFrame->setActualStartTime(skippedFrameTimelineInfo.skippedFrameStartTimeNanos);
510 // For Transactions, the post time is considered to be both queue and acquire fence time.
511 surfaceFrame->setActualQueueTime(postTime);
512 surfaceFrame->setAcquireFenceTime(postTime);
513 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
514 if (fps) {
515 surfaceFrame->setRenderRate(*fps);
516 }
Ady Abraham5a3e3562023-06-07 10:32:08 -0700517 addSurfaceFrameDroppedForBuffer(surfaceFrame, postTime);
518}
519
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700520bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps,
521 nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000522 if (mDrawingState.frameRateForLayerTree == frameRate) {
523 return false;
524 }
525
526 mDrawingState.frameRateForLayerTree = frameRate;
527 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700528 ->recordLayerHistory(sequence, layerProps, now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000529 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -0700530 return true;
Steven Thomas3172e202020-01-06 19:25:30 -0800531}
532
Ady Abraham59fd8ff2021-04-15 20:13:30 -0700533Layer::FrameRate Layer::getFrameRateForLayerTree() const {
534 return getDrawingState().frameRateForLayerTree;
535}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800536
Mathias Agopian13127d82013-03-05 17:47:11 -0800537// ----------------------------------------------------------------------------
538// debugging
539// ----------------------------------------------------------------------------
540
Yiwei Zhang5434a782018-12-05 18:06:32 -0800541void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100542 result.append(kDumpTableRowLength, '-');
543 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -0700544 result.append(" Layer name\n");
545 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700546 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -0700547 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +0800548 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -0700549 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -0700550 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100551 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
552 result.append(kDumpTableRowLength, '-');
553 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -0700554}
555
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000556void Layer::miniDump(std::string& result, const frontend::LayerSnapshot& snapshot,
557 const DisplayDevice& display) const {
558 const auto outputLayer = findOutputLayerForDisplay(&display, snapshot.path);
559 if (!outputLayer) {
560 return;
561 }
562
563 StringAppendF(&result, " %s\n", snapshot.debugName.c_str());
564 StringAppendF(&result, " %10zu | ", snapshot.globalZ);
565 StringAppendF(&result, " %10d | ",
566 snapshot.layerMetadata.getInt32(gui::METADATA_WINDOW_TYPE, 0));
567 StringAppendF(&result, "%10s | ", toString(getCompositionType(outputLayer)).c_str());
568 const auto& outputLayerState = outputLayer->getState();
569 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
570 const Rect& frame = outputLayerState.displayFrame;
571 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
572 const FloatRect& crop = outputLayerState.sourceCrop;
573 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
574 crop.bottom);
575 const auto frameRate = snapshot.frameRate;
Ady Abraham77d406d2023-11-22 15:00:23 -0800576 std::string frameRateStr;
577 if (frameRate.vote.rate.isValid()) {
578 StringAppendF(&frameRateStr, "%.2f", frameRate.vote.rate.getValue());
579 }
Rachel Leece6e0042023-06-27 11:22:54 -0700580 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
Ady Abraham77d406d2023-11-22 15:00:23 -0800581 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
Rachel Leece6e0042023-06-27 11:22:54 -0700582 ftl::enum_string(frameRate.vote.type).c_str(),
583 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abraham77d406d2023-11-22 15:00:23 -0800584 } else if (frameRate.category != FrameRateCategory::Default) {
585 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
586 (std::string("Cat::") + ftl::enum_string(frameRate.category)).c_str(),
587 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000588 } else {
589 result.append(41, ' ');
590 }
591
592 const auto focused = isLayerFocusedBasedOnPriority(snapshot.frameRateSelectionPriority);
593 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
594
595 result.append(kDumpTableRowLength, '-');
596 result.append("\n");
597}
598
Yiwei Zhang5434a782018-12-05 18:06:32 -0800599void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -0700600 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -0800601}
602
Svetoslavd85084b2014-03-20 10:28:31 -0700603void Layer::clearFrameStats() {
604 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -0800605}
606
Svetoslavd85084b2014-03-20 10:28:31 -0700607void Layer::getFrameStats(FrameStats* outStats) const {
608 mFrameTracker.getStats(outStats);
609}
610
Brian Anderson5ea5e592016-12-01 16:54:33 -0800611void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800612 const int32_t layerId = getSequence();
613 mFlinger->mTimeStats->onDestroy(layerId);
614 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -0800615}
616
Kean Mariotti4ba343c2023-04-19 13:31:02 +0000617void Layer::writeCompositionStateToProto(perfetto::protos::LayerProto* layerProto,
618 ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +0000619 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +0000620 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +0000621
622 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +0000623 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +0000624 const auto compositionType = getCompositionType(*display);
Kean Mariotti4ba343c2023-04-19 13:31:02 +0000625 layerProto->set_hwc_composition_type(
626 static_cast<perfetto::protos::HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +0000627 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +0000628 [&]() { return layerProto->mutable_visible_region(); });
629 }
630}
631
Lloyd Pique37c2c9b2018-12-04 17:25:10 -0800632compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700633 const DisplayDevice* display) const {
634 if (!display) return nullptr;
Vishnu Naird47bcee2023-02-24 18:08:51 +0000635 sp<LayerFE> layerFE;
636 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
637 for (auto& [p, layer] : mLayerFEs) {
638 if (p == path) {
639 layerFE = layer;
640 }
641 }
642
643 if (!layerFE) return nullptr;
644 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -0800645}
646
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000647compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
648 const DisplayDevice* display, const frontend::LayerHierarchy::TraversalPath& path) const {
649 if (!display) return nullptr;
650 sp<LayerFE> layerFE;
651 for (auto& [p, layer] : mLayerFEs) {
652 if (p == path) {
653 layerFE = layer;
654 }
655 }
656
657 if (!layerFE) return nullptr;
658 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
659}
660
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700661Region Layer::getVisibleRegion(const DisplayDevice* display) const {
662 const auto outputLayer = findOutputLayerForDisplay(display);
663 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -0800664}
665
Patrick Williamsbb25f802022-08-30 23:02:34 +0000666void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
667 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +0800668 const sp<Fence>& releaseFence) {
Patrick Williams7c9fa272024-08-30 12:38:43 +0000669 if (!listener && !mBufferReleaseChannel) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000670 return;
671 }
Patrick Williams7c9fa272024-08-30 12:38:43 +0000672
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000673 SFTRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
Patrick Williams7c9fa272024-08-30 12:38:43 +0000674
675 ReleaseCallbackId callbackId{buffer->getId(), framenumber};
676 const sp<Fence>& fence = releaseFence ? releaseFence : Fence::NO_FENCE;
liulijuneb489f62022-10-17 22:02:14 +0800677 uint32_t currentMaxAcquiredBufferCount =
678 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Patrick Williams7c9fa272024-08-30 12:38:43 +0000679
680 if (listener) {
681 listener->onReleaseBuffer(callbackId, fence, currentMaxAcquiredBufferCount);
682 }
683
684 if (mBufferReleaseChannel) {
685 mBufferReleaseChannel->writeReleaseFence(callbackId, fence, currentMaxAcquiredBufferCount);
686 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000687}
688
Melody Hsu793f8362024-01-08 20:00:35 +0000689sp<CallbackHandle> Layer::findCallbackHandle() {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000690 // If we are displayed on multiple displays in a single composition cycle then we would
691 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
692 // For example we can only use it if all the displays are client comp, and we need
693 // to merge all the client comp fences. We could do this, but for now we just
694 // disable the optimization when a layer is composed on multiple displays.
695 if (mClearClientCompositionFenceOnLayerDisplayed) {
696 mLastClientCompositionFence = nullptr;
697 } else {
698 mClearClientCompositionFenceOnLayerDisplayed = true;
699 }
700
701 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
702 // buffer that was presented on this layer. The first transaction that came in this frame that
703 // replaced the previous buffer on this layer needs this release fence, because the fence will
704 // let the client know when that previous buffer is removed from the screen.
705 //
706 // Every other transaction on this layer does not need a release fence because no other
707 // Transactions that were set on this layer this frame are going to have their preceding buffer
708 // removed from the display this frame.
709 //
710 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
711 // buffer so it doesn't need a previous release fence because the layer still needs the previous
712 // buffer. The second transaction contains a buffer so it needs a previous release fence because
713 // the previous buffer will be released this frame. The third transaction also contains a
714 // buffer. It replaces the buffer in the second transaction. The buffer in the second
715 // transaction will now no longer be presented so it is released immediately and the third
716 // transaction doesn't need a previous release fence.
717 sp<CallbackHandle> ch;
718 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -0700719 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000720 ch = handle;
721 break;
722 }
723 }
Melody Hsu793f8362024-01-08 20:00:35 +0000724 return ch;
725}
726
727void Layer::prepareReleaseCallbacks(ftl::Future<FenceResult> futureFenceResult,
728 ui::LayerStack layerStack) {
729 sp<CallbackHandle> ch = findCallbackHandle();
730
731 if (ch != nullptr) {
732 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
733 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
734 ch->name = mName;
735 } else {
Melody Hsue4ef87f2024-03-26 23:54:45 +0000736 // If we didn't get a release callback yet (e.g. some scenarios when capturing
737 // screenshots asynchronously) then make sure we don't drop the fence.
738 // Older fences for the same layer stack can be dropped when a new fence arrives.
739 // An assumption here is that RenderEngine performs work sequentially, so an
740 // incoming fence will not fire before an existing fence.
741 mAdditionalPreviousReleaseFences.emplace_or_replace(layerStack,
742 std::move(futureFenceResult));
Melody Hsu793f8362024-01-08 20:00:35 +0000743 }
744
745 if (mBufferInfo.mBuffer) {
746 mPreviouslyPresentedLayerStacks.push_back(layerStack);
747 }
748
749 if (mDrawingState.frameNumber > 0) {
750 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
751 }
752}
753
754void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
755 ui::LayerStack layerStack,
756 std::function<FenceResult(FenceResult)>&& continuation) {
757 sp<CallbackHandle> ch = findCallbackHandle();
Alec Mouri9892aac2023-12-11 21:16:59 +0000758
759 if (!FlagManager::getInstance().screenshot_fence_preservation() && continuation) {
760 futureFenceResult = ftl::Future(futureFenceResult).then(std::move(continuation)).share();
761 }
762
Patrick Williamsbb25f802022-08-30 23:02:34 +0000763 if (ch != nullptr) {
764 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
Melody Hsu793f8362024-01-08 20:00:35 +0000765 ch->previousSharedReleaseFences.emplace_back(std::move(futureFenceResult));
Patrick Williamsbb25f802022-08-30 23:02:34 +0000766 ch->name = mName;
Alec Mouri9892aac2023-12-11 21:16:59 +0000767 } else if (FlagManager::getInstance().screenshot_fence_preservation()) {
768 // If we didn't get a release callback yet, e.g. some scenarios when capturing screenshots
769 // asynchronously, then make sure we don't drop the fence.
Melody Hsu793f8362024-01-08 20:00:35 +0000770 mPreviousReleaseFenceAndContinuations.emplace_back(std::move(futureFenceResult),
771 std::move(continuation));
Alec Mouri9892aac2023-12-11 21:16:59 +0000772 std::vector<FenceAndContinuation> mergedFences;
773 sp<Fence> prevFence = nullptr;
774 // For a layer that's frequently screenshotted, try to merge fences to make sure we don't
775 // grow unbounded.
Melody Hsu793f8362024-01-08 20:00:35 +0000776 for (const auto& futureAndContinuation : mPreviousReleaseFenceAndContinuations) {
777 auto result = futureAndContinuation.future.wait_for(0s);
Alec Mouri9892aac2023-12-11 21:16:59 +0000778 if (result != std::future_status::ready) {
Melody Hsu793f8362024-01-08 20:00:35 +0000779 mergedFences.emplace_back(futureAndContinuation);
Alec Mouri9892aac2023-12-11 21:16:59 +0000780 continue;
781 }
782
Melody Hsu793f8362024-01-08 20:00:35 +0000783 mergeFence(getDebugName(),
784 futureAndContinuation.chain().get().value_or(Fence::NO_FENCE), prevFence);
Alec Mouri9892aac2023-12-11 21:16:59 +0000785 }
786 if (prevFence != nullptr) {
787 mergedFences.emplace_back(ftl::yield(FenceResult(std::move(prevFence))).share());
788 }
789
Melody Hsu793f8362024-01-08 20:00:35 +0000790 mPreviousReleaseFenceAndContinuations.swap(mergedFences);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000791 }
Alec Mouri9892aac2023-12-11 21:16:59 +0000792
Vishnu Nair316b7f42023-10-13 23:44:46 +0000793 if (mBufferInfo.mBuffer) {
794 mPreviouslyPresentedLayerStacks.push_back(layerStack);
795 }
Alec Mouri21d94322023-10-17 19:51:39 +0000796
797 if (mDrawingState.frameNumber > 0) {
798 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
799 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000800}
801
Patrick Williamsbb25f802022-08-30 23:02:34 +0000802void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
803 for (const auto& handle : mDrawingState.callbackHandles) {
Patrick Williams7c9fa272024-08-30 12:38:43 +0000804 handle->bufferReleaseChannel = mBufferReleaseChannel;
Melody Hsu9af30702024-04-17 18:23:43 +0000805 handle->transformHint = mTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000806 handle->dequeueReadyTime = dequeueReadyTime;
807 handle->currentMaxAcquiredBufferCount =
808 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000809 SFTRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
810 handle->previousReleaseCallbackId.framenumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000811 }
812
813 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -0700814 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000815 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
816 break;
817 }
818 }
819
Pascal Mütschardd56514e2024-05-24 17:37:13 +0200820 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000821 mDrawingState.callbackHandles = {};
822}
823
Patrick Williamsbb25f802022-08-30 23:02:34 +0000824bool Layer::setTransform(uint32_t transform) {
825 if (mDrawingState.bufferTransform == transform) return false;
826 mDrawingState.bufferTransform = transform;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000827 setTransactionFlags(eTransactionNeeded);
828 return true;
829}
830
831bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
832 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
833 mDrawingState.sequence++;
834 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000835 setTransactionFlags(eTransactionNeeded);
836 return true;
837}
838
Dorin Drimuse5374e52023-08-02 17:52:43 +0000839void Layer::releasePreviousBuffer() {
840 mReleasePreviousBuffer = true;
841 if (!mBufferInfo.mBuffer ||
842 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
843 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
844 // If mDrawingState has a buffer, and we are about to update again
845 // before swapping to drawing state, then the first buffer will be
846 // dropped and we should decrement the pending buffer count and
847 // call any release buffer callbacks if set.
848 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
849 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
850 mDrawingState.acquireFence);
Dominic Lemire95c4ecc2024-07-09 12:06:18 -0700851 const int32_t layerId = getSequence();
852 mFlinger->mTimeStats->removeTimeRecord(layerId, mDrawingState.frameNumber);
Dorin Drimuse5374e52023-08-02 17:52:43 +0000853 decrementPendingBufferCount();
854 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
855 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
856 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX, systemTime());
857 mDrawingState.bufferSurfaceFrameTX.reset();
858 }
859 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
860 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
861 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
862 mLastClientCompositionFence);
863 mLastClientCompositionFence = nullptr;
864 }
865}
866
Vishnu Nair7ee4f462023-04-19 09:54:09 -0700867void Layer::resetDrawingStateBufferInfo() {
868 mDrawingState.producerId = 0;
869 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +0000870 mDrawingState.previousFrameNumber = 0;
Vishnu Nair7ee4f462023-04-19 09:54:09 -0700871 mDrawingState.releaseBufferListener = nullptr;
872 mDrawingState.buffer = nullptr;
873 mDrawingState.acquireFence = sp<Fence>::make(-1);
874 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
875 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
876 mDrawingState.releaseBufferEndpoint = nullptr;
877}
878
Patrick Williamsbb25f802022-08-30 23:02:34 +0000879bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
880 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
Vishnu Nair39a74a92024-07-29 19:01:50 +0000881 bool isAutoTimestamp, const FrameTimelineInfo& info, gui::GameMode gameMode) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000882 SFTRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +0000883
884 const bool frameNumberChanged =
885 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
886 const uint64_t frameNumber =
887 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000888 SFTRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000889
890 if (mDrawingState.buffer) {
Dorin Drimuse5374e52023-08-02 17:52:43 +0000891 releasePreviousBuffer();
Vishnu Nair7ee4f462023-04-19 09:54:09 -0700892 } else if (buffer) {
Vishnu Nairc09c0232023-03-02 03:22:35 +0000893 // if we are latching a buffer for the first time then clear the mLastLatchTime since
894 // we don't want to incorrectly classify a frame if we miss the desired present time.
895 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000896 }
897
Vishnu Nair7ee4f462023-04-19 09:54:09 -0700898 mDrawingState.desiredPresentTime = desiredPresentTime;
899 mDrawingState.isAutoTimestamp = isAutoTimestamp;
900 mDrawingState.latchedVsyncId = info.vsyncId;
Ady Abraham55269162023-05-09 11:26:06 -0700901 mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
Vishnu Nair7ee4f462023-04-19 09:54:09 -0700902 if (!buffer) {
903 resetDrawingStateBufferInfo();
904 setTransactionFlags(eTransactionNeeded);
905 mDrawingState.bufferSurfaceFrameTX = nullptr;
Vishnu Nair39a74a92024-07-29 19:01:50 +0000906 setFrameTimelineVsyncForBufferlessTransaction(info, postTime, gameMode);
Vishnu Nair7ee4f462023-04-19 09:54:09 -0700907 return true;
Dorin Drimuse5374e52023-08-02 17:52:43 +0000908 } else {
909 // release sideband stream if it exists and a non null buffer is being set
910 if (mDrawingState.sidebandStream != nullptr) {
Vishnu Nair39a74a92024-07-29 19:01:50 +0000911 setSidebandStream(nullptr, info, postTime, gameMode);
Dorin Drimuse5374e52023-08-02 17:52:43 +0000912 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -0700913 }
914
Vishnu Naird1f74982023-06-15 20:16:51 -0700915 if ((mDrawingState.producerId > bufferData.producerId) ||
916 ((mDrawingState.producerId == bufferData.producerId) &&
917 (mDrawingState.frameNumber > frameNumber))) {
918 ALOGE("Out of order buffers detected for %s producedId=%d frameNumber=%" PRIu64
919 " -> producedId=%d frameNumber=%" PRIu64,
920 getDebugName(), mDrawingState.producerId, mDrawingState.frameNumber,
921 bufferData.producerId, frameNumber);
922 TransactionTraceWriter::getInstance().invoke("out_of_order_buffers_", /*overwrite=*/false);
923 }
924
liulijuneb489f62022-10-17 22:02:14 +0800925 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -0700926 mDrawingState.barrierProducerId =
927 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000928 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -0700929 mDrawingState.barrierFrameNumber =
930 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
931
Patrick Williamsbb25f802022-08-30 23:02:34 +0000932 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
933 mDrawingState.buffer = std::move(buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000934 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
935 ? bufferData.acquireFence
936 : Fence::NO_FENCE;
937 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
938 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
939 // We latched this buffer unsiganled, so we need to pass the acquire fence
940 // on the callback instead of just the acquire time, since it's unknown at
941 // this point.
942 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
943 } else {
944 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
945 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000946 setTransactionFlags(eTransactionNeeded);
947
948 const int32_t layerId = getSequence();
949 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
Vishnu Nair39a74a92024-07-29 19:01:50 +0000950 mOwnerUid, postTime, gameMode);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000951
Vishnu Nair39a74a92024-07-29 19:01:50 +0000952 setFrameTimelineVsyncForBufferTransaction(info, postTime, gameMode);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000953
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900954 if (bufferData.dequeueTime > 0) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000955 const uint64_t bufferId = mDrawingState.buffer->getId();
956 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900957 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber,
958 bufferData.dequeueTime,
Patrick Williamsbb25f802022-08-30 23:02:34 +0000959 FrameTracer::FrameEvent::DEQUEUE);
960 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
961 FrameTracer::FrameEvent::QUEUE);
962 }
963
964 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
Arthur Hungc70bee22023-06-02 01:35:52 +0000965
966 // If the layer had been updated a TextureView, this would make sure the present time could be
967 // same to TextureView update when it's a small dirty, and get the correct heuristic rate.
Jerry Chang36678002023-11-29 16:56:17 +0000968 if (mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +0000969 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
970 mUsedVsyncIdForRefreshRateSelection = true;
971 }
972 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000973 return true;
974}
975
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000976void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
977 mDrawingState.desiredPresentTime = desiredPresentTime;
978 mDrawingState.isAutoTimestamp = isAutoTimestamp;
979}
980
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700981void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps, nsecs_t now) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000982 SFTRACE_CALL();
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000983 const nsecs_t presentTime = [&] {
Ady Abraham55269162023-05-09 11:26:06 -0700984 if (!mDrawingState.isAutoTimestamp) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000985 SFTRACE_FORMAT_INSTANT("desiredPresentTime");
Ady Abraham55269162023-05-09 11:26:06 -0700986 return mDrawingState.desiredPresentTime;
987 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000988
Ady Abraham55269162023-05-09 11:26:06 -0700989 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
990 const auto prediction =
991 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
992 mDrawingState.latchedVsyncId);
993 if (prediction.has_value()) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000994 SFTRACE_FORMAT_INSTANT("predictedPresentTime");
Arthur Hungc70bee22023-06-02 01:35:52 +0000995 mMaxTimeForUseVsyncId = prediction->presentTime +
996 scheduler::LayerHistory::kMaxPeriodForHistory.count();
Ady Abraham55269162023-05-09 11:26:06 -0700997 return prediction->presentTime;
998 }
999 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001000
Jerry Chang36678002023-11-29 16:56:17 +00001001 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00001002 return static_cast<nsecs_t>(0);
1003 }
1004
1005 // If the layer is not an application and didn't set an explicit rate or desiredPresentTime,
1006 // return "0" to tell the layer history that it will use the max refresh rate without
1007 // calculating the adaptive rate.
1008 if (mWindowType != WindowInfo::Type::APPLICATION &&
1009 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
1010 return static_cast<nsecs_t>(0);
1011 }
1012
1013 // Return the valid present time only when the layer potentially updated a TextureView so
1014 // LayerHistory could heuristically calculate the rate if the UI is continually updating.
1015 if (mUsedVsyncIdForRefreshRateSelection) {
1016 const auto prediction =
1017 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
1018 mDrawingState.latchedVsyncId);
1019 if (prediction.has_value()) {
1020 if (mMaxTimeForUseVsyncId >= prediction->presentTime) {
1021 return prediction->presentTime;
1022 }
1023 mUsedVsyncIdForRefreshRateSelection = false;
1024 }
1025 }
1026
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001027 return static_cast<nsecs_t>(0);
1028 }();
Ady Abraham55269162023-05-09 11:26:06 -07001029
Vishnu Nair2665ca92024-07-09 22:08:15 +00001030 if (SFTRACE_ENABLED() && presentTime > 0) {
Ady Abraham55269162023-05-09 11:26:06 -07001031 const auto presentIn = TimePoint::fromNs(presentTime) - TimePoint::now();
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001032 SFTRACE_FORMAT_INSTANT("presentIn %s", to_string(presentIn).c_str());
Ady Abraham55269162023-05-09 11:26:06 -07001033 }
1034
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001035 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001036 scheduler::LayerHistory::LayerUpdateType::Buffer);
1037}
1038
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001039void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps, nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001040 const nsecs_t presentTime =
1041 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001042 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001043 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
1044}
1045
Patrick Williamsbb25f802022-08-30 23:02:34 +00001046bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00001047 if (mDrawingState.dataspace == dataspace) return false;
1048 mDrawingState.dataspace = dataspace;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001049 setTransactionFlags(eTransactionNeeded);
1050 return true;
1051}
1052
John Reck68796592023-01-25 13:47:12 -05001053bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07001054 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
1055 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05001056 return false;
Sally Qi963049b2023-03-23 14:06:21 -07001057 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
1058 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05001059 setTransactionFlags(eTransactionNeeded);
1060 return true;
1061}
1062
Alec Mouri1b0d4e12024-02-12 22:27:19 +00001063bool Layer::setDesiredHdrHeadroom(float desiredRatio) {
1064 if (mDrawingState.desiredHdrSdrRatio == desiredRatio) return false;
1065 mDrawingState.desiredHdrSdrRatio = desiredRatio;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001066 setTransactionFlags(eTransactionNeeded);
1067 return true;
1068}
1069
Dorin Drimuse5374e52023-08-02 17:52:43 +00001070bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream, const FrameTimelineInfo& info,
Vishnu Nair39a74a92024-07-29 19:01:50 +00001071 nsecs_t postTime, gui::GameMode gameMode) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00001072 if (mDrawingState.sidebandStream == sidebandStream) return false;
1073
1074 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
1075 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
1076 } else if (sidebandStream != nullptr) {
1077 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
1078 }
1079
1080 mDrawingState.sidebandStream = sidebandStream;
Dorin Drimuse5374e52023-08-02 17:52:43 +00001081 if (sidebandStream != nullptr && mDrawingState.buffer != nullptr) {
1082 releasePreviousBuffer();
1083 resetDrawingStateBufferInfo();
1084 mDrawingState.bufferSurfaceFrameTX = nullptr;
Vishnu Nair39a74a92024-07-29 19:01:50 +00001085 setFrameTimelineVsyncForBufferlessTransaction(info, postTime, gameMode);
Dorin Drimuse5374e52023-08-02 17:52:43 +00001086 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00001087 setTransactionFlags(eTransactionNeeded);
1088 if (!mSidebandStreamChanged.exchange(true)) {
1089 // mSidebandStreamChanged was false
1090 mFlinger->onLayerUpdate();
1091 }
1092 return true;
1093}
1094
Vishnu Nair3af0ec02023-02-10 04:13:48 +00001095bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
1096 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00001097 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
1098 if (handles.empty()) {
1099 mReleasePreviousBuffer = false;
1100 return false;
1101 }
1102
Pascal Muetschard81cef292023-02-06 12:18:52 +01001103 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001104 for (const auto& handle : handles) {
1105 // If this transaction set a buffer on this layer, release its previous buffer
1106 handle->releasePreviousBuffer = mReleasePreviousBuffer;
1107
1108 // If this layer will be presented in this frame
1109 if (willPresent) {
1110 // If this transaction set an acquire fence on this layer, set its acquire time
1111 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
1112 handle->frameNumber = mDrawingState.frameNumber;
Alec Mouri21d94322023-10-17 19:51:39 +00001113 handle->previousFrameNumber = mDrawingState.previousFrameNumber;
Melody Hsu793f8362024-01-08 20:00:35 +00001114 if (FlagManager::getInstance().ce_fence_promise() &&
Alec Mouri9892aac2023-12-11 21:16:59 +00001115 mPreviousReleaseBufferEndpoint == handle->listener) {
Melody Hsue4ef87f2024-03-26 23:54:45 +00001116 // Add fence from previous screenshot now so that it can be dispatched to the
Alec Mouri9892aac2023-12-11 21:16:59 +00001117 // client.
Melody Hsue4ef87f2024-03-26 23:54:45 +00001118 for (auto& [_, future] : mAdditionalPreviousReleaseFences) {
1119 handle->previousReleaseFences.emplace_back(std::move(future));
Alec Mouri9892aac2023-12-11 21:16:59 +00001120 }
1121 mAdditionalPreviousReleaseFences.clear();
Melody Hsu793f8362024-01-08 20:00:35 +00001122 } else if (FlagManager::getInstance().screenshot_fence_preservation() &&
1123 mPreviousReleaseBufferEndpoint == handle->listener) {
1124 // Add fences from previous screenshots now so that they can be dispatched to the
1125 // client.
1126 for (const auto& futureAndContinution : mPreviousReleaseFenceAndContinuations) {
1127 handle->previousSharedReleaseFences.emplace_back(futureAndContinution.chain());
1128 }
1129 mPreviousReleaseFenceAndContinuations.clear();
Alec Mouri9892aac2023-12-11 21:16:59 +00001130 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00001131 // Store so latched time and release fence can be set
1132 mDrawingState.callbackHandles.push_back(handle);
1133
1134 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01001135 // Queue this handle to be notified below.
1136 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00001137 }
1138 }
1139
Pascal Muetschard81cef292023-02-06 12:18:52 +01001140 if (!remainingHandles.empty()) {
1141 // Notify the transaction completed threads these handles are done. These are only the
1142 // handles that were not added to the mDrawingState, which will be notified later.
Pascal Mütschardd56514e2024-05-24 17:37:13 +02001143 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles);
Pascal Muetschard81cef292023-02-06 12:18:52 +01001144 }
1145
Patrick Williamsbb25f802022-08-30 23:02:34 +00001146 mReleasePreviousBuffer = false;
1147 mCallbackHandleAcquireTimeOrFence = -1;
1148
1149 return willPresent;
1150}
1151
1152Rect Layer::getBufferSize(const State& /*s*/) const {
1153 // for buffer state layers we use the display frame size as the buffer size.
1154
1155 if (mBufferInfo.mBuffer == nullptr) {
1156 return Rect::INVALID_RECT;
1157 }
1158
1159 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
1160 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
1161
1162 // Undo any transformations on the buffer and return the result.
1163 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
1164 std::swap(bufWidth, bufHeight);
1165 }
1166
1167 if (getTransformToDisplayInverse()) {
Leon Scroggins III85d4b222023-05-09 13:58:18 -04001168 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00001169 if (invTransform & ui::Transform::ROT_90) {
1170 std::swap(bufWidth, bufHeight);
1171 }
1172 }
1173
1174 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
1175}
1176
Patrick Williamsbb25f802022-08-30 23:02:34 +00001177bool Layer::fenceHasSignaled() const {
1178 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
1179 return true;
1180 }
1181
1182 const bool fenceSignaled =
1183 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
1184 if (!fenceSignaled) {
1185 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
1186 TimeStats::LatchSkipReason::LateAcquire);
1187 }
1188
1189 return fenceSignaled;
1190}
1191
Vishnu Nair3af0ec02023-02-10 04:13:48 +00001192void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00001193 for (const auto& handle : mDrawingState.callbackHandles) {
1194 handle->refreshStartTime = refreshStartTime;
1195 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00001196}
1197
Patrick Williamsbb25f802022-08-30 23:02:34 +00001198bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00001199 if (mSidebandStreamChanged.exchange(false)) {
1200 const State& s(getDrawingState());
1201 // mSidebandStreamChanged was true
1202 mSidebandStream = s.sidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001203 if (mSidebandStream != nullptr) {
1204 setTransactionFlags(eTransactionNeeded);
1205 mFlinger->setTransactionFlags(eTraversalNeeded);
1206 }
1207 recomputeVisibleRegions = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001208 return true;
1209 }
1210 return false;
1211}
1212
Vishnu Naird47bcee2023-02-24 18:08:51 +00001213void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00001214 const State& s(getDrawingState());
1215
1216 if (!s.buffer) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07001217 if (bgColorOnly || mBufferInfo.mBuffer) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00001218 for (auto& handle : mDrawingState.callbackHandles) {
1219 handle->latchTime = latchTime;
1220 }
1221 }
1222 return;
1223 }
1224
1225 for (auto& handle : mDrawingState.callbackHandles) {
1226 if (handle->frameNumber == mDrawingState.frameNumber) {
1227 handle->latchTime = latchTime;
1228 }
1229 }
1230
1231 const int32_t layerId = getSequence();
1232 const uint64_t bufferId = mDrawingState.buffer->getId();
1233 const uint64_t frameNumber = mDrawingState.frameNumber;
1234 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
1235 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
1236 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
1237
1238 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
1239 FrameTracer::FrameEvent::ACQUIRE_FENCE);
1240 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
1241 FrameTracer::FrameEvent::LATCH);
1242
1243 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
1244 if (bufferSurfaceFrame != nullptr &&
1245 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
1246 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
1247 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
1248 // are processing the next state.
1249 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
1250 mDrawingState.acquireFenceTime->getSignalTime(),
1251 latchTime);
1252 mDrawingState.bufferSurfaceFrameTX.reset();
1253 }
1254
1255 std::deque<sp<CallbackHandle>> remainingHandles;
1256 mFlinger->getTransactionCallbackInvoker()
1257 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
1258 mDrawingState.callbackHandles = remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001259}
1260
1261void Layer::gatherBufferInfo() {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07001262 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
1263 mPreviousReleaseBufferEndpoint = mBufferInfo.mReleaseBufferEndpoint;
1264 if (!mDrawingState.buffer) {
1265 mBufferInfo = {};
1266 return;
1267 }
1268
1269 if ((!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer))) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00001270 decrementPendingBufferCount();
1271 }
1272
Patrick Williamsbb25f802022-08-30 23:02:34 +00001273 mBufferInfo.mBuffer = mDrawingState.buffer;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07001274 mBufferInfo.mReleaseBufferEndpoint = mDrawingState.releaseBufferEndpoint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001275 mBufferInfo.mFence = mDrawingState.acquireFence;
1276 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
1277 mBufferInfo.mPixelFormat =
1278 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
1279 mBufferInfo.mFrameLatencyNeeded = true;
1280 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
1281 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +00001282 mBufferInfo.mTransform = mDrawingState.bufferTransform;
1283 auto lastDataspace = mBufferInfo.mDataspace;
1284 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00001285 if (mBufferInfo.mBuffer != nullptr) {
1286 auto& mapper = GraphicBufferMapper::get();
1287 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
1288 // and don't need to possibly remaps buffers.
1289 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
1290 status_t err = OK;
1291 {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001292 SFTRACE_NAME("getDataspace");
Alec Mouri74c7ae12023-03-26 02:57:47 +00001293 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
1294 }
1295 if (err != OK || dataspace != mBufferInfo.mDataspace) {
1296 {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001297 SFTRACE_NAME("setDataspace");
Alec Mouri74c7ae12023-03-26 02:57:47 +00001298 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
1299 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
1300 }
1301
1302 // Some GPU drivers may cache gralloc metadata which means before we composite we need
1303 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
1304 // compatible with old vendors, with a ticking clock.
1305 static const int32_t kVendorVersion =
Alec Mouri8a06fb72023-11-16 22:07:13 +00001306 base::GetIntProperty("ro.board.api_level", __ANDROID_API_FUTURE__);
Alec Mouri74c7ae12023-03-26 02:57:47 +00001307 if (const auto format =
1308 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
1309 mBufferInfo.mBuffer->getPixelFormat());
1310 err == OK && kVendorVersion < __ANDROID_API_U__ &&
1311 (format ==
1312 aidl::android::hardware::graphics::common::PixelFormat::
1313 IMPLEMENTATION_DEFINED ||
1314 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
1315 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
1316 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
1317 mBufferInfo.mBuffer->remapBuffer();
1318 }
1319 }
1320 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00001321 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05001322 mFlinger->mHdrLayerInfoChanged = true;
1323 }
Sally Qi963049b2023-03-23 14:06:21 -07001324 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
1325 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05001326 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001327 }
1328 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
Patrick Williamsbb25f802022-08-30 23:02:34 +00001329 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001330}
1331
1332Rect Layer::computeBufferCrop(const State& s) {
1333 if (s.buffer && !s.bufferCrop.isEmpty()) {
1334 Rect bufferCrop;
1335 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
1336 return bufferCrop;
1337 } else if (s.buffer) {
1338 return s.buffer->getBounds();
1339 } else {
1340 return s.bufferCrop;
1341 }
1342}
1343
Patrick Williamsbb25f802022-08-30 23:02:34 +00001344void Layer::decrementPendingBufferCount() {
Melody Hsu16355782024-10-09 08:56:28 +00001345 int32_t pendingBuffers = --mPendingBuffers;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001346 tracePendingBufferCount(pendingBuffers);
1347}
1348
1349void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001350 SFTRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
Patrick Williamsbb25f802022-08-30 23:02:34 +00001351}
1352
Vishnu Nair3af0ec02023-02-10 04:13:48 +00001353sp<LayerFE> Layer::getCompositionEngineLayerFE(
1354 const frontend::LayerHierarchy::TraversalPath& path) {
1355 for (auto& [p, layerFE] : mLayerFEs) {
1356 if (p == path) {
1357 return layerFE;
1358 }
1359 }
Lloyd Pique70ddc672024-04-30 18:20:40 -07001360 auto layerFE = mFlinger->getFactory().createLayerFE(mName, this);
Vishnu Nair3af0ec02023-02-10 04:13:48 +00001361 mLayerFEs.emplace_back(path, layerFE);
1362 return layerFE;
1363}
1364
Leon Scroggins III5b581492023-10-31 14:29:41 -04001365void Layer::onCompositionPresented(const DisplayDevice* display,
1366 const std::shared_ptr<FenceTime>& glDoneFence,
1367 const std::shared_ptr<FenceTime>& presentFence,
Vishnu Nair39a74a92024-07-29 19:01:50 +00001368 const CompositorTiming& compositorTiming,
1369 gui::GameMode gameMode) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00001370 // mFrameLatencyNeeded is true when a new frame was latched for the
1371 // composition.
1372 if (!mBufferInfo.mFrameLatencyNeeded) return;
1373
1374 for (const auto& handle : mDrawingState.callbackHandles) {
1375 handle->gpuCompositionDoneFence = glDoneFence;
1376 handle->compositorTiming = compositorTiming;
1377 }
1378
1379 // Update mFrameTracker.
1380 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
1381 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1382
1383 const int32_t layerId = getSequence();
1384 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
1385
1386 const auto outputLayer = findOutputLayerForDisplay(display);
1387 if (outputLayer && outputLayer->requiresClientComposition()) {
1388 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
1389 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
1390 clientCompositionTimestamp,
1391 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
1392 // Update the SurfaceFrames in the drawing state
1393 if (mDrawingState.bufferSurfaceFrameTX) {
1394 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
1395 }
1396 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
1397 surfaceFrame->setGpuComposition();
1398 }
1399 }
1400
1401 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
1402 if (frameReadyFence->isValid()) {
1403 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
1404 } else {
1405 // There was no fence for this frame, so assume that it was ready
1406 // to be presented at the desired present time.
1407 mFrameTracker.setFrameReadyTime(desiredPresentTime);
1408 }
1409
1410 if (display) {
Dominik Laskowskife749dc2024-07-26 10:09:31 -04001411 const auto activeMode = display->refreshRateSelector().getActiveMode();
1412 const Fps refreshRate = activeMode.fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001413 const std::optional<Fps> renderRate =
1414 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1415
Alec Mouri7c1d8b52023-08-29 20:14:46 +00001416 const auto vote = frameRateToSetFrameRateVotePayload(getFrameRateForLayerTree());
Patrick Williamsbb25f802022-08-30 23:02:34 +00001417
1418 if (presentFence->isValid()) {
1419 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
1420 refreshRate, renderRate, vote, gameMode);
1421 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
1422 presentFence,
1423 FrameTracer::FrameEvent::PRESENT_FENCE);
1424 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
1425 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
1426 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04001427 // The HWC doesn't support present fences, so use the present timestamp instead.
1428 const nsecs_t presentTimestamp =
1429 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
1430
1431 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
Dominik Laskowskife749dc2024-07-26 10:09:31 -04001432 const nsecs_t vsyncPeriod =
1433 mFlinger->getHwComposer()
1434 .getDisplayVsyncPeriod(*displayId)
1435 .value_opt()
1436 .value_or(activeMode.modePtr->getVsyncRate().getPeriodNsecs());
1437
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04001438 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
1439
Patrick Williamsbb25f802022-08-30 23:02:34 +00001440 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
1441 refreshRate, renderRate, vote, gameMode);
1442 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
1443 mCurrentFrameNumber, actualPresentTime,
1444 FrameTracer::FrameEvent::PRESENT_FENCE);
1445 mFrameTracker.setActualPresentTime(actualPresentTime);
1446 }
1447 }
1448
1449 mFrameTracker.advanceFrame();
1450 mBufferInfo.mFrameLatencyNeeded = false;
1451}
1452
Vishnu Naird47bcee2023-02-24 18:08:51 +00001453bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001454 SFTRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
1455 getDrawingState().frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00001456
1457 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
1458
1459 if (refreshRequired) {
1460 return refreshRequired;
1461 }
1462
1463 // If the head buffer's acquire fence hasn't signaled yet, return and
1464 // try again later
1465 if (!fenceHasSignaled()) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001466 SFTRACE_NAME("!fenceHasSignaled()");
Patrick Williamsbb25f802022-08-30 23:02:34 +00001467 mFlinger->onLayerUpdate();
1468 return false;
1469 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00001470 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00001471
1472 // Capture the old state of the layer for comparisons later
1473 BufferInfo oldBufferInfo = mBufferInfo;
Patrick Williamsbb25f802022-08-30 23:02:34 +00001474 mPreviousFrameNumber = mCurrentFrameNumber;
1475 mCurrentFrameNumber = mDrawingState.frameNumber;
1476 gatherBufferInfo();
1477
Vishnu Nair7ee4f462023-04-19 09:54:09 -07001478 if (mBufferInfo.mBuffer) {
1479 // We latched a buffer that will be presented soon. Clear the previously presented layer
1480 // stack list.
1481 mPreviouslyPresentedLayerStacks.clear();
1482 }
1483
1484 if (mDrawingState.buffer == nullptr) {
1485 const bool bufferReleased = oldBufferInfo.mBuffer != nullptr;
1486 recomputeVisibleRegions = bufferReleased;
1487 return bufferReleased;
1488 }
1489
Patrick Williamsbb25f802022-08-30 23:02:34 +00001490 if (oldBufferInfo.mBuffer == nullptr) {
1491 // the first time we receive a buffer, we need to trigger a
1492 // geometry invalidation.
1493 recomputeVisibleRegions = true;
1494 }
1495
1496 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
1497 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
Patrick Williamsbb25f802022-08-30 23:02:34 +00001498 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
1499 recomputeVisibleRegions = true;
1500 }
1501
1502 if (oldBufferInfo.mBuffer != nullptr) {
1503 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
1504 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
1505 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
1506 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
1507 recomputeVisibleRegions = true;
1508 }
1509 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00001510 return true;
1511}
1512
Patrick Williamsbb25f802022-08-30 23:02:34 +00001513bool Layer::getTransformToDisplayInverse() const {
1514 return mBufferInfo.mTransformToDisplayInverse;
1515}
1516
Patrick Williamsbb25f802022-08-30 23:02:34 +00001517ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
1518 ui::Dataspace updatedDataspace = dataspace;
1519 // translate legacy dataspaces to modern dataspaces
1520 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00001521 // Treat unknown dataspaces as V0_sRGB
1522 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00001523 case ui::Dataspace::SRGB:
1524 updatedDataspace = ui::Dataspace::V0_SRGB;
1525 break;
1526 case ui::Dataspace::SRGB_LINEAR:
1527 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
1528 break;
1529 case ui::Dataspace::JFIF:
1530 updatedDataspace = ui::Dataspace::V0_JFIF;
1531 break;
1532 case ui::Dataspace::BT601_625:
1533 updatedDataspace = ui::Dataspace::V0_BT601_625;
1534 break;
1535 case ui::Dataspace::BT601_525:
1536 updatedDataspace = ui::Dataspace::V0_BT601_525;
1537 break;
1538 case ui::Dataspace::BT709:
1539 updatedDataspace = ui::Dataspace::V0_BT709;
1540 break;
1541 default:
1542 break;
1543 }
1544
1545 return updatedDataspace;
1546}
1547
1548sp<GraphicBuffer> Layer::getBuffer() const {
1549 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
1550}
1551
Chavi Weingarten328a8312023-01-26 21:17:52 +00001552bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00001553 TrustedPresentationListener const& listener) {
1554 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
1555 mTrustedPresentationListener = listener;
1556 mTrustedPresentationThresholds = thresholds;
1557 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
1558 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
1559 mFlinger->mNumTrustedPresentationListeners++;
1560 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
1561 mFlinger->mNumTrustedPresentationListeners--;
1562 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00001563
1564 // Reset trusted presentation states to ensure we start the time again.
1565 mEnteredTrustedPresentationStateTime = -1;
1566 mLastReportedTrustedPresentationState = false;
1567 mLastComputedTrustedPresentationState = false;
1568
1569 // If there's a new trusted presentation listener, the code needs to go through the composite
1570 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
1571 // we're already in the requested state.
1572 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00001573}
1574
Patrick Williams7c9fa272024-08-30 12:38:43 +00001575void Layer::setBufferReleaseChannel(
1576 const std::shared_ptr<gui::BufferReleaseChannel::ProducerEndpoint>& channel) {
1577 mBufferReleaseChannel = channel;
1578}
1579
Vishnu Naira156f482023-02-22 00:23:38 +00001580void Layer::updateLastLatchTime(nsecs_t latchTime) {
1581 mLastLatchTime = latchTime;
1582}
1583
Vishnu Nairdc83d4b2024-08-15 16:29:20 +00001584void Layer::setIsSmallDirty(frontend::LayerSnapshot* snapshot) {
Jerry Chang36678002023-11-29 16:56:17 +00001585 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Vishnu Nairdc83d4b2024-08-15 16:29:20 +00001586 snapshot->isSmallDirty = false;
Arthur Hungc70bee22023-06-02 01:35:52 +00001587 return;
1588 }
1589
1590 if (mWindowType != WindowInfo::Type::APPLICATION &&
1591 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
Vishnu Nairdc83d4b2024-08-15 16:29:20 +00001592 snapshot->isSmallDirty = false;
Arthur Hungc70bee22023-06-02 01:35:52 +00001593 return;
1594 }
Arthur Hung69f95222023-10-04 07:39:02 +00001595
Vishnu Nairdc83d4b2024-08-15 16:29:20 +00001596 Rect bounds = snapshot->surfaceDamage.getBounds();
Arthur Hungc70bee22023-06-02 01:35:52 +00001597 if (!bounds.isValid()) {
Vishnu Nairdc83d4b2024-08-15 16:29:20 +00001598 snapshot->isSmallDirty = false;
Arthur Hungc70bee22023-06-02 01:35:52 +00001599 return;
1600 }
1601
Arthur Hung69f95222023-10-04 07:39:02 +00001602 // Transform to screen space.
Vishnu Nairdc83d4b2024-08-15 16:29:20 +00001603 bounds = snapshot->localTransform.transform(bounds);
Arthur Hung69f95222023-10-04 07:39:02 +00001604
Arthur Hungc70bee22023-06-02 01:35:52 +00001605 // If the damage region is a small dirty, this could give the hint for the layer history that
1606 // it could suppress the heuristic rate when calculating.
Vishnu Nairdc83d4b2024-08-15 16:29:20 +00001607 snapshot->isSmallDirty =
1608 mFlinger->mScheduler->isSmallDirtyArea(mOwnerAppId,
1609 bounds.getWidth() * bounds.getHeight());
Arthur Hung69f95222023-10-04 07:39:02 +00001610}
1611
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001612} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07001613
1614#if defined(__gl_h_)
1615#error "don't include gl/gl.h in this file"
1616#endif
1617
1618#if defined(__gl2_h_)
1619#error "don't include gl2/gl2.h in this file"
1620#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08001621
1622// TODO(b/129481165): remove the #pragma below and fix conversion issues
1623#pragma clang diagnostic pop // ignored "-Wconversion"