blob: d68a0e0b471ca02dfb777f19db08682e6cd2d9d4 [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>
Marissa Wall61c58622018-07-18 10:12:20 -070036
Vishnu Nairfa247b12020-02-11 08:58:26 -080037#include "EffectLayer.h"
Adithya Srinivasanb238cd52021-02-04 17:54:05 +000038#include "FrameTracer/FrameTracer.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080039#include "TimeStats/TimeStats.h"
Valerie Hau0bc09152018-12-20 07:42:47 -080040
Marissa Wall61c58622018-07-18 10:12:20 -070041namespace android {
42
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +000043using PresentState = frametimeline::SurfaceFrame::PresentState;
Vishnu Nair1506b182021-02-22 14:35:15 -080044namespace {
45void callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
Robert Carr97e7cc02021-06-07 10:45:40 -070046 const sp<GraphicBuffer>& buffer, const sp<Fence>& releaseFence,
47 uint32_t transformHint) {
Vishnu Nair1506b182021-02-22 14:35:15 -080048 if (!listener) {
49 return;
50 }
Robert Carr97e7cc02021-06-07 10:45:40 -070051 listener->onReleaseBuffer(buffer->getId(), releaseFence ? releaseFence : Fence::NO_FENCE,
52 transformHint);
Vishnu Nair1506b182021-02-22 14:35:15 -080053}
54} // namespace
55
Lloyd Pique42ab75e2018-09-12 20:46:03 -070056// clang-format off
57const std::array<float, 16> BufferStateLayer::IDENTITY_MATRIX{
58 1, 0, 0, 0,
59 0, 1, 0, 0,
60 0, 0, 1, 0,
61 0, 0, 0, 1
62};
63// clang-format on
Marissa Wall61c58622018-07-18 10:12:20 -070064
Marissa Wall947d34e2019-03-29 14:03:53 -070065BufferStateLayer::BufferStateLayer(const LayerCreationArgs& args)
66 : BufferLayer(args), mHwcSlotGenerator(new HwcSlotGenerator()) {
Marissa Wall3ff826c2019-02-07 11:58:25 -080067 mCurrentState.dataspace = ui::Dataspace::V0_SRGB;
Vishnu Nair60356342018-11-13 13:00:45 -080068}
Marissa Wall61c58622018-07-18 10:12:20 -070069
Alec Mouri4545a8a2019-08-08 20:05:32 -070070BufferStateLayer::~BufferStateLayer() {
chaviwb4c6e582019-08-16 14:35:07 -070071 // The original layer and the clone layer share the same texture and buffer. Therefore, only
72 // one of the layers, in this case the original layer, needs to handle the deletion. The
73 // original layer and the clone should be removed at the same time so there shouldn't be any
74 // issue with the clone layer trying to use the texture.
75 if (mBufferInfo.mBuffer != nullptr && !isClone()) {
Alec Mouria90a5702021-04-16 16:36:21 +000076 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
Robert Carr97e7cc02021-06-07 10:45:40 -070077 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFence,
78 mTransformHint);
Alec Mouri4545a8a2019-08-08 20:05:32 -070079 }
80}
81
Robert Carr8d958532020-11-10 14:09:16 -080082status_t BufferStateLayer::addReleaseFence(const sp<CallbackHandle>& ch,
83 const sp<Fence>& fence) {
84 if (ch == nullptr) {
85 return OK;
86 }
Vishnu Nair1506b182021-02-22 14:35:15 -080087 ch->previousBufferId = mPreviousBufferId;
Robert Carr8d958532020-11-10 14:09:16 -080088 if (!ch->previousReleaseFence.get()) {
89 ch->previousReleaseFence = fence;
90 return OK;
91 }
92
93 // Below logic is lifted from ConsumerBase.cpp:
94 // Check status of fences first because merging is expensive.
95 // Merging an invalid fence with any other fence results in an
96 // invalid fence.
97 auto currentStatus = ch->previousReleaseFence->getStatus();
98 if (currentStatus == Fence::Status::Invalid) {
99 ALOGE("Existing fence has invalid state, layer: %s", mName.c_str());
100 return BAD_VALUE;
101 }
102
103 auto incomingStatus = fence->getStatus();
104 if (incomingStatus == Fence::Status::Invalid) {
105 ALOGE("New fence has invalid state, layer: %s", mName.c_str());
106 ch->previousReleaseFence = fence;
107 return BAD_VALUE;
108 }
109
110 // If both fences are signaled or both are unsignaled, we need to merge
111 // them to get an accurate timestamp.
112 if (currentStatus == incomingStatus) {
113 char fenceName[32] = {};
114 snprintf(fenceName, 32, "%.28s", mName.c_str());
115 sp<Fence> mergedFence = Fence::merge(
116 fenceName, ch->previousReleaseFence, fence);
117 if (!mergedFence.get()) {
118 ALOGE("failed to merge release fences, layer: %s", mName.c_str());
119 // synchronization is broken, the best we can do is hope fences
120 // signal in order so the new fence will act like a union
121 ch->previousReleaseFence = fence;
122 return BAD_VALUE;
123 }
124 ch->previousReleaseFence = mergedFence;
125 } else if (incomingStatus == Fence::Status::Unsignaled) {
126 // If one fence has signaled and the other hasn't, the unsignaled
127 // fence will approximately correspond with the correct timestamp.
128 // There's a small race if both fences signal at about the same time
129 // and their statuses are retrieved with unfortunate timing. However,
130 // by this point, they will have both signaled and only the timestamp
131 // will be slightly off; any dependencies after this point will
132 // already have been met.
133 ch->previousReleaseFence = fence;
134 }
135 // else if (currentStatus == Fence::Status::Unsignaled) is a no-op.
136
137 return OK;
138}
139
Marissa Wall61c58622018-07-18 10:12:20 -0700140// -----------------------------------------------------------------------
141// Interface implementation for Layer
142// -----------------------------------------------------------------------
Marissa Wallfda30bb2018-10-12 11:34:28 -0700143void BufferStateLayer::onLayerDisplayed(const sp<Fence>& releaseFence) {
Robert Carr8d958532020-11-10 14:09:16 -0800144 if (!releaseFence->isValid()) {
145 return;
146 }
Marissa Wall5a68a772018-12-22 17:43:42 -0800147 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
148 // buffer that was presented on this layer. The first transaction that came in this frame that
149 // replaced the previous buffer on this layer needs this release fence, because the fence will
150 // let the client know when that previous buffer is removed from the screen.
151 //
152 // Every other transaction on this layer does not need a release fence because no other
153 // Transactions that were set on this layer this frame are going to have their preceeding buffer
154 // removed from the display this frame.
155 //
156 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
157 // buffer so it doesn't need a previous release fence because the layer still needs the previous
158 // buffer. The second transaction contains a buffer so it needs a previous release fence because
159 // the previous buffer will be released this frame. The third transaction also contains a
160 // buffer. It replaces the buffer in the second transaction. The buffer in the second
161 // transaction will now no longer be presented so it is released immediately and the third
162 // transaction doesn't need a previous release fence.
Robert Carr8d958532020-11-10 14:09:16 -0800163 sp<CallbackHandle> ch;
Marissa Wall5a68a772018-12-22 17:43:42 -0800164 for (auto& handle : mDrawingState.callbackHandles) {
165 if (handle->releasePreviousBuffer) {
Robert Carr8d958532020-11-10 14:09:16 -0800166 ch = handle;
Marissa Wall5a68a772018-12-22 17:43:42 -0800167 break;
168 }
169 }
Robert Carr8d958532020-11-10 14:09:16 -0800170 auto status = addReleaseFence(ch, releaseFence);
171 if (status != OK) {
172 ALOGE("Failed to add release fence for layer %s", getName().c_str());
173 }
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700174
Valerie Haubf784642020-01-29 07:25:23 -0800175 mPreviousReleaseFence = releaseFence;
176
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700177 // Prevent tracing the same release multiple times.
178 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700179 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
180 }
Marissa Wall61c58622018-07-18 10:12:20 -0700181}
182
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100183void BufferStateLayer::onSurfaceFrameCreated(
184 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasand17c7da2021-03-05 20:43:32 +0000185 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
186 // Too many SurfaceFrames pending classification. The front of the deque is probably not
187 // tracked by FrameTimeline and will never be presented. This will only result in a memory
188 // leak.
189 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
190 mName.c_str());
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000191 std::string miniDump = mPendingJankClassifications.front()->miniDump();
192 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
Adithya Srinivasand17c7da2021-03-05 20:43:32 +0000193 mPendingJankClassifications.pop_front();
194 }
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100195 mPendingJankClassifications.emplace_back(surfaceFrame);
196}
197
Valerie Haubf784642020-01-29 07:25:23 -0800198void BufferStateLayer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Valerie Hau32cdc1f2019-10-21 14:45:54 -0700199 for (const auto& handle : mDrawingState.callbackHandles) {
200 handle->transformHint = mTransformHint;
Valerie Hau871d6352020-01-29 08:44:02 -0800201 handle->dequeueReadyTime = dequeueReadyTime;
Valerie Hau32cdc1f2019-10-21 14:45:54 -0700202 }
203
Vishnu Nair1506b182021-02-22 14:35:15 -0800204 // If there are multiple transactions in this frame, set the previous id on the earliest
205 // transacton. We don't need to pass in the released buffer id to multiple transactions.
206 // The buffer id does not have to correspond to any particular transaction as long as the
207 // listening end point is the same but the client expects the first transaction callback that
208 // replaces the presented buffer to contain the release fence. This follows the same logic.
209 // see BufferStateLayer::onLayerDisplayed.
210 for (auto& handle : mDrawingState.callbackHandles) {
211 if (handle->releasePreviousBuffer) {
212 handle->previousBufferId = mPreviousBufferId;
213 break;
214 }
215 }
216
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100217 std::vector<JankData> jankData;
218 jankData.reserve(mPendingJankClassifications.size());
219 while (!mPendingJankClassifications.empty()
220 && mPendingJankClassifications.front()->getJankType()) {
221 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
222 mPendingJankClassifications.front();
223 mPendingJankClassifications.pop_front();
224 jankData.emplace_back(
225 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
226 }
227
Robert Carr9a803c32021-01-14 16:57:58 -0800228 mFlinger->getTransactionCallbackInvoker().finalizePendingCallbackHandles(
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100229 mDrawingState.callbackHandles, jankData);
Marissa Wall5a68a772018-12-22 17:43:42 -0800230
231 mDrawingState.callbackHandles = {};
Valerie Haubf784642020-01-29 07:25:23 -0800232
233 const sp<Fence>& releaseFence(mPreviousReleaseFence);
234 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(releaseFence);
235 {
236 Mutex::Autolock lock(mFrameEventHistoryMutex);
237 if (mPreviousFrameNumber != 0) {
238 mFrameEventHistory.addRelease(mPreviousFrameNumber, dequeueReadyTime,
239 std::move(releaseFenceTime));
240 }
241 }
Marissa Wall61c58622018-07-18 10:12:20 -0700242}
243
Valerie Hau871d6352020-01-29 08:44:02 -0800244void BufferStateLayer::finalizeFrameEventHistory(const std::shared_ptr<FenceTime>& glDoneFence,
245 const CompositorTiming& compositorTiming) {
246 for (const auto& handle : mDrawingState.callbackHandles) {
247 handle->gpuCompositionDoneFence = glDoneFence;
248 handle->compositorTiming = compositorTiming;
249 }
250}
251
Marissa Walle2ffb422018-10-12 11:33:52 -0700252bool BufferStateLayer::willPresentCurrentTransaction() const {
253 // Returns true if the most recent Transaction applied to CurrentState will be presented.
Robert Carr321e83c2019-08-19 15:49:30 -0700254 return (getSidebandStreamChanged() || getAutoRefresh() ||
Valerie Hauaa194562019-02-05 16:21:38 -0800255 (mCurrentState.modified &&
chaviw8ba8b072021-01-25 14:55:46 -0800256 (mCurrentState.buffer != nullptr || mCurrentState.bgColorLayer != nullptr)));
Marissa Wall61c58622018-07-18 10:12:20 -0700257}
258
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000259Rect BufferStateLayer::getCrop(const Layer::State& s) const {
260 return s.crop;
Marissa Wall61c58622018-07-18 10:12:20 -0700261}
262
263bool BufferStateLayer::setTransform(uint32_t transform) {
chaviw766c9c52021-02-10 17:36:47 -0800264 if (mCurrentState.bufferTransform == transform) return false;
265 mCurrentState.bufferTransform = transform;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800266 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700267 setTransactionFlags(eTransactionNeeded);
268 return true;
269}
270
271bool BufferStateLayer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800272 if (mCurrentState.transformToDisplayInverse == transformToDisplayInverse) return false;
273 mCurrentState.sequence++;
274 mCurrentState.transformToDisplayInverse = transformToDisplayInverse;
275 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700276 setTransactionFlags(eTransactionNeeded);
277 return true;
278}
279
280bool BufferStateLayer::setCrop(const Rect& crop) {
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000281 if (mCurrentState.crop == crop) return false;
282 mCurrentState.sequence++;
283 mCurrentState.crop = crop;
Marissa Wall290ad082019-03-06 13:23:47 -0800284
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800285 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700286 setTransactionFlags(eTransactionNeeded);
287 return true;
288}
289
chaviwf3f40fe2021-04-27 15:54:02 -0500290bool BufferStateLayer::setBufferCrop(const Rect& bufferCrop) {
291 if (mCurrentState.bufferCrop == bufferCrop) return false;
292
293 mCurrentState.sequence++;
294 mCurrentState.bufferCrop = bufferCrop;
295
296 mCurrentState.modified = true;
297 setTransactionFlags(eTransactionNeeded);
298 return true;
299}
300
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700301bool BufferStateLayer::setDestinationFrame(const Rect& destinationFrame) {
302 if (mCurrentState.destinationFrame == destinationFrame) return false;
303
304 mCurrentState.sequence++;
305 mCurrentState.destinationFrame = destinationFrame;
306
307 mCurrentState.modified = true;
308 setTransactionFlags(eTransactionNeeded);
309 return true;
310}
311
312// Translate destination frame into scale and position. If a destination frame is not set, use the
313// provided scale and position
314void BufferStateLayer::updateGeometry() {
315 if (mCurrentState.destinationFrame.isEmpty()) {
316 // If destination frame is not set, use the requested transform set via
317 // BufferStateLayer::setPosition and BufferStateLayer::setMatrix.
318 mCurrentState.transform = mRequestedTransform;
319 return;
320 }
321
322 Rect destRect = mCurrentState.destinationFrame;
323 int32_t destW = destRect.width();
324 int32_t destH = destRect.height();
325 if (destRect.left < 0) {
326 destRect.left = 0;
327 destRect.right = destW;
328 }
329 if (destRect.top < 0) {
330 destRect.top = 0;
331 destRect.bottom = destH;
332 }
333
334 if (!mCurrentState.buffer) {
335 ui::Transform t;
336 t.set(destRect.left, destRect.top);
337 mCurrentState.transform = t;
338 return;
339 }
340
341 uint32_t bufferWidth = mCurrentState.buffer->getBuffer()->getWidth();
342 uint32_t bufferHeight = mCurrentState.buffer->getBuffer()->getHeight();
343 // Undo any transformations on the buffer.
344 if (mCurrentState.bufferTransform & ui::Transform::ROT_90) {
345 std::swap(bufferWidth, bufferHeight);
346 }
347 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
348 if (mCurrentState.transformToDisplayInverse) {
349 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);
359 mCurrentState.transform = t;
360 return;
361}
362
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000363bool BufferStateLayer::setMatrix(const layer_state_t::matrix22_t& matrix,
364 bool allowNonRectPreservingTransforms) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700365 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
366 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
Marissa Wall861616d2018-10-22 12:52:23 -0700367 return false;
368 }
369
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000370 ui::Transform t;
371 t.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
372
373 if (!allowNonRectPreservingTransforms && !t.preserveRects()) {
374 ALOGW("Attempt to set rotation matrix without permission ACCESS_SURFACE_FLINGER nor "
375 "ROTATE_SURFACE_FLINGER ignored");
376 return false;
Marissa Wall861616d2018-10-22 12:52:23 -0700377 }
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000378
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700379 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
chaviw9a93ea62021-03-11 16:44:42 -0600380
381 mCurrentState.sequence++;
382 mCurrentState.modified = true;
383 setTransactionFlags(eTransactionNeeded);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000384
385 return true;
386}
387
388bool BufferStateLayer::setPosition(float x, float y) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700389 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000390 return false;
391 }
392
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700393 mRequestedTransform.set(x, y);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000394
395 mCurrentState.sequence++;
396 mCurrentState.modified = true;
397 setTransactionFlags(eTransactionNeeded);
398
Marissa Wall861616d2018-10-22 12:52:23 -0700399 return true;
400}
401
Valerie Hau871d6352020-01-29 08:44:02 -0800402bool BufferStateLayer::addFrameEvent(const sp<Fence>& acquireFence, nsecs_t postedTime,
403 nsecs_t desiredPresentTime) {
Valerie Haubf784642020-01-29 07:25:23 -0800404 Mutex::Autolock lock(mFrameEventHistoryMutex);
405 mAcquireTimeline.updateSignalTimes();
406 std::shared_ptr<FenceTime> acquireFenceTime =
407 std::make_shared<FenceTime>((acquireFence ? acquireFence : Fence::NO_FENCE));
408 NewFrameEventsEntry newTimestamps = {mCurrentState.frameNumber, postedTime, desiredPresentTime,
409 acquireFenceTime};
Valerie Hau871d6352020-01-29 08:44:02 -0800410 mFrameEventHistory.setProducerWantsEvents();
Valerie Haubf784642020-01-29 07:25:23 -0800411 mFrameEventHistory.addQueue(newTimestamps);
412 return true;
413}
414
Alec Mouria90a5702021-04-16 16:36:21 +0000415bool BufferStateLayer::setBuffer(const std::shared_ptr<renderengine::ExternalTexture>& buffer,
416 const sp<Fence>& acquireFence, nsecs_t postTime,
417 nsecs_t desiredPresentTime, bool isAutoTimestamp,
Vishnu Nairadf632b2021-01-07 14:05:08 -0800418 const client_cache_t& clientCacheId, uint64_t frameNumber,
Vishnu Nair1506b182021-02-22 14:35:15 -0800419 std::optional<nsecs_t> dequeueTime, const FrameTimelineInfo& info,
420 const sp<ITransactionCompletedListener>& releaseBufferListener) {
Robert Carr0c1966e2020-10-19 12:12:08 -0700421 ATRACE_CALL();
422
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800423 if (mCurrentState.buffer) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700424 mReleasePreviousBuffer = true;
Alec Mouria90a5702021-04-16 16:36:21 +0000425 if (!mDrawingState.buffer ||
426 mCurrentState.buffer->getBuffer() != mDrawingState.buffer->getBuffer()) {
Robert Carr7121caf2020-12-15 13:07:32 -0800427 // If mCurrentState has a buffer, and we are about to update again
428 // 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.
Alec Mouria90a5702021-04-16 16:36:21 +0000431 callReleaseBufferCallback(mCurrentState.releaseBufferListener,
432 mCurrentState.buffer->getBuffer(),
Robert Carr97e7cc02021-06-07 10:45:40 -0700433 mCurrentState.acquireFence,
434 mTransformHint);
Robert Carr7121caf2020-12-15 13:07:32 -0800435 decrementPendingBufferCount();
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000436 if (mCurrentState.bufferSurfaceFrameTX != nullptr) {
437 addSurfaceFrameDroppedForBuffer(mCurrentState.bufferSurfaceFrameTX);
438 mCurrentState.bufferSurfaceFrameTX.reset();
439 }
Robert Carr7121caf2020-12-15 13:07:32 -0800440 }
Marissa Wallfda30bb2018-10-12 11:34:28 -0700441 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -0700442 mCurrentState.frameNumber = frameNumber;
Vishnu Nair1506b182021-02-22 14:35:15 -0800443 mCurrentState.releaseBufferListener = releaseBufferListener;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800444 mCurrentState.buffer = buffer;
Marissa Wall947d34e2019-03-29 14:03:53 -0700445 mCurrentState.clientCacheId = clientCacheId;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800446 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700447 setTransactionFlags(eTransactionNeeded);
Ady Abraham09bd3922019-04-08 10:44:56 -0700448
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800449 const int32_t layerId = getSequence();
Valerie Hau134651a2020-01-28 16:21:22 -0800450 mFlinger->mTimeStats->setPostTime(layerId, mCurrentState.frameNumber, getName().c_str(),
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000451 mOwnerUid, postTime, getGameMode());
chaviwfa67b552019-08-12 16:51:55 -0700452 mCurrentState.desiredPresentTime = desiredPresentTime;
Ady Abrahamf0c56492020-12-17 18:04:15 -0800453 mCurrentState.isAutoTimestamp = isAutoTimestamp;
Ady Abraham09bd3922019-04-08 10:44:56 -0700454
Ady Abrahamb7f15562021-03-15 18:34:08 -0700455 const nsecs_t presentTime = [&] {
456 if (!isAutoTimestamp) return desiredPresentTime;
457
458 const auto prediction =
459 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
460 if (prediction.has_value()) return prediction->presentTime;
461
462 return static_cast<nsecs_t>(0);
463 }();
464 mFlinger->mScheduler->recordLayerHistory(this, presentTime,
Ady Abraham5def7332020-05-29 16:13:47 -0700465 LayerHistory::LayerUpdateType::Buffer);
Ady Abraham09bd3922019-04-08 10:44:56 -0700466
Ady Abrahamf0c56492020-12-17 18:04:15 -0800467 addFrameEvent(acquireFence, postTime, isAutoTimestamp ? 0 : desiredPresentTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000468
Adithya Srinivasan891004e2021-02-12 20:20:47 +0000469 setFrameTimelineVsyncForBufferTransaction(info, postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000470
Alec Mouria90a5702021-04-16 16:36:21 +0000471 if (buffer && dequeueTime && *dequeueTime != 0) {
472 const uint64_t bufferId = buffer->getBuffer()->getId();
Adithya Srinivasanb238cd52021-02-04 17:54:05 +0000473 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
474 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
475 FrameTracer::FrameEvent::DEQUEUE);
476 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
477 FrameTracer::FrameEvent::QUEUE);
478 }
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000479
Alec Mouria90a5702021-04-16 16:36:21 +0000480 mCurrentState.width = mCurrentState.buffer->getBuffer()->getWidth();
481 mCurrentState.height = mCurrentState.buffer->getBuffer()->getHeight();
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000482
Marissa Wall61c58622018-07-18 10:12:20 -0700483 return true;
484}
485
486bool BufferStateLayer::setAcquireFence(const sp<Fence>& fence) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800487 mCurrentState.acquireFence = fence;
Ady Abraham6c1b7ac2021-03-31 16:56:03 -0700488 mCurrentState.acquireFenceTime = std::make_unique<FenceTime>(fence);
489
490 // The acquire fences of BufferStateLayers have already signaled before they are set
491 mCallbackHandleAcquireTime = mCurrentState.acquireFenceTime->getSignalTime();
492
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800493 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700494 setTransactionFlags(eTransactionNeeded);
495 return true;
496}
497
498bool BufferStateLayer::setDataspace(ui::Dataspace dataspace) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800499 if (mCurrentState.dataspace == dataspace) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800500 mCurrentState.dataspace = dataspace;
501 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700502 setTransactionFlags(eTransactionNeeded);
503 return true;
504}
505
506bool BufferStateLayer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800507 if (mCurrentState.hdrMetadata == hdrMetadata) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800508 mCurrentState.hdrMetadata = hdrMetadata;
509 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700510 setTransactionFlags(eTransactionNeeded);
511 return true;
512}
513
514bool BufferStateLayer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800515 mCurrentState.surfaceDamageRegion = surfaceDamage;
516 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700517 setTransactionFlags(eTransactionNeeded);
518 return true;
519}
520
521bool BufferStateLayer::setApi(int32_t api) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800522 if (mCurrentState.api == api) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800523 mCurrentState.api = api;
524 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700525 setTransactionFlags(eTransactionNeeded);
526 return true;
527}
528
529bool BufferStateLayer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800530 if (mCurrentState.sidebandStream == sidebandStream) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800531 mCurrentState.sidebandStream = sidebandStream;
532 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700533 setTransactionFlags(eTransactionNeeded);
534
535 if (!mSidebandStreamChanged.exchange(true)) {
536 // mSidebandStreamChanged was false
537 mFlinger->signalLayerUpdate();
538 }
539 return true;
540}
541
Marissa Walle2ffb422018-10-12 11:33:52 -0700542bool BufferStateLayer::setTransactionCompletedListeners(
543 const std::vector<sp<CallbackHandle>>& handles) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700544 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
Marissa Walle2ffb422018-10-12 11:33:52 -0700545 if (handles.empty()) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700546 mReleasePreviousBuffer = false;
Marissa Walle2ffb422018-10-12 11:33:52 -0700547 return false;
548 }
549
550 const bool willPresent = willPresentCurrentTransaction();
551
552 for (const auto& handle : handles) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700553 // If this transaction set a buffer on this layer, release its previous buffer
554 handle->releasePreviousBuffer = mReleasePreviousBuffer;
555
Marissa Walle2ffb422018-10-12 11:33:52 -0700556 // If this layer will be presented in this frame
557 if (willPresent) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700558 // If this transaction set an acquire fence on this layer, set its acquire time
559 handle->acquireTime = mCallbackHandleAcquireTime;
Vishnu Nair935590e2021-02-10 13:05:52 -0800560 handle->frameNumber = mCurrentState.frameNumber;
Marissa Wallfda30bb2018-10-12 11:34:28 -0700561
Marissa Walle2ffb422018-10-12 11:33:52 -0700562 // Notify the transaction completed thread that there is a pending latched callback
563 // handle
Robert Carr9a803c32021-01-14 16:57:58 -0800564 mFlinger->getTransactionCallbackInvoker().registerPendingCallbackHandle(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700565
566 // Store so latched time and release fence can be set
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800567 mCurrentState.callbackHandles.push_back(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700568
569 } else { // If this layer will NOT need to be relatched and presented this frame
570 // Notify the transaction completed thread this handle is done
Robert Carr9a803c32021-01-14 16:57:58 -0800571 mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700572 }
573 }
574
Marissa Wallfda30bb2018-10-12 11:34:28 -0700575 mReleasePreviousBuffer = false;
576 mCallbackHandleAcquireTime = -1;
577
Marissa Walle2ffb422018-10-12 11:33:52 -0700578 return willPresent;
579}
580
Marissa Wall61c58622018-07-18 10:12:20 -0700581bool BufferStateLayer::setTransparentRegionHint(const Region& transparent) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800582 mCurrentState.transparentRegionHint = transparent;
583 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700584 setTransactionFlags(eTransactionNeeded);
585 return true;
586}
587
Marissa Wall861616d2018-10-22 12:52:23 -0700588Rect BufferStateLayer::getBufferSize(const State& s) const {
589 // for buffer state layers we use the display frame size as the buffer size.
Marissa Wall61c58622018-07-18 10:12:20 -0700590
chaviw7e72caf2020-12-02 16:50:43 -0800591 if (mBufferInfo.mBuffer == nullptr) {
592 return Rect::INVALID_RECT;
593 }
594
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700595 uint32_t bufWidth = mBufferInfo.mBuffer->getBuffer()->getWidth();
596 uint32_t bufHeight = mBufferInfo.mBuffer->getBuffer()->getHeight();
597
598 // Undo any transformations on the buffer and return the result.
599 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
600 std::swap(bufWidth, bufHeight);
601 }
602
603 if (getTransformToDisplayInverse()) {
604 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
605 if (invTransform & ui::Transform::ROT_90) {
606 std::swap(bufWidth, bufHeight);
Marissa Wall861616d2018-10-22 12:52:23 -0700607 }
608 }
609
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700610 return Rect(0, 0, bufWidth, bufHeight);
Marissa Wall61c58622018-07-18 10:12:20 -0700611}
Vishnu Nair4351ad52019-02-11 14:13:02 -0800612
613FloatRect BufferStateLayer::computeSourceBounds(const FloatRect& parentBounds) const {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700614 if (mBufferInfo.mBuffer == nullptr) {
615 return parentBounds;
Vishnu Nair4351ad52019-02-11 14:13:02 -0800616 }
617
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700618 return getBufferSize(getDrawingState()).toFloatRect();
Vishnu Nair4351ad52019-02-11 14:13:02 -0800619}
620
Marissa Wall61c58622018-07-18 10:12:20 -0700621// -----------------------------------------------------------------------
622
623// -----------------------------------------------------------------------
624// Interface implementation for BufferLayer
625// -----------------------------------------------------------------------
626bool BufferStateLayer::fenceHasSignaled() const {
Alec Mouri91f6df32020-01-30 08:48:58 -0800627 const bool fenceSignaled =
628 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
629 if (!fenceSignaled) {
630 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
631 TimeStats::LatchSkipReason::LateAcquire);
632 }
633
634 return fenceSignaled;
Marissa Wall61c58622018-07-18 10:12:20 -0700635}
636
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700637bool BufferStateLayer::framePresentTimeIsCurrent(nsecs_t expectedPresentTime) const {
Ady Abrahamcd1580c2019-04-29 15:40:03 -0700638 if (!hasFrameUpdate() || isRemovedFromCurrentState()) {
639 return true;
640 }
641
Ady Abrahamf0c56492020-12-17 18:04:15 -0800642 return mCurrentState.isAutoTimestamp || mCurrentState.desiredPresentTime <= expectedPresentTime;
Ady Abrahamcd1580c2019-04-29 15:40:03 -0700643}
644
Valerie Hau871d6352020-01-29 08:44:02 -0800645bool BufferStateLayer::onPreComposition(nsecs_t refreshStartTime) {
646 for (const auto& handle : mDrawingState.callbackHandles) {
647 handle->refreshStartTime = refreshStartTime;
648 }
649 return BufferLayer::onPreComposition(refreshStartTime);
650}
651
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700652uint64_t BufferStateLayer::getFrameNumber(nsecs_t /*expectedPresentTime*/) const {
Valerie Hau134651a2020-01-28 16:21:22 -0800653 return mDrawingState.frameNumber;
Marissa Wall61c58622018-07-18 10:12:20 -0700654}
655
Robert Carrfe1209c2020-02-11 12:25:35 -0800656/**
657 * This is the frameNumber used for deferred transaction signalling. We need to use this because
658 * of cases where we defer a transaction for a surface to itself. In the BLAST world this
659 * may not make a huge amount of sense (Why not just merge the Buffer transaction with the
660 * deferred transaction?) but this is an important legacy use case, for example moving
661 * a window at the same time it draws makes use of this kind of technique. So anyway
662 * imagine we have something like this:
663 *
664 * Transaction { // containing
665 * Buffer -> frameNumber = 2
666 * DeferTransactionUntil -> frameNumber = 2
667 * Random other stuff
668 * }
669 * Now imagine getHeadFrameNumber returned mDrawingState.mFrameNumber (or mCurrentFrameNumber).
670 * Prior to doTransaction SurfaceFlinger will call notifyAvailableFrames, but because we
671 * haven't swapped mCurrentState to mDrawingState yet we will think the sync point
672 * is not ready. So we will return false from applyPendingState and not swap
673 * current state to drawing state. But because we don't swap current state
674 * to drawing state the number will never update and we will be stuck. This way
675 * we can see we need to return the frame number for the buffer we are about
676 * to apply.
677 */
678uint64_t BufferStateLayer::getHeadFrameNumber(nsecs_t /* expectedPresentTime */) const {
679 return mCurrentState.frameNumber;
680}
681
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800682void BufferStateLayer::setAutoRefresh(bool autoRefresh) {
683 if (!mAutoRefresh.exchange(autoRefresh)) {
684 mFlinger->signalLayerUpdate();
685 }
Marissa Wall61c58622018-07-18 10:12:20 -0700686}
687
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800688bool BufferStateLayer::latchSidebandStream(bool& recomputeVisibleRegions) {
baocheng suna663c2b2021-05-13 18:51:28 +0800689 // We need to update the sideband stream if the layer has both a buffer and a sideband stream.
690 const bool updateSidebandStream = hasFrameUpdate() && mSidebandStream.get();
691
692 if (mSidebandStreamChanged.exchange(false) || updateSidebandStream) {
Marissa Wall61c58622018-07-18 10:12:20 -0700693 const State& s(getDrawingState());
694 // mSidebandStreamChanged was true
Lloyd Pique0b785d82018-12-04 17:25:27 -0800695 mSidebandStream = s.sidebandStream;
Lloyd Piquede196652020-01-22 17:29:58 -0800696 editCompositionState()->sidebandStream = mSidebandStream;
Lloyd Pique0b785d82018-12-04 17:25:27 -0800697 if (mSidebandStream != nullptr) {
Marissa Wall61c58622018-07-18 10:12:20 -0700698 setTransactionFlags(eTransactionNeeded);
699 mFlinger->setTransactionFlags(eTraversalNeeded);
700 }
701 recomputeVisibleRegions = true;
702
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800703 return true;
Marissa Wall61c58622018-07-18 10:12:20 -0700704 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800705 return false;
Marissa Wall61c58622018-07-18 10:12:20 -0700706}
707
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800708bool BufferStateLayer::hasFrameUpdate() const {
Valerie Hauaa194562019-02-05 16:21:38 -0800709 const State& c(getCurrentState());
710 return mCurrentStateModified && (c.buffer != nullptr || c.bgColorLayer != nullptr);
Marissa Wall61c58622018-07-18 10:12:20 -0700711}
712
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700713status_t BufferStateLayer::updateTexImage(bool& /*recomputeVisibleRegions*/, nsecs_t latchTime,
714 nsecs_t /*expectedPresentTime*/) {
Marissa Wall61c58622018-07-18 10:12:20 -0700715 const State& s(getDrawingState());
716
717 if (!s.buffer) {
Valerie Hauaa194562019-02-05 16:21:38 -0800718 if (s.bgColorLayer) {
719 for (auto& handle : mDrawingState.callbackHandles) {
720 handle->latchTime = latchTime;
721 }
722 }
Marissa Wall61c58622018-07-18 10:12:20 -0700723 return NO_ERROR;
724 }
725
Marissa Wall5a68a772018-12-22 17:43:42 -0800726 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair935590e2021-02-10 13:05:52 -0800727 if (handle->frameNumber == mDrawingState.frameNumber) {
728 handle->latchTime = latchTime;
729 }
Marissa Wall5a68a772018-12-22 17:43:42 -0800730 }
Marissa Walle2ffb422018-10-12 11:33:52 -0700731
Vishnu Nairea0de002020-11-17 17:42:37 -0800732 const int32_t layerId = getSequence();
Alec Mouria90a5702021-04-16 16:36:21 +0000733 const uint64_t bufferId = mDrawingState.buffer->getBuffer()->getId();
Adithya Srinivasanb238cd52021-02-04 17:54:05 +0000734 const uint64_t frameNumber = mDrawingState.frameNumber;
735 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
736 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
737 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
738
739 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
740 FrameTracer::FrameEvent::ACQUIRE_FENCE);
741 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
742 FrameTracer::FrameEvent::LATCH);
Marissa Wall61c58622018-07-18 10:12:20 -0700743
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000744 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
745 if (bufferSurfaceFrame != nullptr &&
746 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
747 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
748 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
749 // are processing the next state.
750 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
Ady Abraham6c1b7ac2021-03-31 16:56:03 -0700751 mDrawingState.acquireFenceTime->getSignalTime(),
752 latchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000753 }
754
Vishnu Nairfc46c1e2021-04-21 08:31:32 -0700755 std::deque<sp<CallbackHandle>> remainingHandles;
756 mFlinger->getTransactionCallbackInvoker()
757 .finalizeOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
758 mDrawingState.callbackHandles = remainingHandles;
759
Marissa Wall16c112d2019-03-20 13:21:13 -0700760 mCurrentStateModified = false;
761
Marissa Wall61c58622018-07-18 10:12:20 -0700762 return NO_ERROR;
763}
764
765status_t BufferStateLayer::updateActiveBuffer() {
766 const State& s(getDrawingState());
767
768 if (s.buffer == nullptr) {
769 return BAD_VALUE;
770 }
chaviwdf3c5e82021-01-07 13:00:37 -0800771
Alec Mouria90a5702021-04-16 16:36:21 +0000772 if (!mBufferInfo.mBuffer || s.buffer->getBuffer() != mBufferInfo.mBuffer->getBuffer()) {
chaviwdf3c5e82021-01-07 13:00:37 -0800773 decrementPendingBufferCount();
774 }
Marissa Wall61c58622018-07-18 10:12:20 -0700775
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700776 mPreviousBufferId = getCurrentBufferId();
chaviwd62d3062019-09-04 14:48:02 -0700777 mBufferInfo.mBuffer = s.buffer;
778 mBufferInfo.mFence = s.acquireFence;
Marissa Wall61c58622018-07-18 10:12:20 -0700779
780 return NO_ERROR;
781}
782
Valerie Haubf784642020-01-29 07:25:23 -0800783status_t BufferStateLayer::updateFrameNumber(nsecs_t latchTime) {
Marissa Wall61c58622018-07-18 10:12:20 -0700784 // TODO(marissaw): support frame history events
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700785 mPreviousFrameNumber = mCurrentFrameNumber;
Valerie Hau134651a2020-01-28 16:21:22 -0800786 mCurrentFrameNumber = mDrawingState.frameNumber;
Valerie Haubf784642020-01-29 07:25:23 -0800787 {
788 Mutex::Autolock lock(mFrameEventHistoryMutex);
789 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
790 }
Marissa Wall61c58622018-07-18 10:12:20 -0700791 return NO_ERROR;
792}
793
Marissa Wall947d34e2019-03-29 14:03:53 -0700794void BufferStateLayer::HwcSlotGenerator::bufferErased(const client_cache_t& clientCacheId) {
795 std::lock_guard lock(mMutex);
796 if (!clientCacheId.isValid()) {
797 ALOGE("invalid process, failed to erase buffer");
798 return;
799 }
800 eraseBufferLocked(clientCacheId);
801}
802
803uint32_t BufferStateLayer::HwcSlotGenerator::getHwcCacheSlot(const client_cache_t& clientCacheId) {
804 std::lock_guard<std::mutex> lock(mMutex);
805 auto itr = mCachedBuffers.find(clientCacheId);
806 if (itr == mCachedBuffers.end()) {
807 return addCachedBuffer(clientCacheId);
808 }
809 auto& [hwcCacheSlot, counter] = itr->second;
810 counter = mCounter++;
811 return hwcCacheSlot;
812}
813
814uint32_t BufferStateLayer::HwcSlotGenerator::addCachedBuffer(const client_cache_t& clientCacheId)
815 REQUIRES(mMutex) {
816 if (!clientCacheId.isValid()) {
817 ALOGE("invalid process, returning invalid slot");
818 return BufferQueue::INVALID_BUFFER_SLOT;
819 }
820
821 ClientCache::getInstance().registerErasedRecipient(clientCacheId, wp<ErasedRecipient>(this));
822
823 uint32_t hwcCacheSlot = getFreeHwcCacheSlot();
824 mCachedBuffers[clientCacheId] = {hwcCacheSlot, mCounter++};
825 return hwcCacheSlot;
826}
827
828uint32_t BufferStateLayer::HwcSlotGenerator::getFreeHwcCacheSlot() REQUIRES(mMutex) {
829 if (mFreeHwcCacheSlots.empty()) {
830 evictLeastRecentlyUsed();
831 }
832
833 uint32_t hwcCacheSlot = mFreeHwcCacheSlots.top();
834 mFreeHwcCacheSlots.pop();
835 return hwcCacheSlot;
836}
837
838void BufferStateLayer::HwcSlotGenerator::evictLeastRecentlyUsed() REQUIRES(mMutex) {
839 uint64_t minCounter = UINT_MAX;
840 client_cache_t minClientCacheId = {};
841 for (const auto& [clientCacheId, slotCounter] : mCachedBuffers) {
842 const auto& [hwcCacheSlot, counter] = slotCounter;
843 if (counter < minCounter) {
844 minCounter = counter;
845 minClientCacheId = clientCacheId;
846 }
847 }
848 eraseBufferLocked(minClientCacheId);
849
850 ClientCache::getInstance().unregisterErasedRecipient(minClientCacheId, this);
851}
852
853void BufferStateLayer::HwcSlotGenerator::eraseBufferLocked(const client_cache_t& clientCacheId)
854 REQUIRES(mMutex) {
855 auto itr = mCachedBuffers.find(clientCacheId);
856 if (itr == mCachedBuffers.end()) {
857 return;
858 }
859 auto& [hwcCacheSlot, counter] = itr->second;
860
861 // TODO send to hwc cache and resources
862
863 mFreeHwcCacheSlots.push(hwcCacheSlot);
864 mCachedBuffers.erase(clientCacheId);
865}
chaviw4244e032019-09-04 11:27:49 -0700866
867void BufferStateLayer::gatherBufferInfo() {
chaviwdebadb82020-03-26 14:57:24 -0700868 BufferLayer::gatherBufferInfo();
chaviw4244e032019-09-04 11:27:49 -0700869
chaviwdebadb82020-03-26 14:57:24 -0700870 const State& s(getDrawingState());
chaviw4244e032019-09-04 11:27:49 -0700871 mBufferInfo.mDesiredPresentTime = s.desiredPresentTime;
872 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(s.acquireFence);
873 mBufferInfo.mFence = s.acquireFence;
chaviw766c9c52021-02-10 17:36:47 -0800874 mBufferInfo.mTransform = s.bufferTransform;
chaviw4244e032019-09-04 11:27:49 -0700875 mBufferInfo.mDataspace = translateDataspace(s.dataspace);
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700876 mBufferInfo.mCrop = computeBufferCrop(s);
chaviw4244e032019-09-04 11:27:49 -0700877 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
878 mBufferInfo.mSurfaceDamage = s.surfaceDamageRegion;
879 mBufferInfo.mHdrMetadata = s.hdrMetadata;
880 mBufferInfo.mApi = s.api;
chaviw4244e032019-09-04 11:27:49 -0700881 mBufferInfo.mTransformToDisplayInverse = s.transformToDisplayInverse;
chaviwf83ce182019-09-12 14:43:08 -0700882 mBufferInfo.mBufferSlot = mHwcSlotGenerator->getHwcCacheSlot(s.clientCacheId);
chaviw4244e032019-09-04 11:27:49 -0700883}
884
Robert Carr916b0362020-10-06 13:53:03 -0700885uint32_t BufferStateLayer::getEffectiveScalingMode() const {
886 return NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
887}
888
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700889Rect BufferStateLayer::computeBufferCrop(const State& s) {
chaviwf3f40fe2021-04-27 15:54:02 -0500890 if (s.buffer && !s.bufferCrop.isEmpty()) {
891 Rect bufferCrop;
892 s.buffer->getBuffer()->getBounds().intersect(s.bufferCrop, &bufferCrop);
893 return bufferCrop;
894 } else if (s.buffer) {
Alec Mouria90a5702021-04-16 16:36:21 +0000895 return s.buffer->getBuffer()->getBounds();
chaviwf3f40fe2021-04-27 15:54:02 -0500896 } else {
897 return s.bufferCrop;
chaviw4244e032019-09-04 11:27:49 -0700898 }
chaviw4244e032019-09-04 11:27:49 -0700899}
900
chaviwb4c6e582019-08-16 14:35:07 -0700901sp<Layer> BufferStateLayer::createClone() {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700902 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, 0, 0, LayerMetadata());
chaviwb4c6e582019-08-16 14:35:07 -0700903 args.textureName = mTextureName;
Lloyd Pique1c3a5eb2019-10-03 13:07:08 -0700904 sp<BufferStateLayer> layer = mFlinger->getFactory().createBufferStateLayer(args);
chaviwb4c6e582019-08-16 14:35:07 -0700905 layer->mHwcSlotGenerator = mHwcSlotGenerator;
906 layer->setInitialValuesForClone(this);
907 return layer;
908}
Valerie Hau92bf5482020-02-10 09:49:08 -0800909
Vishnu Naire7f79c52020-10-29 14:45:03 -0700910bool BufferStateLayer::bufferNeedsFiltering() const {
911 const State& s(getDrawingState());
912 if (!s.buffer) {
913 return false;
914 }
915
Alec Mouria90a5702021-04-16 16:36:21 +0000916 uint32_t bufferWidth = s.buffer->getBuffer()->width;
917 uint32_t bufferHeight = s.buffer->getBuffer()->height;
Vishnu Naire7f79c52020-10-29 14:45:03 -0700918
919 // Undo any transformations on the buffer and return the result.
chaviw766c9c52021-02-10 17:36:47 -0800920 if (s.bufferTransform & ui::Transform::ROT_90) {
Vishnu Naire7f79c52020-10-29 14:45:03 -0700921 std::swap(bufferWidth, bufferHeight);
922 }
923
924 if (s.transformToDisplayInverse) {
925 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
926 if (invTransform & ui::Transform::ROT_90) {
927 std::swap(bufferWidth, bufferHeight);
928 }
929 }
930
931 const Rect layerSize{getBounds()};
932 return layerSize.width() != bufferWidth || layerSize.height() != bufferHeight;
933}
Robert Carr7121caf2020-12-15 13:07:32 -0800934
Robert Carr7121caf2020-12-15 13:07:32 -0800935void BufferStateLayer::decrementPendingBufferCount() {
Vishnu Nair8eda69e2021-02-26 10:42:10 -0800936 int32_t pendingBuffers = --mPendingBufferTransactions;
937 tracePendingBufferCount(pendingBuffers);
Robert Carr7121caf2020-12-15 13:07:32 -0800938}
939
Vishnu Nair8eda69e2021-02-26 10:42:10 -0800940void BufferStateLayer::tracePendingBufferCount(int32_t pendingBuffers) {
941 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
Robert Carr7121caf2020-12-15 13:07:32 -0800942}
943
Alec Mouria90a5702021-04-16 16:36:21 +0000944void BufferStateLayer::bufferMayChange(const sp<GraphicBuffer>& newBuffer) {
945 if (mDrawingState.buffer != nullptr &&
946 (!mBufferInfo.mBuffer ||
947 mDrawingState.buffer->getBuffer() != mBufferInfo.mBuffer->getBuffer()) &&
948 newBuffer != mDrawingState.buffer->getBuffer()) {
Robert Carr7121caf2020-12-15 13:07:32 -0800949 // If we are about to update mDrawingState.buffer but it has not yet latched
Vishnu Nair1506b182021-02-22 14:35:15 -0800950 // then we will drop a buffer and should decrement the pending buffer count and
951 // call any release buffer callbacks if set.
Alec Mouria90a5702021-04-16 16:36:21 +0000952 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
Robert Carr97e7cc02021-06-07 10:45:40 -0700953 mDrawingState.buffer->getBuffer(), mDrawingState.acquireFence,
954 mTransformHint);
Robert Carr7121caf2020-12-15 13:07:32 -0800955 decrementPendingBufferCount();
956 }
Robert Carr7121caf2020-12-15 13:07:32 -0800957}
958
chaviw39d01472021-04-08 14:26:24 -0500959/*
960 * We don't want to send the layer's transform to input, but rather the
961 * parent's transform. This is because BufferStateLayer's transform is
962 * information about how the buffer is placed on screen. The parent's
963 * transform makes more sense to send since it's information about how the
964 * layer is placed on screen. This transform is used by input to determine
965 * how to go from screen space back to window space.
966 */
967ui::Transform BufferStateLayer::getInputTransform() const {
968 sp<Layer> parent = mDrawingParent.promote();
969 if (parent == nullptr) {
970 return ui::Transform();
971 }
972
973 return parent->getTransform();
974}
975
976/**
977 * Similar to getInputTransform, we need to update the bounds to include the transform.
978 * This is because bounds for BSL doesn't include buffer transform, where the input assumes
979 * that's already included.
980 */
981Rect BufferStateLayer::getInputBounds() const {
982 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
983 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
984 return bufferBounds;
985 }
986 return mDrawingState.transform.transform(bufferBounds);
987}
988
Marissa Wall61c58622018-07-18 10:12:20 -0700989} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800990
991// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100992#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"