blob: df91904ac8f3d89ef1643124bfb84f15d9c3b6d9 [file] [log] [blame]
Marissa Wall61c58622018-07-18 10:12:20 -07001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
Marin Shalamanovbed7fd32020-12-21 20:02:20 +010020#pragma clang diagnostic ignored "-Wextra"
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080021
Marissa Wall61c58622018-07-18 10:12:20 -070022//#define LOG_NDEBUG 0
23#undef LOG_TAG
24#define LOG_TAG "BufferStateLayer"
25#define ATRACE_TAG ATRACE_TAG_GRAPHICS
26
Lloyd Pique9755fb72019-03-26 14:44:40 -070027#include "BufferStateLayer.h"
28
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080029#include <limits>
Marissa Wall61c58622018-07-18 10:12:20 -070030
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +000031#include <FrameTimeline/FrameTimeline.h>
Lloyd Pique9755fb72019-03-26 14:44:40 -070032#include <compositionengine/LayerFECompositionState.h>
Marissa Wall947d34e2019-03-29 14:03:53 -070033#include <gui/BufferQueue.h>
Marissa Wall61c58622018-07-18 10:12:20 -070034#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070035#include <renderengine/Image.h>
Robert Carr38d25002021-06-11 14:30:09 -070036#include "TunnelModeEnabledReporter.h"
Marissa Wall61c58622018-07-18 10:12:20 -070037
Vishnu Nairfa247b12020-02-11 08:58:26 -080038#include "EffectLayer.h"
Adithya Srinivasanb238cd52021-02-04 17:54:05 +000039#include "FrameTracer/FrameTracer.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080040#include "TimeStats/TimeStats.h"
Valerie Hau0bc09152018-12-20 07:42:47 -080041
Marissa Wall61c58622018-07-18 10:12:20 -070042namespace android {
43
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +000044using PresentState = frametimeline::SurfaceFrame::PresentState;
Vishnu Nair1506b182021-02-22 14:35:15 -080045namespace {
46void callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -070047 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
48 const sp<Fence>& releaseFence, uint32_t transformHint,
49 uint32_t currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -080050 if (!listener) {
51 return;
52 }
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -070053 listener->onReleaseBuffer({buffer->getId(), framenumber},
54 releaseFence ? releaseFence : Fence::NO_FENCE, transformHint,
55 currentMaxAcquiredBufferCount);
Vishnu Nair1506b182021-02-22 14:35:15 -080056}
57} // namespace
58
Marissa Wall947d34e2019-03-29 14:03:53 -070059BufferStateLayer::BufferStateLayer(const LayerCreationArgs& args)
60 : BufferLayer(args), mHwcSlotGenerator(new HwcSlotGenerator()) {
Robert Carr6a160312021-05-17 12:08:20 -070061 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Vishnu Nair60356342018-11-13 13:00:45 -080062}
Marissa Wall61c58622018-07-18 10:12:20 -070063
Alec Mouri4545a8a2019-08-08 20:05:32 -070064BufferStateLayer::~BufferStateLayer() {
chaviwb4c6e582019-08-16 14:35:07 -070065 // The original layer and the clone layer share the same texture and buffer. Therefore, only
66 // one of the layers, in this case the original layer, needs to handle the deletion. The
67 // original layer and the clone should be removed at the same time so there shouldn't be any
68 // issue with the clone layer trying to use the texture.
Vishnu Nair3bb11d02021-11-26 09:24:11 -080069 if (mBufferInfo.mBuffer != nullptr) {
Alec Mouria90a5702021-04-16 16:36:21 +000070 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -070071 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
72 mBufferInfo.mFence, mTransformHint,
Ady Abraham899dcdb2021-06-15 16:56:21 -070073 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
74 mOwnerUid));
Alec Mouri4545a8a2019-08-08 20:05:32 -070075 }
76}
77
Robert Carr8d958532020-11-10 14:09:16 -080078status_t BufferStateLayer::addReleaseFence(const sp<CallbackHandle>& ch,
79 const sp<Fence>& fence) {
80 if (ch == nullptr) {
81 return OK;
82 }
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -070083 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
Robert Carr8d958532020-11-10 14:09:16 -080084 if (!ch->previousReleaseFence.get()) {
85 ch->previousReleaseFence = fence;
86 return OK;
87 }
88
89 // Below logic is lifted from ConsumerBase.cpp:
90 // Check status of fences first because merging is expensive.
91 // Merging an invalid fence with any other fence results in an
92 // invalid fence.
93 auto currentStatus = ch->previousReleaseFence->getStatus();
94 if (currentStatus == Fence::Status::Invalid) {
95 ALOGE("Existing fence has invalid state, layer: %s", mName.c_str());
96 return BAD_VALUE;
97 }
98
99 auto incomingStatus = fence->getStatus();
100 if (incomingStatus == Fence::Status::Invalid) {
101 ALOGE("New fence has invalid state, layer: %s", mName.c_str());
102 ch->previousReleaseFence = fence;
103 return BAD_VALUE;
104 }
105
106 // If both fences are signaled or both are unsignaled, we need to merge
107 // them to get an accurate timestamp.
108 if (currentStatus == incomingStatus) {
109 char fenceName[32] = {};
110 snprintf(fenceName, 32, "%.28s", mName.c_str());
111 sp<Fence> mergedFence = Fence::merge(
112 fenceName, ch->previousReleaseFence, fence);
113 if (!mergedFence.get()) {
114 ALOGE("failed to merge release fences, layer: %s", mName.c_str());
115 // synchronization is broken, the best we can do is hope fences
116 // signal in order so the new fence will act like a union
117 ch->previousReleaseFence = fence;
118 return BAD_VALUE;
119 }
120 ch->previousReleaseFence = mergedFence;
121 } else if (incomingStatus == Fence::Status::Unsignaled) {
122 // If one fence has signaled and the other hasn't, the unsignaled
123 // fence will approximately correspond with the correct timestamp.
124 // There's a small race if both fences signal at about the same time
125 // and their statuses are retrieved with unfortunate timing. However,
126 // by this point, they will have both signaled and only the timestamp
127 // will be slightly off; any dependencies after this point will
128 // already have been met.
129 ch->previousReleaseFence = fence;
130 }
131 // else if (currentStatus == Fence::Status::Unsignaled) is a no-op.
132
133 return OK;
134}
135
Marissa Wall61c58622018-07-18 10:12:20 -0700136// -----------------------------------------------------------------------
137// Interface implementation for Layer
138// -----------------------------------------------------------------------
Marissa Wallfda30bb2018-10-12 11:34:28 -0700139void BufferStateLayer::onLayerDisplayed(const sp<Fence>& releaseFence) {
Robert Carr8d958532020-11-10 14:09:16 -0800140 if (!releaseFence->isValid()) {
141 return;
142 }
Marissa Wall5a68a772018-12-22 17:43:42 -0800143 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
144 // buffer that was presented on this layer. The first transaction that came in this frame that
145 // replaced the previous buffer on this layer needs this release fence, because the fence will
146 // let the client know when that previous buffer is removed from the screen.
147 //
148 // Every other transaction on this layer does not need a release fence because no other
149 // Transactions that were set on this layer this frame are going to have their preceeding buffer
150 // removed from the display this frame.
151 //
152 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
153 // buffer so it doesn't need a previous release fence because the layer still needs the previous
154 // buffer. The second transaction contains a buffer so it needs a previous release fence because
155 // the previous buffer will be released this frame. The third transaction also contains a
156 // buffer. It replaces the buffer in the second transaction. The buffer in the second
157 // transaction will now no longer be presented so it is released immediately and the third
158 // transaction doesn't need a previous release fence.
Robert Carr8d958532020-11-10 14:09:16 -0800159 sp<CallbackHandle> ch;
Marissa Wall5a68a772018-12-22 17:43:42 -0800160 for (auto& handle : mDrawingState.callbackHandles) {
chaviw0b06a8d2021-08-06 11:49:08 -0500161 if (handle->releasePreviousBuffer &&
162 mDrawingState.releaseBufferEndpoint == handle->listener) {
Robert Carr8d958532020-11-10 14:09:16 -0800163 ch = handle;
Marissa Wall5a68a772018-12-22 17:43:42 -0800164 break;
165 }
166 }
Robert Carr8d958532020-11-10 14:09:16 -0800167 auto status = addReleaseFence(ch, releaseFence);
168 if (status != OK) {
169 ALOGE("Failed to add release fence for layer %s", getName().c_str());
170 }
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700171
Valerie Haubf784642020-01-29 07:25:23 -0800172 mPreviousReleaseFence = releaseFence;
173
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700174 // Prevent tracing the same release multiple times.
175 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700176 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
177 }
Marissa Wall61c58622018-07-18 10:12:20 -0700178}
179
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100180void BufferStateLayer::onSurfaceFrameCreated(
181 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasand17c7da2021-03-05 20:43:32 +0000182 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
183 // Too many SurfaceFrames pending classification. The front of the deque is probably not
184 // tracked by FrameTimeline and will never be presented. This will only result in a memory
185 // leak.
186 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
187 mName.c_str());
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000188 std::string miniDump = mPendingJankClassifications.front()->miniDump();
189 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
Adithya Srinivasand17c7da2021-03-05 20:43:32 +0000190 mPendingJankClassifications.pop_front();
191 }
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100192 mPendingJankClassifications.emplace_back(surfaceFrame);
193}
194
Valerie Haubf784642020-01-29 07:25:23 -0800195void BufferStateLayer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Valerie Hau32cdc1f2019-10-21 14:45:54 -0700196 for (const auto& handle : mDrawingState.callbackHandles) {
197 handle->transformHint = mTransformHint;
Valerie Hau871d6352020-01-29 08:44:02 -0800198 handle->dequeueReadyTime = dequeueReadyTime;
Ady Abraham899dcdb2021-06-15 16:56:21 -0700199 handle->currentMaxAcquiredBufferCount =
200 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Valerie Hau32cdc1f2019-10-21 14:45:54 -0700201 }
202
Vishnu Nair1506b182021-02-22 14:35:15 -0800203 for (auto& handle : mDrawingState.callbackHandles) {
chaviw0b06a8d2021-08-06 11:49:08 -0500204 if (handle->releasePreviousBuffer &&
205 mDrawingState.releaseBufferEndpoint == handle->listener) {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700206 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
Vishnu Nair1506b182021-02-22 14:35:15 -0800207 break;
208 }
209 }
210
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100211 std::vector<JankData> jankData;
212 jankData.reserve(mPendingJankClassifications.size());
213 while (!mPendingJankClassifications.empty()
214 && mPendingJankClassifications.front()->getJankType()) {
215 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
216 mPendingJankClassifications.front();
217 mPendingJankClassifications.pop_front();
218 jankData.emplace_back(
219 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
220 }
221
Robert Carr9a803c32021-01-14 16:57:58 -0800222 mFlinger->getTransactionCallbackInvoker().finalizePendingCallbackHandles(
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100223 mDrawingState.callbackHandles, jankData);
Marissa Wall5a68a772018-12-22 17:43:42 -0800224
225 mDrawingState.callbackHandles = {};
Valerie Haubf784642020-01-29 07:25:23 -0800226
227 const sp<Fence>& releaseFence(mPreviousReleaseFence);
228 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(releaseFence);
229 {
230 Mutex::Autolock lock(mFrameEventHistoryMutex);
231 if (mPreviousFrameNumber != 0) {
232 mFrameEventHistory.addRelease(mPreviousFrameNumber, dequeueReadyTime,
233 std::move(releaseFenceTime));
234 }
235 }
Marissa Wall61c58622018-07-18 10:12:20 -0700236}
237
Valerie Hau871d6352020-01-29 08:44:02 -0800238void BufferStateLayer::finalizeFrameEventHistory(const std::shared_ptr<FenceTime>& glDoneFence,
239 const CompositorTiming& compositorTiming) {
240 for (const auto& handle : mDrawingState.callbackHandles) {
241 handle->gpuCompositionDoneFence = glDoneFence;
242 handle->compositorTiming = compositorTiming;
243 }
244}
245
Marissa Walle2ffb422018-10-12 11:33:52 -0700246bool BufferStateLayer::willPresentCurrentTransaction() const {
247 // Returns true if the most recent Transaction applied to CurrentState will be presented.
Robert Carr321e83c2019-08-19 15:49:30 -0700248 return (getSidebandStreamChanged() || getAutoRefresh() ||
Robert Carr6a160312021-05-17 12:08:20 -0700249 (mDrawingState.modified &&
250 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
Marissa Wall61c58622018-07-18 10:12:20 -0700251}
252
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000253Rect BufferStateLayer::getCrop(const Layer::State& s) const {
254 return s.crop;
Marissa Wall61c58622018-07-18 10:12:20 -0700255}
256
257bool BufferStateLayer::setTransform(uint32_t transform) {
Robert Carr6a160312021-05-17 12:08:20 -0700258 if (mDrawingState.bufferTransform == transform) return false;
259 mDrawingState.bufferTransform = transform;
260 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700261 setTransactionFlags(eTransactionNeeded);
262 return true;
263}
264
265bool BufferStateLayer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
Robert Carr6a160312021-05-17 12:08:20 -0700266 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
267 mDrawingState.sequence++;
268 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
269 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700270 setTransactionFlags(eTransactionNeeded);
271 return true;
272}
273
274bool BufferStateLayer::setCrop(const Rect& crop) {
Robert Carr6a160312021-05-17 12:08:20 -0700275 if (mDrawingState.crop == crop) return false;
276 mDrawingState.sequence++;
277 mDrawingState.crop = crop;
Marissa Wall290ad082019-03-06 13:23:47 -0800278
Robert Carr6a160312021-05-17 12:08:20 -0700279 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700280 setTransactionFlags(eTransactionNeeded);
281 return true;
282}
283
chaviwf3f40fe2021-04-27 15:54:02 -0500284bool BufferStateLayer::setBufferCrop(const Rect& bufferCrop) {
Robert Carr6a160312021-05-17 12:08:20 -0700285 if (mDrawingState.bufferCrop == bufferCrop) return false;
chaviwf3f40fe2021-04-27 15:54:02 -0500286
Robert Carr6a160312021-05-17 12:08:20 -0700287 mDrawingState.sequence++;
288 mDrawingState.bufferCrop = bufferCrop;
chaviwf3f40fe2021-04-27 15:54:02 -0500289
Robert Carr6a160312021-05-17 12:08:20 -0700290 mDrawingState.modified = true;
chaviwf3f40fe2021-04-27 15:54:02 -0500291 setTransactionFlags(eTransactionNeeded);
292 return true;
293}
294
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700295bool BufferStateLayer::setDestinationFrame(const Rect& destinationFrame) {
Robert Carr6a160312021-05-17 12:08:20 -0700296 if (mDrawingState.destinationFrame == destinationFrame) return false;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700297
Robert Carr6a160312021-05-17 12:08:20 -0700298 mDrawingState.sequence++;
299 mDrawingState.destinationFrame = destinationFrame;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700300
Robert Carr6a160312021-05-17 12:08:20 -0700301 mDrawingState.modified = true;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700302 setTransactionFlags(eTransactionNeeded);
303 return true;
304}
305
Robert Carr6a160312021-05-17 12:08:20 -0700306static bool assignTransform(ui::Transform* dst, ui::Transform& from) {
307 if (*dst == from) {
308 return false;
309 }
310 *dst = from;
311 return true;
312}
313
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700314// Translate destination frame into scale and position. If a destination frame is not set, use the
315// provided scale and position
Robert Carr6a160312021-05-17 12:08:20 -0700316bool BufferStateLayer::updateGeometry() {
317 if (mDrawingState.destinationFrame.isEmpty()) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700318 // If destination frame is not set, use the requested transform set via
319 // BufferStateLayer::setPosition and BufferStateLayer::setMatrix.
Robert Carr6a160312021-05-17 12:08:20 -0700320 return assignTransform(&mDrawingState.transform, mRequestedTransform);
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700321 }
322
Robert Carr6a160312021-05-17 12:08:20 -0700323 Rect destRect = mDrawingState.destinationFrame;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700324 int32_t destW = destRect.width();
325 int32_t destH = destRect.height();
326 if (destRect.left < 0) {
327 destRect.left = 0;
328 destRect.right = destW;
329 }
330 if (destRect.top < 0) {
331 destRect.top = 0;
332 destRect.bottom = destH;
333 }
334
Robert Carr6a160312021-05-17 12:08:20 -0700335 if (!mDrawingState.buffer) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700336 ui::Transform t;
337 t.set(destRect.left, destRect.top);
Robert Carr6a160312021-05-17 12:08:20 -0700338 return assignTransform(&mDrawingState.transform, t);
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700339 }
340
Robert Carr6a160312021-05-17 12:08:20 -0700341 uint32_t bufferWidth = mDrawingState.buffer->getBuffer()->getWidth();
342 uint32_t bufferHeight = mDrawingState.buffer->getBuffer()->getHeight();
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700343 // Undo any transformations on the buffer.
Robert Carr6a160312021-05-17 12:08:20 -0700344 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700345 std::swap(bufferWidth, bufferHeight);
346 }
347 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
Robert Carr6a160312021-05-17 12:08:20 -0700348 if (mDrawingState.transformToDisplayInverse) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700349 if (invTransform & ui::Transform::ROT_90) {
350 std::swap(bufferWidth, bufferHeight);
351 }
352 }
353
354 float sx = destW / static_cast<float>(bufferWidth);
355 float sy = destH / static_cast<float>(bufferHeight);
356 ui::Transform t;
357 t.set(sx, 0, 0, sy);
358 t.set(destRect.left, destRect.top);
Robert Carr6a160312021-05-17 12:08:20 -0700359 return assignTransform(&mDrawingState.transform, t);
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700360}
361
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000362bool BufferStateLayer::setMatrix(const layer_state_t::matrix22_t& matrix,
363 bool allowNonRectPreservingTransforms) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700364 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
365 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
Marissa Wall861616d2018-10-22 12:52:23 -0700366 return false;
367 }
368
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000369 ui::Transform t;
370 t.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
371
372 if (!allowNonRectPreservingTransforms && !t.preserveRects()) {
373 ALOGW("Attempt to set rotation matrix without permission ACCESS_SURFACE_FLINGER nor "
374 "ROTATE_SURFACE_FLINGER ignored");
375 return false;
Marissa Wall861616d2018-10-22 12:52:23 -0700376 }
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000377
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700378 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
chaviw9a93ea62021-03-11 16:44:42 -0600379
Robert Carr6a160312021-05-17 12:08:20 -0700380 mDrawingState.sequence++;
381 mDrawingState.modified = true;
chaviw9a93ea62021-03-11 16:44:42 -0600382 setTransactionFlags(eTransactionNeeded);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000383
384 return true;
385}
386
387bool BufferStateLayer::setPosition(float x, float y) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700388 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000389 return false;
390 }
391
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700392 mRequestedTransform.set(x, y);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000393
Robert Carr6a160312021-05-17 12:08:20 -0700394 mDrawingState.sequence++;
395 mDrawingState.modified = true;
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000396 setTransactionFlags(eTransactionNeeded);
397
Marissa Wall861616d2018-10-22 12:52:23 -0700398 return true;
399}
400
Valerie Hau871d6352020-01-29 08:44:02 -0800401bool BufferStateLayer::addFrameEvent(const sp<Fence>& acquireFence, nsecs_t postedTime,
402 nsecs_t desiredPresentTime) {
Valerie Haubf784642020-01-29 07:25:23 -0800403 Mutex::Autolock lock(mFrameEventHistoryMutex);
404 mAcquireTimeline.updateSignalTimes();
405 std::shared_ptr<FenceTime> acquireFenceTime =
406 std::make_shared<FenceTime>((acquireFence ? acquireFence : Fence::NO_FENCE));
Robert Carr6a160312021-05-17 12:08:20 -0700407 NewFrameEventsEntry newTimestamps = {mDrawingState.frameNumber, postedTime, desiredPresentTime,
Valerie Haubf784642020-01-29 07:25:23 -0800408 acquireFenceTime};
Valerie Hau871d6352020-01-29 08:44:02 -0800409 mFrameEventHistory.setProducerWantsEvents();
Valerie Haubf784642020-01-29 07:25:23 -0800410 mFrameEventHistory.addQueue(newTimestamps);
411 return true;
412}
413
Alec Mouria90a5702021-04-16 16:36:21 +0000414bool BufferStateLayer::setBuffer(const std::shared_ptr<renderengine::ExternalTexture>& buffer,
415 const sp<Fence>& acquireFence, nsecs_t postTime,
416 nsecs_t desiredPresentTime, bool isAutoTimestamp,
Vishnu Nairadf632b2021-01-07 14:05:08 -0800417 const client_cache_t& clientCacheId, uint64_t frameNumber,
Vishnu Nair1506b182021-02-22 14:35:15 -0800418 std::optional<nsecs_t> dequeueTime, const FrameTimelineInfo& info,
chaviw0b06a8d2021-08-06 11:49:08 -0500419 const sp<ITransactionCompletedListener>& releaseBufferListener,
420 const sp<IBinder>& releaseBufferEndpoint) {
Robert Carr0c1966e2020-10-19 12:12:08 -0700421 ATRACE_CALL();
422
Robert Carr6a160312021-05-17 12:08:20 -0700423 if (mDrawingState.buffer) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700424 mReleasePreviousBuffer = true;
Vishnu Nair52846cd2021-08-05 16:12:48 -0700425 if (mDrawingState.buffer != mBufferInfo.mBuffer ||
426 mDrawingState.frameNumber != mBufferInfo.mFrameNumber) {
Robert Carr6a160312021-05-17 12:08:20 -0700427 // If mDrawingState has a buffer, and we are about to update again
Robert Carr7121caf2020-12-15 13:07:32 -0800428 // before swapping to drawing state, then the first buffer will be
Vishnu Nair1506b182021-02-22 14:35:15 -0800429 // dropped and we should decrement the pending buffer count and
430 // call any release buffer callbacks if set.
Robert Carr6a160312021-05-17 12:08:20 -0700431 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700432 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
433 mDrawingState.acquireFence, mTransformHint,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700434 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
435 mOwnerUid));
Robert Carr7121caf2020-12-15 13:07:32 -0800436 decrementPendingBufferCount();
Robert Carr6a160312021-05-17 12:08:20 -0700437 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
438 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
439 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
440 mDrawingState.bufferSurfaceFrameTX.reset();
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000441 }
Robert Carr7121caf2020-12-15 13:07:32 -0800442 }
Marissa Wallfda30bb2018-10-12 11:34:28 -0700443 }
Robert Carr6a160312021-05-17 12:08:20 -0700444
445 mDrawingState.frameNumber = frameNumber;
446 mDrawingState.releaseBufferListener = releaseBufferListener;
447 mDrawingState.buffer = buffer;
448 mDrawingState.clientCacheId = clientCacheId;
449 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700450 setTransactionFlags(eTransactionNeeded);
Ady Abraham09bd3922019-04-08 10:44:56 -0700451
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800452 const int32_t layerId = getSequence();
Robert Carr6a160312021-05-17 12:08:20 -0700453 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000454 mOwnerUid, postTime, getGameMode());
Robert Carr6a160312021-05-17 12:08:20 -0700455 mDrawingState.desiredPresentTime = desiredPresentTime;
456 mDrawingState.isAutoTimestamp = isAutoTimestamp;
Ady Abraham09bd3922019-04-08 10:44:56 -0700457
Ady Abrahamb7f15562021-03-15 18:34:08 -0700458 const nsecs_t presentTime = [&] {
459 if (!isAutoTimestamp) return desiredPresentTime;
460
461 const auto prediction =
462 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
463 if (prediction.has_value()) return prediction->presentTime;
464
465 return static_cast<nsecs_t>(0);
466 }();
467 mFlinger->mScheduler->recordLayerHistory(this, presentTime,
Ady Abraham5def7332020-05-29 16:13:47 -0700468 LayerHistory::LayerUpdateType::Buffer);
Ady Abraham09bd3922019-04-08 10:44:56 -0700469
Ady Abrahamf0c56492020-12-17 18:04:15 -0800470 addFrameEvent(acquireFence, postTime, isAutoTimestamp ? 0 : desiredPresentTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000471
Adithya Srinivasan891004e2021-02-12 20:20:47 +0000472 setFrameTimelineVsyncForBufferTransaction(info, postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000473
Alec Mouria90a5702021-04-16 16:36:21 +0000474 if (buffer && dequeueTime && *dequeueTime != 0) {
475 const uint64_t bufferId = buffer->getBuffer()->getId();
Adithya Srinivasanb238cd52021-02-04 17:54:05 +0000476 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
477 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
478 FrameTracer::FrameEvent::DEQUEUE);
479 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
480 FrameTracer::FrameEvent::QUEUE);
481 }
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000482
Robert Carr6a160312021-05-17 12:08:20 -0700483 mDrawingState.width = mDrawingState.buffer->getBuffer()->getWidth();
484 mDrawingState.height = mDrawingState.buffer->getBuffer()->getHeight();
chaviw0b06a8d2021-08-06 11:49:08 -0500485 mDrawingState.releaseBufferEndpoint = releaseBufferEndpoint;
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000486
Marissa Wall61c58622018-07-18 10:12:20 -0700487 return true;
488}
489
490bool BufferStateLayer::setAcquireFence(const sp<Fence>& fence) {
Robert Carr6a160312021-05-17 12:08:20 -0700491 mDrawingState.acquireFence = fence;
492 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(fence);
Ady Abraham6c1b7ac2021-03-31 16:56:03 -0700493
494 // The acquire fences of BufferStateLayers have already signaled before they are set
Robert Carr6a160312021-05-17 12:08:20 -0700495 mCallbackHandleAcquireTime = mDrawingState.acquireFenceTime->getSignalTime();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -0700496
Robert Carr6a160312021-05-17 12:08:20 -0700497 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700498 setTransactionFlags(eTransactionNeeded);
499 return true;
500}
501
502bool BufferStateLayer::setDataspace(ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700503 if (mDrawingState.dataspace == dataspace) return false;
504 mDrawingState.dataspace = dataspace;
505 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700506 setTransactionFlags(eTransactionNeeded);
507 return true;
508}
509
510bool BufferStateLayer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
Robert Carr6a160312021-05-17 12:08:20 -0700511 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
512 mDrawingState.hdrMetadata = hdrMetadata;
513 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700514 setTransactionFlags(eTransactionNeeded);
515 return true;
516}
517
518bool BufferStateLayer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Robert Carr6a160312021-05-17 12:08:20 -0700519 mDrawingState.surfaceDamageRegion = surfaceDamage;
520 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700521 setTransactionFlags(eTransactionNeeded);
522 return true;
523}
524
525bool BufferStateLayer::setApi(int32_t api) {
Robert Carr6a160312021-05-17 12:08:20 -0700526 if (mDrawingState.api == api) return false;
527 mDrawingState.api = api;
528 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700529 setTransactionFlags(eTransactionNeeded);
530 return true;
531}
532
533bool BufferStateLayer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
Robert Carr6a160312021-05-17 12:08:20 -0700534 if (mDrawingState.sidebandStream == sidebandStream) return false;
Robert Carr3e2a2992021-06-11 13:42:55 -0700535
536 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
537 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
538 } else if (sidebandStream != nullptr) {
539 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
540 }
541
Robert Carr6a160312021-05-17 12:08:20 -0700542 mDrawingState.sidebandStream = sidebandStream;
543 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700544 setTransactionFlags(eTransactionNeeded);
Marissa Wall61c58622018-07-18 10:12:20 -0700545 if (!mSidebandStreamChanged.exchange(true)) {
546 // mSidebandStreamChanged was false
547 mFlinger->signalLayerUpdate();
548 }
549 return true;
550}
551
Marissa Walle2ffb422018-10-12 11:33:52 -0700552bool BufferStateLayer::setTransactionCompletedListeners(
553 const std::vector<sp<CallbackHandle>>& handles) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700554 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
Marissa Walle2ffb422018-10-12 11:33:52 -0700555 if (handles.empty()) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700556 mReleasePreviousBuffer = false;
Marissa Walle2ffb422018-10-12 11:33:52 -0700557 return false;
558 }
559
560 const bool willPresent = willPresentCurrentTransaction();
561
562 for (const auto& handle : handles) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700563 // If this transaction set a buffer on this layer, release its previous buffer
564 handle->releasePreviousBuffer = mReleasePreviousBuffer;
565
Marissa Walle2ffb422018-10-12 11:33:52 -0700566 // If this layer will be presented in this frame
567 if (willPresent) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700568 // If this transaction set an acquire fence on this layer, set its acquire time
569 handle->acquireTime = mCallbackHandleAcquireTime;
Robert Carr6a160312021-05-17 12:08:20 -0700570 handle->frameNumber = mDrawingState.frameNumber;
Marissa Wallfda30bb2018-10-12 11:34:28 -0700571
Marissa Walle2ffb422018-10-12 11:33:52 -0700572 // Notify the transaction completed thread that there is a pending latched callback
573 // handle
Robert Carr9a803c32021-01-14 16:57:58 -0800574 mFlinger->getTransactionCallbackInvoker().registerPendingCallbackHandle(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700575
576 // Store so latched time and release fence can be set
Robert Carr6a160312021-05-17 12:08:20 -0700577 mDrawingState.callbackHandles.push_back(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700578
579 } else { // If this layer will NOT need to be relatched and presented this frame
580 // Notify the transaction completed thread this handle is done
Robert Carr9a803c32021-01-14 16:57:58 -0800581 mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700582 }
583 }
584
Marissa Wallfda30bb2018-10-12 11:34:28 -0700585 mReleasePreviousBuffer = false;
586 mCallbackHandleAcquireTime = -1;
587
Marissa Walle2ffb422018-10-12 11:33:52 -0700588 return willPresent;
589}
590
Marissa Wall61c58622018-07-18 10:12:20 -0700591bool BufferStateLayer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nair27e3ed52021-07-08 18:24:25 -0700592 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -0700593 mDrawingState.transparentRegionHint = transparent;
594 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700595 setTransactionFlags(eTransactionNeeded);
596 return true;
597}
598
Marissa Wall861616d2018-10-22 12:52:23 -0700599Rect BufferStateLayer::getBufferSize(const State& s) const {
600 // for buffer state layers we use the display frame size as the buffer size.
Marissa Wall61c58622018-07-18 10:12:20 -0700601
chaviw7e72caf2020-12-02 16:50:43 -0800602 if (mBufferInfo.mBuffer == nullptr) {
603 return Rect::INVALID_RECT;
604 }
605
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700606 uint32_t bufWidth = mBufferInfo.mBuffer->getBuffer()->getWidth();
607 uint32_t bufHeight = mBufferInfo.mBuffer->getBuffer()->getHeight();
608
609 // Undo any transformations on the buffer and return the result.
610 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
611 std::swap(bufWidth, bufHeight);
612 }
613
614 if (getTransformToDisplayInverse()) {
615 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
616 if (invTransform & ui::Transform::ROT_90) {
617 std::swap(bufWidth, bufHeight);
Marissa Wall861616d2018-10-22 12:52:23 -0700618 }
619 }
620
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700621 return Rect(0, 0, bufWidth, bufHeight);
Marissa Wall61c58622018-07-18 10:12:20 -0700622}
Vishnu Nair4351ad52019-02-11 14:13:02 -0800623
624FloatRect BufferStateLayer::computeSourceBounds(const FloatRect& parentBounds) const {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700625 if (mBufferInfo.mBuffer == nullptr) {
626 return parentBounds;
Vishnu Nair4351ad52019-02-11 14:13:02 -0800627 }
628
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700629 return getBufferSize(getDrawingState()).toFloatRect();
Vishnu Nair4351ad52019-02-11 14:13:02 -0800630}
631
Marissa Wall61c58622018-07-18 10:12:20 -0700632// -----------------------------------------------------------------------
633
634// -----------------------------------------------------------------------
635// Interface implementation for BufferLayer
636// -----------------------------------------------------------------------
637bool BufferStateLayer::fenceHasSignaled() const {
Huihong Luo86c80e32021-06-16 15:41:07 -0700638 if (SurfaceFlinger::enableLatchUnsignaled) {
639 return true;
640 }
641
Alec Mouri91f6df32020-01-30 08:48:58 -0800642 const bool fenceSignaled =
643 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
644 if (!fenceSignaled) {
645 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
646 TimeStats::LatchSkipReason::LateAcquire);
647 }
648
649 return fenceSignaled;
Marissa Wall61c58622018-07-18 10:12:20 -0700650}
651
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700652bool BufferStateLayer::framePresentTimeIsCurrent(nsecs_t expectedPresentTime) const {
Ady Abrahamcd1580c2019-04-29 15:40:03 -0700653 if (!hasFrameUpdate() || isRemovedFromCurrentState()) {
654 return true;
655 }
656
Robert Carr6a160312021-05-17 12:08:20 -0700657 return mDrawingState.isAutoTimestamp || mDrawingState.desiredPresentTime <= expectedPresentTime;
Ady Abrahamcd1580c2019-04-29 15:40:03 -0700658}
659
Valerie Hau871d6352020-01-29 08:44:02 -0800660bool BufferStateLayer::onPreComposition(nsecs_t refreshStartTime) {
661 for (const auto& handle : mDrawingState.callbackHandles) {
662 handle->refreshStartTime = refreshStartTime;
663 }
664 return BufferLayer::onPreComposition(refreshStartTime);
665}
666
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700667uint64_t BufferStateLayer::getFrameNumber(nsecs_t /*expectedPresentTime*/) const {
Valerie Hau134651a2020-01-28 16:21:22 -0800668 return mDrawingState.frameNumber;
Marissa Wall61c58622018-07-18 10:12:20 -0700669}
670
Robert Carrfe1209c2020-02-11 12:25:35 -0800671/**
672 * This is the frameNumber used for deferred transaction signalling. We need to use this because
673 * of cases where we defer a transaction for a surface to itself. In the BLAST world this
674 * may not make a huge amount of sense (Why not just merge the Buffer transaction with the
675 * deferred transaction?) but this is an important legacy use case, for example moving
676 * a window at the same time it draws makes use of this kind of technique. So anyway
677 * imagine we have something like this:
678 *
679 * Transaction { // containing
680 * Buffer -> frameNumber = 2
681 * DeferTransactionUntil -> frameNumber = 2
682 * Random other stuff
683 * }
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700684 * Now imagine mFrameNumber returned mDrawingState.frameNumber (or mCurrentFrameNumber).
Robert Carrfe1209c2020-02-11 12:25:35 -0800685 * Prior to doTransaction SurfaceFlinger will call notifyAvailableFrames, but because we
Robert Carr6a160312021-05-17 12:08:20 -0700686 * haven't swapped mDrawingState to mDrawingState yet we will think the sync point
Robert Carrfe1209c2020-02-11 12:25:35 -0800687 * is not ready. So we will return false from applyPendingState and not swap
688 * current state to drawing state. But because we don't swap current state
689 * to drawing state the number will never update and we will be stuck. This way
690 * we can see we need to return the frame number for the buffer we are about
691 * to apply.
692 */
693uint64_t BufferStateLayer::getHeadFrameNumber(nsecs_t /* expectedPresentTime */) const {
Robert Carr6a160312021-05-17 12:08:20 -0700694 return mDrawingState.frameNumber;
Robert Carrfe1209c2020-02-11 12:25:35 -0800695}
696
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800697void BufferStateLayer::setAutoRefresh(bool autoRefresh) {
698 if (!mAutoRefresh.exchange(autoRefresh)) {
699 mFlinger->signalLayerUpdate();
700 }
Marissa Wall61c58622018-07-18 10:12:20 -0700701}
702
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800703bool BufferStateLayer::latchSidebandStream(bool& recomputeVisibleRegions) {
baocheng suna663c2b2021-05-13 18:51:28 +0800704 // We need to update the sideband stream if the layer has both a buffer and a sideband stream.
705 const bool updateSidebandStream = hasFrameUpdate() && mSidebandStream.get();
706
707 if (mSidebandStreamChanged.exchange(false) || updateSidebandStream) {
Marissa Wall61c58622018-07-18 10:12:20 -0700708 const State& s(getDrawingState());
709 // mSidebandStreamChanged was true
Lloyd Pique0b785d82018-12-04 17:25:27 -0800710 mSidebandStream = s.sidebandStream;
Lloyd Piquede196652020-01-22 17:29:58 -0800711 editCompositionState()->sidebandStream = mSidebandStream;
Lloyd Pique0b785d82018-12-04 17:25:27 -0800712 if (mSidebandStream != nullptr) {
Marissa Wall61c58622018-07-18 10:12:20 -0700713 setTransactionFlags(eTransactionNeeded);
714 mFlinger->setTransactionFlags(eTraversalNeeded);
715 }
716 recomputeVisibleRegions = true;
717
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800718 return true;
Marissa Wall61c58622018-07-18 10:12:20 -0700719 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800720 return false;
Marissa Wall61c58622018-07-18 10:12:20 -0700721}
722
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800723bool BufferStateLayer::hasFrameUpdate() const {
Robert Carr6a160312021-05-17 12:08:20 -0700724 const State& c(getDrawingState());
Robert Carr315f3c72021-06-24 21:58:09 -0700725 return (mDrawingStateModified || mDrawingState.modified) && (c.buffer != nullptr || c.bgColorLayer != nullptr);
Marissa Wall61c58622018-07-18 10:12:20 -0700726}
727
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700728status_t BufferStateLayer::updateTexImage(bool& /*recomputeVisibleRegions*/, nsecs_t latchTime,
729 nsecs_t /*expectedPresentTime*/) {
Marissa Wall61c58622018-07-18 10:12:20 -0700730 const State& s(getDrawingState());
731
732 if (!s.buffer) {
Valerie Hauaa194562019-02-05 16:21:38 -0800733 if (s.bgColorLayer) {
734 for (auto& handle : mDrawingState.callbackHandles) {
735 handle->latchTime = latchTime;
736 }
737 }
Marissa Wall61c58622018-07-18 10:12:20 -0700738 return NO_ERROR;
739 }
740
Marissa Wall5a68a772018-12-22 17:43:42 -0800741 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair935590e2021-02-10 13:05:52 -0800742 if (handle->frameNumber == mDrawingState.frameNumber) {
743 handle->latchTime = latchTime;
744 }
Marissa Wall5a68a772018-12-22 17:43:42 -0800745 }
Marissa Walle2ffb422018-10-12 11:33:52 -0700746
Vishnu Nairea0de002020-11-17 17:42:37 -0800747 const int32_t layerId = getSequence();
Alec Mouria90a5702021-04-16 16:36:21 +0000748 const uint64_t bufferId = mDrawingState.buffer->getBuffer()->getId();
Adithya Srinivasanb238cd52021-02-04 17:54:05 +0000749 const uint64_t frameNumber = mDrawingState.frameNumber;
750 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
751 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
752 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
753
754 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
755 FrameTracer::FrameEvent::ACQUIRE_FENCE);
756 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
757 FrameTracer::FrameEvent::LATCH);
Marissa Wall61c58622018-07-18 10:12:20 -0700758
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000759 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
760 if (bufferSurfaceFrame != nullptr &&
761 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
762 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
763 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
764 // are processing the next state.
765 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
Ady Abraham6c1b7ac2021-03-31 16:56:03 -0700766 mDrawingState.acquireFenceTime->getSignalTime(),
767 latchTime);
Robert Carr6a160312021-05-17 12:08:20 -0700768 mDrawingState.bufferSurfaceFrameTX.reset();
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000769 }
770
Vishnu Nairfc46c1e2021-04-21 08:31:32 -0700771 std::deque<sp<CallbackHandle>> remainingHandles;
772 mFlinger->getTransactionCallbackInvoker()
773 .finalizeOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
774 mDrawingState.callbackHandles = remainingHandles;
775
Robert Carr6a160312021-05-17 12:08:20 -0700776 mDrawingStateModified = false;
Marissa Wall16c112d2019-03-20 13:21:13 -0700777
Marissa Wall61c58622018-07-18 10:12:20 -0700778 return NO_ERROR;
779}
780
781status_t BufferStateLayer::updateActiveBuffer() {
782 const State& s(getDrawingState());
783
784 if (s.buffer == nullptr) {
785 return BAD_VALUE;
786 }
chaviwdf3c5e82021-01-07 13:00:37 -0800787
Alec Mouria90a5702021-04-16 16:36:21 +0000788 if (!mBufferInfo.mBuffer || s.buffer->getBuffer() != mBufferInfo.mBuffer->getBuffer()) {
chaviwdf3c5e82021-01-07 13:00:37 -0800789 decrementPendingBufferCount();
790 }
Marissa Wall61c58622018-07-18 10:12:20 -0700791
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700792 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
chaviwd62d3062019-09-04 14:48:02 -0700793 mBufferInfo.mBuffer = s.buffer;
794 mBufferInfo.mFence = s.acquireFence;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700795 mBufferInfo.mFrameNumber = s.frameNumber;
Marissa Wall61c58622018-07-18 10:12:20 -0700796
797 return NO_ERROR;
798}
799
Valerie Haubf784642020-01-29 07:25:23 -0800800status_t BufferStateLayer::updateFrameNumber(nsecs_t latchTime) {
Marissa Wall61c58622018-07-18 10:12:20 -0700801 // TODO(marissaw): support frame history events
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700802 mPreviousFrameNumber = mCurrentFrameNumber;
Valerie Hau134651a2020-01-28 16:21:22 -0800803 mCurrentFrameNumber = mDrawingState.frameNumber;
Valerie Haubf784642020-01-29 07:25:23 -0800804 {
805 Mutex::Autolock lock(mFrameEventHistoryMutex);
806 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
807 }
Marissa Wall61c58622018-07-18 10:12:20 -0700808 return NO_ERROR;
809}
810
Marissa Wall947d34e2019-03-29 14:03:53 -0700811void BufferStateLayer::HwcSlotGenerator::bufferErased(const client_cache_t& clientCacheId) {
812 std::lock_guard lock(mMutex);
813 if (!clientCacheId.isValid()) {
814 ALOGE("invalid process, failed to erase buffer");
815 return;
816 }
817 eraseBufferLocked(clientCacheId);
818}
819
820uint32_t BufferStateLayer::HwcSlotGenerator::getHwcCacheSlot(const client_cache_t& clientCacheId) {
821 std::lock_guard<std::mutex> lock(mMutex);
822 auto itr = mCachedBuffers.find(clientCacheId);
823 if (itr == mCachedBuffers.end()) {
824 return addCachedBuffer(clientCacheId);
825 }
826 auto& [hwcCacheSlot, counter] = itr->second;
827 counter = mCounter++;
828 return hwcCacheSlot;
829}
830
831uint32_t BufferStateLayer::HwcSlotGenerator::addCachedBuffer(const client_cache_t& clientCacheId)
832 REQUIRES(mMutex) {
833 if (!clientCacheId.isValid()) {
834 ALOGE("invalid process, returning invalid slot");
835 return BufferQueue::INVALID_BUFFER_SLOT;
836 }
837
838 ClientCache::getInstance().registerErasedRecipient(clientCacheId, wp<ErasedRecipient>(this));
839
840 uint32_t hwcCacheSlot = getFreeHwcCacheSlot();
841 mCachedBuffers[clientCacheId] = {hwcCacheSlot, mCounter++};
842 return hwcCacheSlot;
843}
844
845uint32_t BufferStateLayer::HwcSlotGenerator::getFreeHwcCacheSlot() REQUIRES(mMutex) {
846 if (mFreeHwcCacheSlots.empty()) {
847 evictLeastRecentlyUsed();
848 }
849
850 uint32_t hwcCacheSlot = mFreeHwcCacheSlots.top();
851 mFreeHwcCacheSlots.pop();
852 return hwcCacheSlot;
853}
854
855void BufferStateLayer::HwcSlotGenerator::evictLeastRecentlyUsed() REQUIRES(mMutex) {
856 uint64_t minCounter = UINT_MAX;
857 client_cache_t minClientCacheId = {};
858 for (const auto& [clientCacheId, slotCounter] : mCachedBuffers) {
859 const auto& [hwcCacheSlot, counter] = slotCounter;
860 if (counter < minCounter) {
861 minCounter = counter;
862 minClientCacheId = clientCacheId;
863 }
864 }
865 eraseBufferLocked(minClientCacheId);
866
867 ClientCache::getInstance().unregisterErasedRecipient(minClientCacheId, this);
868}
869
870void BufferStateLayer::HwcSlotGenerator::eraseBufferLocked(const client_cache_t& clientCacheId)
871 REQUIRES(mMutex) {
872 auto itr = mCachedBuffers.find(clientCacheId);
873 if (itr == mCachedBuffers.end()) {
874 return;
875 }
876 auto& [hwcCacheSlot, counter] = itr->second;
877
878 // TODO send to hwc cache and resources
879
880 mFreeHwcCacheSlots.push(hwcCacheSlot);
881 mCachedBuffers.erase(clientCacheId);
882}
chaviw4244e032019-09-04 11:27:49 -0700883
884void BufferStateLayer::gatherBufferInfo() {
chaviwdebadb82020-03-26 14:57:24 -0700885 BufferLayer::gatherBufferInfo();
chaviw4244e032019-09-04 11:27:49 -0700886
chaviwdebadb82020-03-26 14:57:24 -0700887 const State& s(getDrawingState());
chaviw4244e032019-09-04 11:27:49 -0700888 mBufferInfo.mDesiredPresentTime = s.desiredPresentTime;
889 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(s.acquireFence);
890 mBufferInfo.mFence = s.acquireFence;
chaviw766c9c52021-02-10 17:36:47 -0800891 mBufferInfo.mTransform = s.bufferTransform;
Robert Carr167bdde2021-07-28 11:26:51 -0700892 auto lastDataspace = mBufferInfo.mDataspace;
chaviw4244e032019-09-04 11:27:49 -0700893 mBufferInfo.mDataspace = translateDataspace(s.dataspace);
Robert Carr167bdde2021-07-28 11:26:51 -0700894 if (lastDataspace != mBufferInfo.mDataspace) {
895 mFlinger->mSomeDataspaceChanged = true;
896 }
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700897 mBufferInfo.mCrop = computeBufferCrop(s);
chaviw4244e032019-09-04 11:27:49 -0700898 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
899 mBufferInfo.mSurfaceDamage = s.surfaceDamageRegion;
900 mBufferInfo.mHdrMetadata = s.hdrMetadata;
901 mBufferInfo.mApi = s.api;
chaviw4244e032019-09-04 11:27:49 -0700902 mBufferInfo.mTransformToDisplayInverse = s.transformToDisplayInverse;
chaviwf83ce182019-09-12 14:43:08 -0700903 mBufferInfo.mBufferSlot = mHwcSlotGenerator->getHwcCacheSlot(s.clientCacheId);
chaviw4244e032019-09-04 11:27:49 -0700904}
905
Robert Carr916b0362020-10-06 13:53:03 -0700906uint32_t BufferStateLayer::getEffectiveScalingMode() const {
907 return NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
908}
909
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700910Rect BufferStateLayer::computeBufferCrop(const State& s) {
chaviwf3f40fe2021-04-27 15:54:02 -0500911 if (s.buffer && !s.bufferCrop.isEmpty()) {
912 Rect bufferCrop;
913 s.buffer->getBuffer()->getBounds().intersect(s.bufferCrop, &bufferCrop);
914 return bufferCrop;
915 } else if (s.buffer) {
Alec Mouria90a5702021-04-16 16:36:21 +0000916 return s.buffer->getBuffer()->getBounds();
chaviwf3f40fe2021-04-27 15:54:02 -0500917 } else {
918 return s.bufferCrop;
chaviw4244e032019-09-04 11:27:49 -0700919 }
chaviw4244e032019-09-04 11:27:49 -0700920}
921
chaviwb4c6e582019-08-16 14:35:07 -0700922sp<Layer> BufferStateLayer::createClone() {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700923 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, 0, 0, LayerMetadata());
chaviwb4c6e582019-08-16 14:35:07 -0700924 args.textureName = mTextureName;
Lloyd Pique1c3a5eb2019-10-03 13:07:08 -0700925 sp<BufferStateLayer> layer = mFlinger->getFactory().createBufferStateLayer(args);
chaviwb4c6e582019-08-16 14:35:07 -0700926 layer->mHwcSlotGenerator = mHwcSlotGenerator;
927 layer->setInitialValuesForClone(this);
928 return layer;
929}
Valerie Hau92bf5482020-02-10 09:49:08 -0800930
Vishnu Naire7f79c52020-10-29 14:45:03 -0700931bool BufferStateLayer::bufferNeedsFiltering() const {
932 const State& s(getDrawingState());
933 if (!s.buffer) {
934 return false;
935 }
936
Alec Mouria90a5702021-04-16 16:36:21 +0000937 uint32_t bufferWidth = s.buffer->getBuffer()->width;
938 uint32_t bufferHeight = s.buffer->getBuffer()->height;
Vishnu Naire7f79c52020-10-29 14:45:03 -0700939
940 // Undo any transformations on the buffer and return the result.
chaviw766c9c52021-02-10 17:36:47 -0800941 if (s.bufferTransform & ui::Transform::ROT_90) {
Vishnu Naire7f79c52020-10-29 14:45:03 -0700942 std::swap(bufferWidth, bufferHeight);
943 }
944
945 if (s.transformToDisplayInverse) {
946 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
947 if (invTransform & ui::Transform::ROT_90) {
948 std::swap(bufferWidth, bufferHeight);
949 }
950 }
951
952 const Rect layerSize{getBounds()};
953 return layerSize.width() != bufferWidth || layerSize.height() != bufferHeight;
954}
Robert Carr7121caf2020-12-15 13:07:32 -0800955
Robert Carr7121caf2020-12-15 13:07:32 -0800956void BufferStateLayer::decrementPendingBufferCount() {
Vishnu Nair8eda69e2021-02-26 10:42:10 -0800957 int32_t pendingBuffers = --mPendingBufferTransactions;
958 tracePendingBufferCount(pendingBuffers);
Robert Carr7121caf2020-12-15 13:07:32 -0800959}
960
Vishnu Nair8eda69e2021-02-26 10:42:10 -0800961void BufferStateLayer::tracePendingBufferCount(int32_t pendingBuffers) {
962 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
Robert Carr7121caf2020-12-15 13:07:32 -0800963}
964
Robert Carr7121caf2020-12-15 13:07:32 -0800965
chaviw39d01472021-04-08 14:26:24 -0500966/*
967 * We don't want to send the layer's transform to input, but rather the
968 * parent's transform. This is because BufferStateLayer's transform is
969 * information about how the buffer is placed on screen. The parent's
970 * transform makes more sense to send since it's information about how the
971 * layer is placed on screen. This transform is used by input to determine
972 * how to go from screen space back to window space.
973 */
974ui::Transform BufferStateLayer::getInputTransform() const {
975 sp<Layer> parent = mDrawingParent.promote();
976 if (parent == nullptr) {
977 return ui::Transform();
978 }
979
980 return parent->getTransform();
981}
982
983/**
984 * Similar to getInputTransform, we need to update the bounds to include the transform.
985 * This is because bounds for BSL doesn't include buffer transform, where the input assumes
986 * that's already included.
987 */
988Rect BufferStateLayer::getInputBounds() const {
989 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
990 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
991 return bufferBounds;
992 }
993 return mDrawingState.transform.transform(bufferBounds);
994}
995
Marissa Wall61c58622018-07-18 10:12:20 -0700996} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800997
998// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100999#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"