blob: 032ff9a572e48ced726d3af38648e39715a2a4de [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.
69 if (mBufferInfo.mBuffer != nullptr && !isClone()) {
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) {
161 if (handle->releasePreviousBuffer) {
Robert Carr8d958532020-11-10 14:09:16 -0800162 ch = handle;
Marissa Wall5a68a772018-12-22 17:43:42 -0800163 break;
164 }
165 }
Robert Carr8d958532020-11-10 14:09:16 -0800166 auto status = addReleaseFence(ch, releaseFence);
167 if (status != OK) {
168 ALOGE("Failed to add release fence for layer %s", getName().c_str());
169 }
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700170
Valerie Haubf784642020-01-29 07:25:23 -0800171 mPreviousReleaseFence = releaseFence;
172
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700173 // Prevent tracing the same release multiple times.
174 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700175 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
176 }
Marissa Wall61c58622018-07-18 10:12:20 -0700177}
178
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100179void BufferStateLayer::onSurfaceFrameCreated(
180 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasand17c7da2021-03-05 20:43:32 +0000181 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
182 // Too many SurfaceFrames pending classification. The front of the deque is probably not
183 // tracked by FrameTimeline and will never be presented. This will only result in a memory
184 // leak.
185 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
186 mName.c_str());
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000187 std::string miniDump = mPendingJankClassifications.front()->miniDump();
188 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
Adithya Srinivasand17c7da2021-03-05 20:43:32 +0000189 mPendingJankClassifications.pop_front();
190 }
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100191 mPendingJankClassifications.emplace_back(surfaceFrame);
192}
193
Valerie Haubf784642020-01-29 07:25:23 -0800194void BufferStateLayer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Valerie Hau32cdc1f2019-10-21 14:45:54 -0700195 for (const auto& handle : mDrawingState.callbackHandles) {
196 handle->transformHint = mTransformHint;
Valerie Hau871d6352020-01-29 08:44:02 -0800197 handle->dequeueReadyTime = dequeueReadyTime;
Ady Abraham899dcdb2021-06-15 16:56:21 -0700198 handle->currentMaxAcquiredBufferCount =
199 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Valerie Hau32cdc1f2019-10-21 14:45:54 -0700200 }
201
Vishnu Nair1506b182021-02-22 14:35:15 -0800202 // If there are multiple transactions in this frame, set the previous id on the earliest
203 // transacton. We don't need to pass in the released buffer id to multiple transactions.
204 // The buffer id does not have to correspond to any particular transaction as long as the
205 // listening end point is the same but the client expects the first transaction callback that
206 // replaces the presented buffer to contain the release fence. This follows the same logic.
207 // see BufferStateLayer::onLayerDisplayed.
208 for (auto& handle : mDrawingState.callbackHandles) {
209 if (handle->releasePreviousBuffer) {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700210 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
Vishnu Nair1506b182021-02-22 14:35:15 -0800211 break;
212 }
213 }
214
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100215 std::vector<JankData> jankData;
216 jankData.reserve(mPendingJankClassifications.size());
217 while (!mPendingJankClassifications.empty()
218 && mPendingJankClassifications.front()->getJankType()) {
219 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
220 mPendingJankClassifications.front();
221 mPendingJankClassifications.pop_front();
222 jankData.emplace_back(
223 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
224 }
225
Robert Carr9a803c32021-01-14 16:57:58 -0800226 mFlinger->getTransactionCallbackInvoker().finalizePendingCallbackHandles(
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100227 mDrawingState.callbackHandles, jankData);
Marissa Wall5a68a772018-12-22 17:43:42 -0800228
229 mDrawingState.callbackHandles = {};
Valerie Haubf784642020-01-29 07:25:23 -0800230
231 const sp<Fence>& releaseFence(mPreviousReleaseFence);
232 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(releaseFence);
233 {
234 Mutex::Autolock lock(mFrameEventHistoryMutex);
235 if (mPreviousFrameNumber != 0) {
236 mFrameEventHistory.addRelease(mPreviousFrameNumber, dequeueReadyTime,
237 std::move(releaseFenceTime));
238 }
239 }
Marissa Wall61c58622018-07-18 10:12:20 -0700240}
241
Valerie Hau871d6352020-01-29 08:44:02 -0800242void BufferStateLayer::finalizeFrameEventHistory(const std::shared_ptr<FenceTime>& glDoneFence,
243 const CompositorTiming& compositorTiming) {
244 for (const auto& handle : mDrawingState.callbackHandles) {
245 handle->gpuCompositionDoneFence = glDoneFence;
246 handle->compositorTiming = compositorTiming;
247 }
248}
249
Marissa Walle2ffb422018-10-12 11:33:52 -0700250bool BufferStateLayer::willPresentCurrentTransaction() const {
251 // Returns true if the most recent Transaction applied to CurrentState will be presented.
Robert Carr321e83c2019-08-19 15:49:30 -0700252 return (getSidebandStreamChanged() || getAutoRefresh() ||
Robert Carr6a160312021-05-17 12:08:20 -0700253 (mDrawingState.modified &&
254 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
Marissa Wall61c58622018-07-18 10:12:20 -0700255}
256
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000257Rect BufferStateLayer::getCrop(const Layer::State& s) const {
258 return s.crop;
Marissa Wall61c58622018-07-18 10:12:20 -0700259}
260
261bool BufferStateLayer::setTransform(uint32_t transform) {
Robert Carr6a160312021-05-17 12:08:20 -0700262 if (mDrawingState.bufferTransform == transform) return false;
263 mDrawingState.bufferTransform = transform;
264 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700265 setTransactionFlags(eTransactionNeeded);
266 return true;
267}
268
269bool BufferStateLayer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
Robert Carr6a160312021-05-17 12:08:20 -0700270 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
271 mDrawingState.sequence++;
272 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
273 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700274 setTransactionFlags(eTransactionNeeded);
275 return true;
276}
277
278bool BufferStateLayer::setCrop(const Rect& crop) {
Robert Carr6a160312021-05-17 12:08:20 -0700279 if (mDrawingState.crop == crop) return false;
280 mDrawingState.sequence++;
281 mDrawingState.crop = crop;
Marissa Wall290ad082019-03-06 13:23:47 -0800282
Robert Carr6a160312021-05-17 12:08:20 -0700283 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700284 setTransactionFlags(eTransactionNeeded);
285 return true;
286}
287
chaviwf3f40fe2021-04-27 15:54:02 -0500288bool BufferStateLayer::setBufferCrop(const Rect& bufferCrop) {
Robert Carr6a160312021-05-17 12:08:20 -0700289 if (mDrawingState.bufferCrop == bufferCrop) return false;
chaviwf3f40fe2021-04-27 15:54:02 -0500290
Robert Carr6a160312021-05-17 12:08:20 -0700291 mDrawingState.sequence++;
292 mDrawingState.bufferCrop = bufferCrop;
chaviwf3f40fe2021-04-27 15:54:02 -0500293
Robert Carr6a160312021-05-17 12:08:20 -0700294 mDrawingState.modified = true;
chaviwf3f40fe2021-04-27 15:54:02 -0500295 setTransactionFlags(eTransactionNeeded);
296 return true;
297}
298
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700299bool BufferStateLayer::setDestinationFrame(const Rect& destinationFrame) {
Robert Carr6a160312021-05-17 12:08:20 -0700300 if (mDrawingState.destinationFrame == destinationFrame) return false;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700301
Robert Carr6a160312021-05-17 12:08:20 -0700302 mDrawingState.sequence++;
303 mDrawingState.destinationFrame = destinationFrame;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700304
Robert Carr6a160312021-05-17 12:08:20 -0700305 mDrawingState.modified = true;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700306 setTransactionFlags(eTransactionNeeded);
307 return true;
308}
309
Robert Carr6a160312021-05-17 12:08:20 -0700310static bool assignTransform(ui::Transform* dst, ui::Transform& from) {
311 if (*dst == from) {
312 return false;
313 }
314 *dst = from;
315 return true;
316}
317
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700318// Translate destination frame into scale and position. If a destination frame is not set, use the
319// provided scale and position
Robert Carr6a160312021-05-17 12:08:20 -0700320bool BufferStateLayer::updateGeometry() {
321 if (mDrawingState.destinationFrame.isEmpty()) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700322 // If destination frame is not set, use the requested transform set via
323 // BufferStateLayer::setPosition and BufferStateLayer::setMatrix.
Robert Carr6a160312021-05-17 12:08:20 -0700324 return assignTransform(&mDrawingState.transform, mRequestedTransform);
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700325 }
326
Robert Carr6a160312021-05-17 12:08:20 -0700327 Rect destRect = mDrawingState.destinationFrame;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700328 int32_t destW = destRect.width();
329 int32_t destH = destRect.height();
330 if (destRect.left < 0) {
331 destRect.left = 0;
332 destRect.right = destW;
333 }
334 if (destRect.top < 0) {
335 destRect.top = 0;
336 destRect.bottom = destH;
337 }
338
Robert Carr6a160312021-05-17 12:08:20 -0700339 if (!mDrawingState.buffer) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700340 ui::Transform t;
341 t.set(destRect.left, destRect.top);
Robert Carr6a160312021-05-17 12:08:20 -0700342 return assignTransform(&mDrawingState.transform, t);
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700343 }
344
Robert Carr6a160312021-05-17 12:08:20 -0700345 uint32_t bufferWidth = mDrawingState.buffer->getBuffer()->getWidth();
346 uint32_t bufferHeight = mDrawingState.buffer->getBuffer()->getHeight();
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700347 // Undo any transformations on the buffer.
Robert Carr6a160312021-05-17 12:08:20 -0700348 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700349 std::swap(bufferWidth, bufferHeight);
350 }
351 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
Robert Carr6a160312021-05-17 12:08:20 -0700352 if (mDrawingState.transformToDisplayInverse) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700353 if (invTransform & ui::Transform::ROT_90) {
354 std::swap(bufferWidth, bufferHeight);
355 }
356 }
357
358 float sx = destW / static_cast<float>(bufferWidth);
359 float sy = destH / static_cast<float>(bufferHeight);
360 ui::Transform t;
361 t.set(sx, 0, 0, sy);
362 t.set(destRect.left, destRect.top);
Robert Carr6a160312021-05-17 12:08:20 -0700363 return assignTransform(&mDrawingState.transform, t);
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700364}
365
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000366bool BufferStateLayer::setMatrix(const layer_state_t::matrix22_t& matrix,
367 bool allowNonRectPreservingTransforms) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700368 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
369 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
Marissa Wall861616d2018-10-22 12:52:23 -0700370 return false;
371 }
372
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000373 ui::Transform t;
374 t.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
375
376 if (!allowNonRectPreservingTransforms && !t.preserveRects()) {
377 ALOGW("Attempt to set rotation matrix without permission ACCESS_SURFACE_FLINGER nor "
378 "ROTATE_SURFACE_FLINGER ignored");
379 return false;
Marissa Wall861616d2018-10-22 12:52:23 -0700380 }
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000381
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700382 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
chaviw9a93ea62021-03-11 16:44:42 -0600383
Robert Carr6a160312021-05-17 12:08:20 -0700384 mDrawingState.sequence++;
385 mDrawingState.modified = true;
chaviw9a93ea62021-03-11 16:44:42 -0600386 setTransactionFlags(eTransactionNeeded);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000387
388 return true;
389}
390
391bool BufferStateLayer::setPosition(float x, float y) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700392 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000393 return false;
394 }
395
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700396 mRequestedTransform.set(x, y);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000397
Robert Carr6a160312021-05-17 12:08:20 -0700398 mDrawingState.sequence++;
399 mDrawingState.modified = true;
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000400 setTransactionFlags(eTransactionNeeded);
401
Marissa Wall861616d2018-10-22 12:52:23 -0700402 return true;
403}
404
Valerie Hau871d6352020-01-29 08:44:02 -0800405bool BufferStateLayer::addFrameEvent(const sp<Fence>& acquireFence, nsecs_t postedTime,
406 nsecs_t desiredPresentTime) {
Valerie Haubf784642020-01-29 07:25:23 -0800407 Mutex::Autolock lock(mFrameEventHistoryMutex);
408 mAcquireTimeline.updateSignalTimes();
409 std::shared_ptr<FenceTime> acquireFenceTime =
410 std::make_shared<FenceTime>((acquireFence ? acquireFence : Fence::NO_FENCE));
Robert Carr6a160312021-05-17 12:08:20 -0700411 NewFrameEventsEntry newTimestamps = {mDrawingState.frameNumber, postedTime, desiredPresentTime,
Valerie Haubf784642020-01-29 07:25:23 -0800412 acquireFenceTime};
Valerie Hau871d6352020-01-29 08:44:02 -0800413 mFrameEventHistory.setProducerWantsEvents();
Valerie Haubf784642020-01-29 07:25:23 -0800414 mFrameEventHistory.addQueue(newTimestamps);
415 return true;
416}
417
Alec Mouria90a5702021-04-16 16:36:21 +0000418bool BufferStateLayer::setBuffer(const std::shared_ptr<renderengine::ExternalTexture>& buffer,
419 const sp<Fence>& acquireFence, nsecs_t postTime,
420 nsecs_t desiredPresentTime, bool isAutoTimestamp,
Vishnu Nairadf632b2021-01-07 14:05:08 -0800421 const client_cache_t& clientCacheId, uint64_t frameNumber,
Vishnu Nair1506b182021-02-22 14:35:15 -0800422 std::optional<nsecs_t> dequeueTime, const FrameTimelineInfo& info,
423 const sp<ITransactionCompletedListener>& releaseBufferListener) {
Robert Carr0c1966e2020-10-19 12:12:08 -0700424 ATRACE_CALL();
425
Robert Carr6a160312021-05-17 12:08:20 -0700426 if (mDrawingState.buffer) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700427 mReleasePreviousBuffer = true;
Robert Carr6a160312021-05-17 12:08:20 -0700428 if (mDrawingState.buffer != mBufferInfo.mBuffer) {
429 // If mDrawingState has a buffer, and we are about to update again
Robert Carr7121caf2020-12-15 13:07:32 -0800430 // before swapping to drawing state, then the first buffer will be
Vishnu Nair1506b182021-02-22 14:35:15 -0800431 // dropped and we should decrement the pending buffer count and
432 // call any release buffer callbacks if set.
Robert Carr6a160312021-05-17 12:08:20 -0700433 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700434 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
435 mDrawingState.acquireFence, mTransformHint,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700436 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
437 mOwnerUid));
Robert Carr7121caf2020-12-15 13:07:32 -0800438 decrementPendingBufferCount();
Robert Carr6a160312021-05-17 12:08:20 -0700439 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
440 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
441 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
442 mDrawingState.bufferSurfaceFrameTX.reset();
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000443 }
Robert Carr7121caf2020-12-15 13:07:32 -0800444 }
Marissa Wallfda30bb2018-10-12 11:34:28 -0700445 }
Robert Carr6a160312021-05-17 12:08:20 -0700446
447 mDrawingState.frameNumber = frameNumber;
448 mDrawingState.releaseBufferListener = releaseBufferListener;
449 mDrawingState.buffer = buffer;
450 mDrawingState.clientCacheId = clientCacheId;
451 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700452 setTransactionFlags(eTransactionNeeded);
Ady Abraham09bd3922019-04-08 10:44:56 -0700453
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800454 const int32_t layerId = getSequence();
Robert Carr6a160312021-05-17 12:08:20 -0700455 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000456 mOwnerUid, postTime, getGameMode());
Robert Carr6a160312021-05-17 12:08:20 -0700457 mDrawingState.desiredPresentTime = desiredPresentTime;
458 mDrawingState.isAutoTimestamp = isAutoTimestamp;
Ady Abraham09bd3922019-04-08 10:44:56 -0700459
Ady Abrahamb7f15562021-03-15 18:34:08 -0700460 const nsecs_t presentTime = [&] {
461 if (!isAutoTimestamp) return desiredPresentTime;
462
463 const auto prediction =
464 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
465 if (prediction.has_value()) return prediction->presentTime;
466
467 return static_cast<nsecs_t>(0);
468 }();
469 mFlinger->mScheduler->recordLayerHistory(this, presentTime,
Ady Abraham5def7332020-05-29 16:13:47 -0700470 LayerHistory::LayerUpdateType::Buffer);
Ady Abraham09bd3922019-04-08 10:44:56 -0700471
Ady Abrahamf0c56492020-12-17 18:04:15 -0800472 addFrameEvent(acquireFence, postTime, isAutoTimestamp ? 0 : desiredPresentTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000473
Adithya Srinivasan891004e2021-02-12 20:20:47 +0000474 setFrameTimelineVsyncForBufferTransaction(info, postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000475
Alec Mouria90a5702021-04-16 16:36:21 +0000476 if (buffer && dequeueTime && *dequeueTime != 0) {
477 const uint64_t bufferId = buffer->getBuffer()->getId();
Adithya Srinivasanb238cd52021-02-04 17:54:05 +0000478 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
479 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
480 FrameTracer::FrameEvent::DEQUEUE);
481 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
482 FrameTracer::FrameEvent::QUEUE);
483 }
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000484
Robert Carr6a160312021-05-17 12:08:20 -0700485 mDrawingState.width = mDrawingState.buffer->getBuffer()->getWidth();
486 mDrawingState.height = mDrawingState.buffer->getBuffer()->getHeight();
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000487
Marissa Wall61c58622018-07-18 10:12:20 -0700488 return true;
489}
490
491bool BufferStateLayer::setAcquireFence(const sp<Fence>& fence) {
Robert Carr6a160312021-05-17 12:08:20 -0700492 mDrawingState.acquireFence = fence;
493 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(fence);
Ady Abraham6c1b7ac2021-03-31 16:56:03 -0700494
495 // The acquire fences of BufferStateLayers have already signaled before they are set
Robert Carr6a160312021-05-17 12:08:20 -0700496 mCallbackHandleAcquireTime = mDrawingState.acquireFenceTime->getSignalTime();
Ady Abraham6c1b7ac2021-03-31 16:56:03 -0700497
Robert Carr6a160312021-05-17 12:08:20 -0700498 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700499 setTransactionFlags(eTransactionNeeded);
500 return true;
501}
502
503bool BufferStateLayer::setDataspace(ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700504 if (mDrawingState.dataspace == dataspace) return false;
505 mDrawingState.dataspace = dataspace;
506 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700507 setTransactionFlags(eTransactionNeeded);
508 return true;
509}
510
511bool BufferStateLayer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
Robert Carr6a160312021-05-17 12:08:20 -0700512 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
513 mDrawingState.hdrMetadata = hdrMetadata;
514 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700515 setTransactionFlags(eTransactionNeeded);
516 return true;
517}
518
519bool BufferStateLayer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Robert Carr6a160312021-05-17 12:08:20 -0700520 mDrawingState.surfaceDamageRegion = surfaceDamage;
521 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700522 setTransactionFlags(eTransactionNeeded);
523 return true;
524}
525
526bool BufferStateLayer::setApi(int32_t api) {
Robert Carr6a160312021-05-17 12:08:20 -0700527 if (mDrawingState.api == api) return false;
528 mDrawingState.api = api;
529 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700530 setTransactionFlags(eTransactionNeeded);
531 return true;
532}
533
534bool BufferStateLayer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
Robert Carr6a160312021-05-17 12:08:20 -0700535 if (mDrawingState.sidebandStream == sidebandStream) return false;
Robert Carr3e2a2992021-06-11 13:42:55 -0700536
537 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
538 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
539 } else if (sidebandStream != nullptr) {
540 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
541 }
542
Robert Carr6a160312021-05-17 12:08:20 -0700543 mDrawingState.sidebandStream = sidebandStream;
544 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700545 setTransactionFlags(eTransactionNeeded);
Marissa Wall61c58622018-07-18 10:12:20 -0700546 if (!mSidebandStreamChanged.exchange(true)) {
547 // mSidebandStreamChanged was false
548 mFlinger->signalLayerUpdate();
549 }
550 return true;
551}
552
Marissa Walle2ffb422018-10-12 11:33:52 -0700553bool BufferStateLayer::setTransactionCompletedListeners(
554 const std::vector<sp<CallbackHandle>>& handles) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700555 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
Marissa Walle2ffb422018-10-12 11:33:52 -0700556 if (handles.empty()) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700557 mReleasePreviousBuffer = false;
Marissa Walle2ffb422018-10-12 11:33:52 -0700558 return false;
559 }
560
561 const bool willPresent = willPresentCurrentTransaction();
562
563 for (const auto& handle : handles) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700564 // If this transaction set a buffer on this layer, release its previous buffer
565 handle->releasePreviousBuffer = mReleasePreviousBuffer;
566
Marissa Walle2ffb422018-10-12 11:33:52 -0700567 // If this layer will be presented in this frame
568 if (willPresent) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700569 // If this transaction set an acquire fence on this layer, set its acquire time
570 handle->acquireTime = mCallbackHandleAcquireTime;
Robert Carr6a160312021-05-17 12:08:20 -0700571 handle->frameNumber = mDrawingState.frameNumber;
Marissa Wallfda30bb2018-10-12 11:34:28 -0700572
Marissa Walle2ffb422018-10-12 11:33:52 -0700573 // Notify the transaction completed thread that there is a pending latched callback
574 // handle
Robert Carr9a803c32021-01-14 16:57:58 -0800575 mFlinger->getTransactionCallbackInvoker().registerPendingCallbackHandle(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700576
577 // Store so latched time and release fence can be set
Robert Carr6a160312021-05-17 12:08:20 -0700578 mDrawingState.callbackHandles.push_back(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700579
580 } else { // If this layer will NOT need to be relatched and presented this frame
581 // Notify the transaction completed thread this handle is done
Robert Carr9a803c32021-01-14 16:57:58 -0800582 mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700583 }
584 }
585
Marissa Wallfda30bb2018-10-12 11:34:28 -0700586 mReleasePreviousBuffer = false;
587 mCallbackHandleAcquireTime = -1;
588
Marissa Walle2ffb422018-10-12 11:33:52 -0700589 return willPresent;
590}
591
Marissa Wall61c58622018-07-18 10:12:20 -0700592bool BufferStateLayer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nair27e3ed52021-07-08 18:24:25 -0700593 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -0700594 mDrawingState.transparentRegionHint = transparent;
595 mDrawingState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700596 setTransactionFlags(eTransactionNeeded);
597 return true;
598}
599
Marissa Wall861616d2018-10-22 12:52:23 -0700600Rect BufferStateLayer::getBufferSize(const State& s) const {
601 // for buffer state layers we use the display frame size as the buffer size.
Marissa Wall61c58622018-07-18 10:12:20 -0700602
chaviw7e72caf2020-12-02 16:50:43 -0800603 if (mBufferInfo.mBuffer == nullptr) {
604 return Rect::INVALID_RECT;
605 }
606
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700607 uint32_t bufWidth = mBufferInfo.mBuffer->getBuffer()->getWidth();
608 uint32_t bufHeight = mBufferInfo.mBuffer->getBuffer()->getHeight();
609
610 // Undo any transformations on the buffer and return the result.
611 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
612 std::swap(bufWidth, bufHeight);
613 }
614
615 if (getTransformToDisplayInverse()) {
616 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
617 if (invTransform & ui::Transform::ROT_90) {
618 std::swap(bufWidth, bufHeight);
Marissa Wall861616d2018-10-22 12:52:23 -0700619 }
620 }
621
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700622 return Rect(0, 0, bufWidth, bufHeight);
Marissa Wall61c58622018-07-18 10:12:20 -0700623}
Vishnu Nair4351ad52019-02-11 14:13:02 -0800624
625FloatRect BufferStateLayer::computeSourceBounds(const FloatRect& parentBounds) const {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700626 if (mBufferInfo.mBuffer == nullptr) {
627 return parentBounds;
Vishnu Nair4351ad52019-02-11 14:13:02 -0800628 }
629
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700630 return getBufferSize(getDrawingState()).toFloatRect();
Vishnu Nair4351ad52019-02-11 14:13:02 -0800631}
632
Marissa Wall61c58622018-07-18 10:12:20 -0700633// -----------------------------------------------------------------------
634
635// -----------------------------------------------------------------------
636// Interface implementation for BufferLayer
637// -----------------------------------------------------------------------
638bool BufferStateLayer::fenceHasSignaled() const {
Huihong Luo86c80e32021-06-16 15:41:07 -0700639 if (SurfaceFlinger::enableLatchUnsignaled) {
640 return true;
641 }
642
Alec Mouri91f6df32020-01-30 08:48:58 -0800643 const bool fenceSignaled =
644 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
645 if (!fenceSignaled) {
646 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
647 TimeStats::LatchSkipReason::LateAcquire);
648 }
649
650 return fenceSignaled;
Marissa Wall61c58622018-07-18 10:12:20 -0700651}
652
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700653bool BufferStateLayer::framePresentTimeIsCurrent(nsecs_t expectedPresentTime) const {
Ady Abrahamcd1580c2019-04-29 15:40:03 -0700654 if (!hasFrameUpdate() || isRemovedFromCurrentState()) {
655 return true;
656 }
657
Robert Carr6a160312021-05-17 12:08:20 -0700658 return mDrawingState.isAutoTimestamp || mDrawingState.desiredPresentTime <= expectedPresentTime;
Ady Abrahamcd1580c2019-04-29 15:40:03 -0700659}
660
Valerie Hau871d6352020-01-29 08:44:02 -0800661bool BufferStateLayer::onPreComposition(nsecs_t refreshStartTime) {
662 for (const auto& handle : mDrawingState.callbackHandles) {
663 handle->refreshStartTime = refreshStartTime;
664 }
665 return BufferLayer::onPreComposition(refreshStartTime);
666}
667
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700668uint64_t BufferStateLayer::getFrameNumber(nsecs_t /*expectedPresentTime*/) const {
Valerie Hau134651a2020-01-28 16:21:22 -0800669 return mDrawingState.frameNumber;
Marissa Wall61c58622018-07-18 10:12:20 -0700670}
671
Robert Carrfe1209c2020-02-11 12:25:35 -0800672/**
673 * This is the frameNumber used for deferred transaction signalling. We need to use this because
674 * of cases where we defer a transaction for a surface to itself. In the BLAST world this
675 * may not make a huge amount of sense (Why not just merge the Buffer transaction with the
676 * deferred transaction?) but this is an important legacy use case, for example moving
677 * a window at the same time it draws makes use of this kind of technique. So anyway
678 * imagine we have something like this:
679 *
680 * Transaction { // containing
681 * Buffer -> frameNumber = 2
682 * DeferTransactionUntil -> frameNumber = 2
683 * Random other stuff
684 * }
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700685 * Now imagine mFrameNumber returned mDrawingState.frameNumber (or mCurrentFrameNumber).
Robert Carrfe1209c2020-02-11 12:25:35 -0800686 * Prior to doTransaction SurfaceFlinger will call notifyAvailableFrames, but because we
Robert Carr6a160312021-05-17 12:08:20 -0700687 * haven't swapped mDrawingState to mDrawingState yet we will think the sync point
Robert Carrfe1209c2020-02-11 12:25:35 -0800688 * is not ready. So we will return false from applyPendingState and not swap
689 * current state to drawing state. But because we don't swap current state
690 * to drawing state the number will never update and we will be stuck. This way
691 * we can see we need to return the frame number for the buffer we are about
692 * to apply.
693 */
694uint64_t BufferStateLayer::getHeadFrameNumber(nsecs_t /* expectedPresentTime */) const {
Robert Carr6a160312021-05-17 12:08:20 -0700695 return mDrawingState.frameNumber;
Robert Carrfe1209c2020-02-11 12:25:35 -0800696}
697
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800698void BufferStateLayer::setAutoRefresh(bool autoRefresh) {
699 if (!mAutoRefresh.exchange(autoRefresh)) {
700 mFlinger->signalLayerUpdate();
701 }
Marissa Wall61c58622018-07-18 10:12:20 -0700702}
703
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800704bool BufferStateLayer::latchSidebandStream(bool& recomputeVisibleRegions) {
baocheng suna663c2b2021-05-13 18:51:28 +0800705 // We need to update the sideband stream if the layer has both a buffer and a sideband stream.
706 const bool updateSidebandStream = hasFrameUpdate() && mSidebandStream.get();
707
708 if (mSidebandStreamChanged.exchange(false) || updateSidebandStream) {
Marissa Wall61c58622018-07-18 10:12:20 -0700709 const State& s(getDrawingState());
710 // mSidebandStreamChanged was true
Lloyd Pique0b785d82018-12-04 17:25:27 -0800711 mSidebandStream = s.sidebandStream;
Lloyd Piquede196652020-01-22 17:29:58 -0800712 editCompositionState()->sidebandStream = mSidebandStream;
Lloyd Pique0b785d82018-12-04 17:25:27 -0800713 if (mSidebandStream != nullptr) {
Marissa Wall61c58622018-07-18 10:12:20 -0700714 setTransactionFlags(eTransactionNeeded);
715 mFlinger->setTransactionFlags(eTraversalNeeded);
716 }
717 recomputeVisibleRegions = true;
718
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800719 return true;
Marissa Wall61c58622018-07-18 10:12:20 -0700720 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800721 return false;
Marissa Wall61c58622018-07-18 10:12:20 -0700722}
723
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800724bool BufferStateLayer::hasFrameUpdate() const {
Robert Carr6a160312021-05-17 12:08:20 -0700725 const State& c(getDrawingState());
Robert Carr315f3c72021-06-24 21:58:09 -0700726 return (mDrawingStateModified || mDrawingState.modified) && (c.buffer != nullptr || c.bgColorLayer != nullptr);
Marissa Wall61c58622018-07-18 10:12:20 -0700727}
728
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700729status_t BufferStateLayer::updateTexImage(bool& /*recomputeVisibleRegions*/, nsecs_t latchTime,
730 nsecs_t /*expectedPresentTime*/) {
Marissa Wall61c58622018-07-18 10:12:20 -0700731 const State& s(getDrawingState());
732
733 if (!s.buffer) {
Valerie Hauaa194562019-02-05 16:21:38 -0800734 if (s.bgColorLayer) {
735 for (auto& handle : mDrawingState.callbackHandles) {
736 handle->latchTime = latchTime;
737 }
738 }
Marissa Wall61c58622018-07-18 10:12:20 -0700739 return NO_ERROR;
740 }
741
Marissa Wall5a68a772018-12-22 17:43:42 -0800742 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair935590e2021-02-10 13:05:52 -0800743 if (handle->frameNumber == mDrawingState.frameNumber) {
744 handle->latchTime = latchTime;
745 }
Marissa Wall5a68a772018-12-22 17:43:42 -0800746 }
Marissa Walle2ffb422018-10-12 11:33:52 -0700747
Vishnu Nairea0de002020-11-17 17:42:37 -0800748 const int32_t layerId = getSequence();
Alec Mouria90a5702021-04-16 16:36:21 +0000749 const uint64_t bufferId = mDrawingState.buffer->getBuffer()->getId();
Adithya Srinivasanb238cd52021-02-04 17:54:05 +0000750 const uint64_t frameNumber = mDrawingState.frameNumber;
751 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
752 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
753 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
754
755 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
756 FrameTracer::FrameEvent::ACQUIRE_FENCE);
757 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
758 FrameTracer::FrameEvent::LATCH);
Marissa Wall61c58622018-07-18 10:12:20 -0700759
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000760 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
761 if (bufferSurfaceFrame != nullptr &&
762 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
763 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
764 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
765 // are processing the next state.
766 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
Ady Abraham6c1b7ac2021-03-31 16:56:03 -0700767 mDrawingState.acquireFenceTime->getSignalTime(),
768 latchTime);
Robert Carr6a160312021-05-17 12:08:20 -0700769 mDrawingState.bufferSurfaceFrameTX.reset();
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000770 }
771
Vishnu Nairfc46c1e2021-04-21 08:31:32 -0700772 std::deque<sp<CallbackHandle>> remainingHandles;
773 mFlinger->getTransactionCallbackInvoker()
774 .finalizeOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
775 mDrawingState.callbackHandles = remainingHandles;
776
Robert Carr6a160312021-05-17 12:08:20 -0700777 mDrawingStateModified = false;
Marissa Wall16c112d2019-03-20 13:21:13 -0700778
Marissa Wall61c58622018-07-18 10:12:20 -0700779 return NO_ERROR;
780}
781
782status_t BufferStateLayer::updateActiveBuffer() {
783 const State& s(getDrawingState());
784
785 if (s.buffer == nullptr) {
786 return BAD_VALUE;
787 }
chaviwdf3c5e82021-01-07 13:00:37 -0800788
Alec Mouria90a5702021-04-16 16:36:21 +0000789 if (!mBufferInfo.mBuffer || s.buffer->getBuffer() != mBufferInfo.mBuffer->getBuffer()) {
chaviwdf3c5e82021-01-07 13:00:37 -0800790 decrementPendingBufferCount();
791 }
Marissa Wall61c58622018-07-18 10:12:20 -0700792
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700793 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
chaviwd62d3062019-09-04 14:48:02 -0700794 mBufferInfo.mBuffer = s.buffer;
795 mBufferInfo.mFence = s.acquireFence;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700796 mBufferInfo.mFrameNumber = s.frameNumber;
Marissa Wall61c58622018-07-18 10:12:20 -0700797
798 return NO_ERROR;
799}
800
Valerie Haubf784642020-01-29 07:25:23 -0800801status_t BufferStateLayer::updateFrameNumber(nsecs_t latchTime) {
Marissa Wall61c58622018-07-18 10:12:20 -0700802 // TODO(marissaw): support frame history events
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700803 mPreviousFrameNumber = mCurrentFrameNumber;
Valerie Hau134651a2020-01-28 16:21:22 -0800804 mCurrentFrameNumber = mDrawingState.frameNumber;
Valerie Haubf784642020-01-29 07:25:23 -0800805 {
806 Mutex::Autolock lock(mFrameEventHistoryMutex);
807 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
808 }
Marissa Wall61c58622018-07-18 10:12:20 -0700809 return NO_ERROR;
810}
811
Marissa Wall947d34e2019-03-29 14:03:53 -0700812void BufferStateLayer::HwcSlotGenerator::bufferErased(const client_cache_t& clientCacheId) {
813 std::lock_guard lock(mMutex);
814 if (!clientCacheId.isValid()) {
815 ALOGE("invalid process, failed to erase buffer");
816 return;
817 }
818 eraseBufferLocked(clientCacheId);
819}
820
821uint32_t BufferStateLayer::HwcSlotGenerator::getHwcCacheSlot(const client_cache_t& clientCacheId) {
822 std::lock_guard<std::mutex> lock(mMutex);
823 auto itr = mCachedBuffers.find(clientCacheId);
824 if (itr == mCachedBuffers.end()) {
825 return addCachedBuffer(clientCacheId);
826 }
827 auto& [hwcCacheSlot, counter] = itr->second;
828 counter = mCounter++;
829 return hwcCacheSlot;
830}
831
832uint32_t BufferStateLayer::HwcSlotGenerator::addCachedBuffer(const client_cache_t& clientCacheId)
833 REQUIRES(mMutex) {
834 if (!clientCacheId.isValid()) {
835 ALOGE("invalid process, returning invalid slot");
836 return BufferQueue::INVALID_BUFFER_SLOT;
837 }
838
839 ClientCache::getInstance().registerErasedRecipient(clientCacheId, wp<ErasedRecipient>(this));
840
841 uint32_t hwcCacheSlot = getFreeHwcCacheSlot();
842 mCachedBuffers[clientCacheId] = {hwcCacheSlot, mCounter++};
843 return hwcCacheSlot;
844}
845
846uint32_t BufferStateLayer::HwcSlotGenerator::getFreeHwcCacheSlot() REQUIRES(mMutex) {
847 if (mFreeHwcCacheSlots.empty()) {
848 evictLeastRecentlyUsed();
849 }
850
851 uint32_t hwcCacheSlot = mFreeHwcCacheSlots.top();
852 mFreeHwcCacheSlots.pop();
853 return hwcCacheSlot;
854}
855
856void BufferStateLayer::HwcSlotGenerator::evictLeastRecentlyUsed() REQUIRES(mMutex) {
857 uint64_t minCounter = UINT_MAX;
858 client_cache_t minClientCacheId = {};
859 for (const auto& [clientCacheId, slotCounter] : mCachedBuffers) {
860 const auto& [hwcCacheSlot, counter] = slotCounter;
861 if (counter < minCounter) {
862 minCounter = counter;
863 minClientCacheId = clientCacheId;
864 }
865 }
866 eraseBufferLocked(minClientCacheId);
867
868 ClientCache::getInstance().unregisterErasedRecipient(minClientCacheId, this);
869}
870
871void BufferStateLayer::HwcSlotGenerator::eraseBufferLocked(const client_cache_t& clientCacheId)
872 REQUIRES(mMutex) {
873 auto itr = mCachedBuffers.find(clientCacheId);
874 if (itr == mCachedBuffers.end()) {
875 return;
876 }
877 auto& [hwcCacheSlot, counter] = itr->second;
878
879 // TODO send to hwc cache and resources
880
881 mFreeHwcCacheSlots.push(hwcCacheSlot);
882 mCachedBuffers.erase(clientCacheId);
883}
chaviw4244e032019-09-04 11:27:49 -0700884
885void BufferStateLayer::gatherBufferInfo() {
chaviwdebadb82020-03-26 14:57:24 -0700886 BufferLayer::gatherBufferInfo();
chaviw4244e032019-09-04 11:27:49 -0700887
chaviwdebadb82020-03-26 14:57:24 -0700888 const State& s(getDrawingState());
chaviw4244e032019-09-04 11:27:49 -0700889 mBufferInfo.mDesiredPresentTime = s.desiredPresentTime;
890 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(s.acquireFence);
891 mBufferInfo.mFence = s.acquireFence;
chaviw766c9c52021-02-10 17:36:47 -0800892 mBufferInfo.mTransform = s.bufferTransform;
chaviw4244e032019-09-04 11:27:49 -0700893 mBufferInfo.mDataspace = translateDataspace(s.dataspace);
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700894 mBufferInfo.mCrop = computeBufferCrop(s);
chaviw4244e032019-09-04 11:27:49 -0700895 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
896 mBufferInfo.mSurfaceDamage = s.surfaceDamageRegion;
897 mBufferInfo.mHdrMetadata = s.hdrMetadata;
898 mBufferInfo.mApi = s.api;
chaviw4244e032019-09-04 11:27:49 -0700899 mBufferInfo.mTransformToDisplayInverse = s.transformToDisplayInverse;
chaviwf83ce182019-09-12 14:43:08 -0700900 mBufferInfo.mBufferSlot = mHwcSlotGenerator->getHwcCacheSlot(s.clientCacheId);
chaviw4244e032019-09-04 11:27:49 -0700901}
902
Robert Carr916b0362020-10-06 13:53:03 -0700903uint32_t BufferStateLayer::getEffectiveScalingMode() const {
904 return NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
905}
906
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700907Rect BufferStateLayer::computeBufferCrop(const State& s) {
chaviwf3f40fe2021-04-27 15:54:02 -0500908 if (s.buffer && !s.bufferCrop.isEmpty()) {
909 Rect bufferCrop;
910 s.buffer->getBuffer()->getBounds().intersect(s.bufferCrop, &bufferCrop);
911 return bufferCrop;
912 } else if (s.buffer) {
Alec Mouria90a5702021-04-16 16:36:21 +0000913 return s.buffer->getBuffer()->getBounds();
chaviwf3f40fe2021-04-27 15:54:02 -0500914 } else {
915 return s.bufferCrop;
chaviw4244e032019-09-04 11:27:49 -0700916 }
chaviw4244e032019-09-04 11:27:49 -0700917}
918
chaviwb4c6e582019-08-16 14:35:07 -0700919sp<Layer> BufferStateLayer::createClone() {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700920 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, 0, 0, LayerMetadata());
chaviwb4c6e582019-08-16 14:35:07 -0700921 args.textureName = mTextureName;
Lloyd Pique1c3a5eb2019-10-03 13:07:08 -0700922 sp<BufferStateLayer> layer = mFlinger->getFactory().createBufferStateLayer(args);
chaviwb4c6e582019-08-16 14:35:07 -0700923 layer->mHwcSlotGenerator = mHwcSlotGenerator;
924 layer->setInitialValuesForClone(this);
925 return layer;
926}
Valerie Hau92bf5482020-02-10 09:49:08 -0800927
Vishnu Naire7f79c52020-10-29 14:45:03 -0700928bool BufferStateLayer::bufferNeedsFiltering() const {
929 const State& s(getDrawingState());
930 if (!s.buffer) {
931 return false;
932 }
933
Alec Mouria90a5702021-04-16 16:36:21 +0000934 uint32_t bufferWidth = s.buffer->getBuffer()->width;
935 uint32_t bufferHeight = s.buffer->getBuffer()->height;
Vishnu Naire7f79c52020-10-29 14:45:03 -0700936
937 // Undo any transformations on the buffer and return the result.
chaviw766c9c52021-02-10 17:36:47 -0800938 if (s.bufferTransform & ui::Transform::ROT_90) {
Vishnu Naire7f79c52020-10-29 14:45:03 -0700939 std::swap(bufferWidth, bufferHeight);
940 }
941
942 if (s.transformToDisplayInverse) {
943 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
944 if (invTransform & ui::Transform::ROT_90) {
945 std::swap(bufferWidth, bufferHeight);
946 }
947 }
948
949 const Rect layerSize{getBounds()};
950 return layerSize.width() != bufferWidth || layerSize.height() != bufferHeight;
951}
Robert Carr7121caf2020-12-15 13:07:32 -0800952
Robert Carr7121caf2020-12-15 13:07:32 -0800953void BufferStateLayer::decrementPendingBufferCount() {
Vishnu Nair8eda69e2021-02-26 10:42:10 -0800954 int32_t pendingBuffers = --mPendingBufferTransactions;
955 tracePendingBufferCount(pendingBuffers);
Robert Carr7121caf2020-12-15 13:07:32 -0800956}
957
Vishnu Nair8eda69e2021-02-26 10:42:10 -0800958void BufferStateLayer::tracePendingBufferCount(int32_t pendingBuffers) {
959 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
Robert Carr7121caf2020-12-15 13:07:32 -0800960}
961
Alec Mouria90a5702021-04-16 16:36:21 +0000962void BufferStateLayer::bufferMayChange(const sp<GraphicBuffer>& newBuffer) {
963 if (mDrawingState.buffer != nullptr &&
964 (!mBufferInfo.mBuffer ||
965 mDrawingState.buffer->getBuffer() != mBufferInfo.mBuffer->getBuffer()) &&
966 newBuffer != mDrawingState.buffer->getBuffer()) {
Robert Carr7121caf2020-12-15 13:07:32 -0800967 // If we are about to update mDrawingState.buffer but it has not yet latched
Vishnu Nair1506b182021-02-22 14:35:15 -0800968 // then we will drop a buffer and should decrement the pending buffer count and
969 // call any release buffer callbacks if set.
Alec Mouria90a5702021-04-16 16:36:21 +0000970 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700971 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
972 mDrawingState.acquireFence, mTransformHint,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700973 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
974 mOwnerUid));
Robert Carr7121caf2020-12-15 13:07:32 -0800975 decrementPendingBufferCount();
976 }
Robert Carr7121caf2020-12-15 13:07:32 -0800977}
978
chaviw39d01472021-04-08 14:26:24 -0500979/*
980 * We don't want to send the layer's transform to input, but rather the
981 * parent's transform. This is because BufferStateLayer's transform is
982 * information about how the buffer is placed on screen. The parent's
983 * transform makes more sense to send since it's information about how the
984 * layer is placed on screen. This transform is used by input to determine
985 * how to go from screen space back to window space.
986 */
987ui::Transform BufferStateLayer::getInputTransform() const {
988 sp<Layer> parent = mDrawingParent.promote();
989 if (parent == nullptr) {
990 return ui::Transform();
991 }
992
993 return parent->getTransform();
994}
995
996/**
997 * Similar to getInputTransform, we need to update the bounds to include the transform.
998 * This is because bounds for BSL doesn't include buffer transform, where the input assumes
999 * that's already included.
1000 */
1001Rect BufferStateLayer::getInputBounds() const {
1002 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
1003 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
1004 return bufferBounds;
1005 }
1006 return mDrawingState.transform.transform(bufferBounds);
1007}
1008
Marissa Wall61c58622018-07-18 10:12:20 -07001009} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08001010
1011// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01001012#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"