blob: f8af908737d3d75757afaf166b9a0f0041b960a5 [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,
Robert Carr97e7cc02021-06-07 10:45:40 -070047 const sp<GraphicBuffer>& buffer, const sp<Fence>& releaseFence,
Ady Abraham899dcdb2021-06-15 16:56:21 -070048 uint32_t transformHint, uint32_t currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -080049 if (!listener) {
50 return;
51 }
Robert Carr97e7cc02021-06-07 10:45:40 -070052 listener->onReleaseBuffer(buffer->getId(), releaseFence ? releaseFence : Fence::NO_FENCE,
Ady Abraham899dcdb2021-06-15 16:56:21 -070053 transformHint, currentMaxAcquiredBufferCount);
Vishnu Nair1506b182021-02-22 14:35:15 -080054}
55} // namespace
56
Lloyd Pique42ab75e2018-09-12 20:46:03 -070057// clang-format off
58const std::array<float, 16> BufferStateLayer::IDENTITY_MATRIX{
59 1, 0, 0, 0,
60 0, 1, 0, 0,
61 0, 0, 1, 0,
62 0, 0, 0, 1
63};
64// clang-format on
Marissa Wall61c58622018-07-18 10:12:20 -070065
Marissa Wall947d34e2019-03-29 14:03:53 -070066BufferStateLayer::BufferStateLayer(const LayerCreationArgs& args)
67 : BufferLayer(args), mHwcSlotGenerator(new HwcSlotGenerator()) {
Marissa Wall3ff826c2019-02-07 11:58:25 -080068 mCurrentState.dataspace = ui::Dataspace::V0_SRGB;
Vishnu Nair60356342018-11-13 13:00:45 -080069}
Marissa Wall61c58622018-07-18 10:12:20 -070070
Alec Mouri4545a8a2019-08-08 20:05:32 -070071BufferStateLayer::~BufferStateLayer() {
chaviwb4c6e582019-08-16 14:35:07 -070072 // The original layer and the clone layer share the same texture and buffer. Therefore, only
73 // one of the layers, in this case the original layer, needs to handle the deletion. The
74 // original layer and the clone should be removed at the same time so there shouldn't be any
75 // issue with the clone layer trying to use the texture.
76 if (mBufferInfo.mBuffer != nullptr && !isClone()) {
Alec Mouria90a5702021-04-16 16:36:21 +000077 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
Robert Carr97e7cc02021-06-07 10:45:40 -070078 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFence,
Ady Abraham899dcdb2021-06-15 16:56:21 -070079 mTransformHint,
80 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
81 mOwnerUid));
Alec Mouri4545a8a2019-08-08 20:05:32 -070082 }
83}
84
Robert Carr8d958532020-11-10 14:09:16 -080085status_t BufferStateLayer::addReleaseFence(const sp<CallbackHandle>& ch,
86 const sp<Fence>& fence) {
87 if (ch == nullptr) {
88 return OK;
89 }
Vishnu Nair1506b182021-02-22 14:35:15 -080090 ch->previousBufferId = mPreviousBufferId;
Robert Carr8d958532020-11-10 14:09:16 -080091 if (!ch->previousReleaseFence.get()) {
92 ch->previousReleaseFence = fence;
93 return OK;
94 }
95
96 // Below logic is lifted from ConsumerBase.cpp:
97 // Check status of fences first because merging is expensive.
98 // Merging an invalid fence with any other fence results in an
99 // invalid fence.
100 auto currentStatus = ch->previousReleaseFence->getStatus();
101 if (currentStatus == Fence::Status::Invalid) {
102 ALOGE("Existing fence has invalid state, layer: %s", mName.c_str());
103 return BAD_VALUE;
104 }
105
106 auto incomingStatus = fence->getStatus();
107 if (incomingStatus == Fence::Status::Invalid) {
108 ALOGE("New fence has invalid state, layer: %s", mName.c_str());
109 ch->previousReleaseFence = fence;
110 return BAD_VALUE;
111 }
112
113 // If both fences are signaled or both are unsignaled, we need to merge
114 // them to get an accurate timestamp.
115 if (currentStatus == incomingStatus) {
116 char fenceName[32] = {};
117 snprintf(fenceName, 32, "%.28s", mName.c_str());
118 sp<Fence> mergedFence = Fence::merge(
119 fenceName, ch->previousReleaseFence, fence);
120 if (!mergedFence.get()) {
121 ALOGE("failed to merge release fences, layer: %s", mName.c_str());
122 // synchronization is broken, the best we can do is hope fences
123 // signal in order so the new fence will act like a union
124 ch->previousReleaseFence = fence;
125 return BAD_VALUE;
126 }
127 ch->previousReleaseFence = mergedFence;
128 } else if (incomingStatus == Fence::Status::Unsignaled) {
129 // If one fence has signaled and the other hasn't, the unsignaled
130 // fence will approximately correspond with the correct timestamp.
131 // There's a small race if both fences signal at about the same time
132 // and their statuses are retrieved with unfortunate timing. However,
133 // by this point, they will have both signaled and only the timestamp
134 // will be slightly off; any dependencies after this point will
135 // already have been met.
136 ch->previousReleaseFence = fence;
137 }
138 // else if (currentStatus == Fence::Status::Unsignaled) is a no-op.
139
140 return OK;
141}
142
Marissa Wall61c58622018-07-18 10:12:20 -0700143// -----------------------------------------------------------------------
144// Interface implementation for Layer
145// -----------------------------------------------------------------------
Marissa Wallfda30bb2018-10-12 11:34:28 -0700146void BufferStateLayer::onLayerDisplayed(const sp<Fence>& releaseFence) {
Robert Carr8d958532020-11-10 14:09:16 -0800147 if (!releaseFence->isValid()) {
148 return;
149 }
Marissa Wall5a68a772018-12-22 17:43:42 -0800150 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
151 // buffer that was presented on this layer. The first transaction that came in this frame that
152 // replaced the previous buffer on this layer needs this release fence, because the fence will
153 // let the client know when that previous buffer is removed from the screen.
154 //
155 // Every other transaction on this layer does not need a release fence because no other
156 // Transactions that were set on this layer this frame are going to have their preceeding buffer
157 // removed from the display this frame.
158 //
159 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
160 // buffer so it doesn't need a previous release fence because the layer still needs the previous
161 // buffer. The second transaction contains a buffer so it needs a previous release fence because
162 // the previous buffer will be released this frame. The third transaction also contains a
163 // buffer. It replaces the buffer in the second transaction. The buffer in the second
164 // transaction will now no longer be presented so it is released immediately and the third
165 // transaction doesn't need a previous release fence.
Robert Carr8d958532020-11-10 14:09:16 -0800166 sp<CallbackHandle> ch;
Marissa Wall5a68a772018-12-22 17:43:42 -0800167 for (auto& handle : mDrawingState.callbackHandles) {
168 if (handle->releasePreviousBuffer) {
Robert Carr8d958532020-11-10 14:09:16 -0800169 ch = handle;
Marissa Wall5a68a772018-12-22 17:43:42 -0800170 break;
171 }
172 }
Robert Carr8d958532020-11-10 14:09:16 -0800173 auto status = addReleaseFence(ch, releaseFence);
174 if (status != OK) {
175 ALOGE("Failed to add release fence for layer %s", getName().c_str());
176 }
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700177
Valerie Haubf784642020-01-29 07:25:23 -0800178 mPreviousReleaseFence = releaseFence;
179
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700180 // Prevent tracing the same release multiple times.
181 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700182 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
183 }
Marissa Wall61c58622018-07-18 10:12:20 -0700184}
185
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100186void BufferStateLayer::onSurfaceFrameCreated(
187 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
Adithya Srinivasand17c7da2021-03-05 20:43:32 +0000188 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
189 // Too many SurfaceFrames pending classification. The front of the deque is probably not
190 // tracked by FrameTimeline and will never be presented. This will only result in a memory
191 // leak.
192 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
193 mName.c_str());
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000194 std::string miniDump = mPendingJankClassifications.front()->miniDump();
195 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
Adithya Srinivasand17c7da2021-03-05 20:43:32 +0000196 mPendingJankClassifications.pop_front();
197 }
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100198 mPendingJankClassifications.emplace_back(surfaceFrame);
199}
200
Valerie Haubf784642020-01-29 07:25:23 -0800201void BufferStateLayer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Valerie Hau32cdc1f2019-10-21 14:45:54 -0700202 for (const auto& handle : mDrawingState.callbackHandles) {
203 handle->transformHint = mTransformHint;
Valerie Hau871d6352020-01-29 08:44:02 -0800204 handle->dequeueReadyTime = dequeueReadyTime;
Ady Abraham899dcdb2021-06-15 16:56:21 -0700205 handle->currentMaxAcquiredBufferCount =
206 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Valerie Hau32cdc1f2019-10-21 14:45:54 -0700207 }
208
Vishnu Nair1506b182021-02-22 14:35:15 -0800209 // If there are multiple transactions in this frame, set the previous id on the earliest
210 // transacton. We don't need to pass in the released buffer id to multiple transactions.
211 // The buffer id does not have to correspond to any particular transaction as long as the
212 // listening end point is the same but the client expects the first transaction callback that
213 // replaces the presented buffer to contain the release fence. This follows the same logic.
214 // see BufferStateLayer::onLayerDisplayed.
215 for (auto& handle : mDrawingState.callbackHandles) {
216 if (handle->releasePreviousBuffer) {
217 handle->previousBufferId = mPreviousBufferId;
218 break;
219 }
220 }
221
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100222 std::vector<JankData> jankData;
223 jankData.reserve(mPendingJankClassifications.size());
224 while (!mPendingJankClassifications.empty()
225 && mPendingJankClassifications.front()->getJankType()) {
226 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
227 mPendingJankClassifications.front();
228 mPendingJankClassifications.pop_front();
229 jankData.emplace_back(
230 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
231 }
232
Robert Carr9a803c32021-01-14 16:57:58 -0800233 mFlinger->getTransactionCallbackInvoker().finalizePendingCallbackHandles(
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100234 mDrawingState.callbackHandles, jankData);
Marissa Wall5a68a772018-12-22 17:43:42 -0800235
236 mDrawingState.callbackHandles = {};
Valerie Haubf784642020-01-29 07:25:23 -0800237
238 const sp<Fence>& releaseFence(mPreviousReleaseFence);
239 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(releaseFence);
240 {
241 Mutex::Autolock lock(mFrameEventHistoryMutex);
242 if (mPreviousFrameNumber != 0) {
243 mFrameEventHistory.addRelease(mPreviousFrameNumber, dequeueReadyTime,
244 std::move(releaseFenceTime));
245 }
246 }
Marissa Wall61c58622018-07-18 10:12:20 -0700247}
248
Valerie Hau871d6352020-01-29 08:44:02 -0800249void BufferStateLayer::finalizeFrameEventHistory(const std::shared_ptr<FenceTime>& glDoneFence,
250 const CompositorTiming& compositorTiming) {
251 for (const auto& handle : mDrawingState.callbackHandles) {
252 handle->gpuCompositionDoneFence = glDoneFence;
253 handle->compositorTiming = compositorTiming;
254 }
255}
256
Marissa Walle2ffb422018-10-12 11:33:52 -0700257bool BufferStateLayer::willPresentCurrentTransaction() const {
258 // Returns true if the most recent Transaction applied to CurrentState will be presented.
Robert Carr321e83c2019-08-19 15:49:30 -0700259 return (getSidebandStreamChanged() || getAutoRefresh() ||
Valerie Hauaa194562019-02-05 16:21:38 -0800260 (mCurrentState.modified &&
chaviw8ba8b072021-01-25 14:55:46 -0800261 (mCurrentState.buffer != nullptr || mCurrentState.bgColorLayer != nullptr)));
Marissa Wall61c58622018-07-18 10:12:20 -0700262}
263
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000264Rect BufferStateLayer::getCrop(const Layer::State& s) const {
265 return s.crop;
Marissa Wall61c58622018-07-18 10:12:20 -0700266}
267
268bool BufferStateLayer::setTransform(uint32_t transform) {
chaviw766c9c52021-02-10 17:36:47 -0800269 if (mCurrentState.bufferTransform == transform) return false;
270 mCurrentState.bufferTransform = transform;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800271 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700272 setTransactionFlags(eTransactionNeeded);
273 return true;
274}
275
276bool BufferStateLayer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800277 if (mCurrentState.transformToDisplayInverse == transformToDisplayInverse) return false;
278 mCurrentState.sequence++;
279 mCurrentState.transformToDisplayInverse = transformToDisplayInverse;
280 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700281 setTransactionFlags(eTransactionNeeded);
282 return true;
283}
284
285bool BufferStateLayer::setCrop(const Rect& crop) {
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000286 if (mCurrentState.crop == crop) return false;
287 mCurrentState.sequence++;
288 mCurrentState.crop = crop;
Marissa Wall290ad082019-03-06 13:23:47 -0800289
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800290 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700291 setTransactionFlags(eTransactionNeeded);
292 return true;
293}
294
chaviwf3f40fe2021-04-27 15:54:02 -0500295bool BufferStateLayer::setBufferCrop(const Rect& bufferCrop) {
296 if (mCurrentState.bufferCrop == bufferCrop) return false;
297
298 mCurrentState.sequence++;
299 mCurrentState.bufferCrop = bufferCrop;
300
301 mCurrentState.modified = true;
302 setTransactionFlags(eTransactionNeeded);
303 return true;
304}
305
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700306bool BufferStateLayer::setDestinationFrame(const Rect& destinationFrame) {
307 if (mCurrentState.destinationFrame == destinationFrame) return false;
308
309 mCurrentState.sequence++;
310 mCurrentState.destinationFrame = destinationFrame;
311
312 mCurrentState.modified = true;
313 setTransactionFlags(eTransactionNeeded);
314 return true;
315}
316
317// Translate destination frame into scale and position. If a destination frame is not set, use the
318// provided scale and position
319void BufferStateLayer::updateGeometry() {
320 if (mCurrentState.destinationFrame.isEmpty()) {
321 // If destination frame is not set, use the requested transform set via
322 // BufferStateLayer::setPosition and BufferStateLayer::setMatrix.
323 mCurrentState.transform = mRequestedTransform;
324 return;
325 }
326
327 Rect destRect = mCurrentState.destinationFrame;
328 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
339 if (!mCurrentState.buffer) {
340 ui::Transform t;
341 t.set(destRect.left, destRect.top);
342 mCurrentState.transform = t;
343 return;
344 }
345
346 uint32_t bufferWidth = mCurrentState.buffer->getBuffer()->getWidth();
347 uint32_t bufferHeight = mCurrentState.buffer->getBuffer()->getHeight();
348 // Undo any transformations on the buffer.
349 if (mCurrentState.bufferTransform & ui::Transform::ROT_90) {
350 std::swap(bufferWidth, bufferHeight);
351 }
352 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
353 if (mCurrentState.transformToDisplayInverse) {
354 if (invTransform & ui::Transform::ROT_90) {
355 std::swap(bufferWidth, bufferHeight);
356 }
357 }
358
359 float sx = destW / static_cast<float>(bufferWidth);
360 float sy = destH / static_cast<float>(bufferHeight);
361 ui::Transform t;
362 t.set(sx, 0, 0, sy);
363 t.set(destRect.left, destRect.top);
364 mCurrentState.transform = t;
365 return;
366}
367
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000368bool BufferStateLayer::setMatrix(const layer_state_t::matrix22_t& matrix,
369 bool allowNonRectPreservingTransforms) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700370 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
371 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
Marissa Wall861616d2018-10-22 12:52:23 -0700372 return false;
373 }
374
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000375 ui::Transform t;
376 t.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
377
378 if (!allowNonRectPreservingTransforms && !t.preserveRects()) {
379 ALOGW("Attempt to set rotation matrix without permission ACCESS_SURFACE_FLINGER nor "
380 "ROTATE_SURFACE_FLINGER ignored");
381 return false;
Marissa Wall861616d2018-10-22 12:52:23 -0700382 }
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000383
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700384 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
chaviw9a93ea62021-03-11 16:44:42 -0600385
386 mCurrentState.sequence++;
387 mCurrentState.modified = true;
388 setTransactionFlags(eTransactionNeeded);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000389
390 return true;
391}
392
393bool BufferStateLayer::setPosition(float x, float y) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700394 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000395 return false;
396 }
397
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700398 mRequestedTransform.set(x, y);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000399
400 mCurrentState.sequence++;
401 mCurrentState.modified = true;
402 setTransactionFlags(eTransactionNeeded);
403
Marissa Wall861616d2018-10-22 12:52:23 -0700404 return true;
405}
406
Valerie Hau871d6352020-01-29 08:44:02 -0800407bool BufferStateLayer::addFrameEvent(const sp<Fence>& acquireFence, nsecs_t postedTime,
408 nsecs_t desiredPresentTime) {
Valerie Haubf784642020-01-29 07:25:23 -0800409 Mutex::Autolock lock(mFrameEventHistoryMutex);
410 mAcquireTimeline.updateSignalTimes();
411 std::shared_ptr<FenceTime> acquireFenceTime =
412 std::make_shared<FenceTime>((acquireFence ? acquireFence : Fence::NO_FENCE));
413 NewFrameEventsEntry newTimestamps = {mCurrentState.frameNumber, postedTime, desiredPresentTime,
414 acquireFenceTime};
Valerie Hau871d6352020-01-29 08:44:02 -0800415 mFrameEventHistory.setProducerWantsEvents();
Valerie Haubf784642020-01-29 07:25:23 -0800416 mFrameEventHistory.addQueue(newTimestamps);
417 return true;
418}
419
Alec Mouria90a5702021-04-16 16:36:21 +0000420bool BufferStateLayer::setBuffer(const std::shared_ptr<renderengine::ExternalTexture>& buffer,
421 const sp<Fence>& acquireFence, nsecs_t postTime,
422 nsecs_t desiredPresentTime, bool isAutoTimestamp,
Vishnu Nairadf632b2021-01-07 14:05:08 -0800423 const client_cache_t& clientCacheId, uint64_t frameNumber,
Vishnu Nair1506b182021-02-22 14:35:15 -0800424 std::optional<nsecs_t> dequeueTime, const FrameTimelineInfo& info,
425 const sp<ITransactionCompletedListener>& releaseBufferListener) {
Robert Carr0c1966e2020-10-19 12:12:08 -0700426 ATRACE_CALL();
427
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800428 if (mCurrentState.buffer) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700429 mReleasePreviousBuffer = true;
Alec Mouria90a5702021-04-16 16:36:21 +0000430 if (!mDrawingState.buffer ||
431 mCurrentState.buffer->getBuffer() != mDrawingState.buffer->getBuffer()) {
Robert Carr7121caf2020-12-15 13:07:32 -0800432 // If mCurrentState has a buffer, and we are about to update again
433 // before swapping to drawing state, then the first buffer will be
Vishnu Nair1506b182021-02-22 14:35:15 -0800434 // dropped and we should decrement the pending buffer count and
435 // call any release buffer callbacks if set.
Alec Mouria90a5702021-04-16 16:36:21 +0000436 callReleaseBufferCallback(mCurrentState.releaseBufferListener,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700437 mCurrentState.buffer->getBuffer(), mCurrentState.acquireFence,
438 mTransformHint,
439 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
440 mOwnerUid));
Robert Carr7121caf2020-12-15 13:07:32 -0800441 decrementPendingBufferCount();
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000442 if (mCurrentState.bufferSurfaceFrameTX != nullptr) {
443 addSurfaceFrameDroppedForBuffer(mCurrentState.bufferSurfaceFrameTX);
444 mCurrentState.bufferSurfaceFrameTX.reset();
445 }
Robert Carr7121caf2020-12-15 13:07:32 -0800446 }
Marissa Wallfda30bb2018-10-12 11:34:28 -0700447 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -0700448 mCurrentState.frameNumber = frameNumber;
Vishnu Nair1506b182021-02-22 14:35:15 -0800449 mCurrentState.releaseBufferListener = releaseBufferListener;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800450 mCurrentState.buffer = buffer;
Marissa Wall947d34e2019-03-29 14:03:53 -0700451 mCurrentState.clientCacheId = clientCacheId;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800452 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700453 setTransactionFlags(eTransactionNeeded);
Ady Abraham09bd3922019-04-08 10:44:56 -0700454
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800455 const int32_t layerId = getSequence();
Valerie Hau134651a2020-01-28 16:21:22 -0800456 mFlinger->mTimeStats->setPostTime(layerId, mCurrentState.frameNumber, getName().c_str(),
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000457 mOwnerUid, postTime, getGameMode());
chaviwfa67b552019-08-12 16:51:55 -0700458 mCurrentState.desiredPresentTime = desiredPresentTime;
Ady Abrahamf0c56492020-12-17 18:04:15 -0800459 mCurrentState.isAutoTimestamp = isAutoTimestamp;
Ady Abraham09bd3922019-04-08 10:44:56 -0700460
Ady Abrahamb7f15562021-03-15 18:34:08 -0700461 const nsecs_t presentTime = [&] {
462 if (!isAutoTimestamp) return desiredPresentTime;
463
464 const auto prediction =
465 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
466 if (prediction.has_value()) return prediction->presentTime;
467
468 return static_cast<nsecs_t>(0);
469 }();
470 mFlinger->mScheduler->recordLayerHistory(this, presentTime,
Ady Abraham5def7332020-05-29 16:13:47 -0700471 LayerHistory::LayerUpdateType::Buffer);
Ady Abraham09bd3922019-04-08 10:44:56 -0700472
Ady Abrahamf0c56492020-12-17 18:04:15 -0800473 addFrameEvent(acquireFence, postTime, isAutoTimestamp ? 0 : desiredPresentTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000474
Adithya Srinivasan891004e2021-02-12 20:20:47 +0000475 setFrameTimelineVsyncForBufferTransaction(info, postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000476
Alec Mouria90a5702021-04-16 16:36:21 +0000477 if (buffer && dequeueTime && *dequeueTime != 0) {
478 const uint64_t bufferId = buffer->getBuffer()->getId();
Adithya Srinivasanb238cd52021-02-04 17:54:05 +0000479 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
480 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
481 FrameTracer::FrameEvent::DEQUEUE);
482 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
483 FrameTracer::FrameEvent::QUEUE);
484 }
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000485
Alec Mouria90a5702021-04-16 16:36:21 +0000486 mCurrentState.width = mCurrentState.buffer->getBuffer()->getWidth();
487 mCurrentState.height = mCurrentState.buffer->getBuffer()->getHeight();
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000488
Marissa Wall61c58622018-07-18 10:12:20 -0700489 return true;
490}
491
492bool BufferStateLayer::setAcquireFence(const sp<Fence>& fence) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800493 mCurrentState.acquireFence = fence;
Ady Abraham6c1b7ac2021-03-31 16:56:03 -0700494 mCurrentState.acquireFenceTime = std::make_unique<FenceTime>(fence);
495
496 // The acquire fences of BufferStateLayers have already signaled before they are set
497 mCallbackHandleAcquireTime = mCurrentState.acquireFenceTime->getSignalTime();
498
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800499 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700500 setTransactionFlags(eTransactionNeeded);
501 return true;
502}
503
504bool BufferStateLayer::setDataspace(ui::Dataspace dataspace) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800505 if (mCurrentState.dataspace == dataspace) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800506 mCurrentState.dataspace = dataspace;
507 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700508 setTransactionFlags(eTransactionNeeded);
509 return true;
510}
511
512bool BufferStateLayer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800513 if (mCurrentState.hdrMetadata == hdrMetadata) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800514 mCurrentState.hdrMetadata = hdrMetadata;
515 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700516 setTransactionFlags(eTransactionNeeded);
517 return true;
518}
519
520bool BufferStateLayer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800521 mCurrentState.surfaceDamageRegion = surfaceDamage;
522 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700523 setTransactionFlags(eTransactionNeeded);
524 return true;
525}
526
527bool BufferStateLayer::setApi(int32_t api) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800528 if (mCurrentState.api == api) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800529 mCurrentState.api = api;
530 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700531 setTransactionFlags(eTransactionNeeded);
532 return true;
533}
534
535bool BufferStateLayer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800536 if (mCurrentState.sidebandStream == sidebandStream) return false;
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800537 mCurrentState.sidebandStream = sidebandStream;
538 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700539 setTransactionFlags(eTransactionNeeded);
540
541 if (!mSidebandStreamChanged.exchange(true)) {
542 // mSidebandStreamChanged was false
543 mFlinger->signalLayerUpdate();
544 }
545 return true;
546}
547
Marissa Walle2ffb422018-10-12 11:33:52 -0700548bool BufferStateLayer::setTransactionCompletedListeners(
549 const std::vector<sp<CallbackHandle>>& handles) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700550 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
Marissa Walle2ffb422018-10-12 11:33:52 -0700551 if (handles.empty()) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700552 mReleasePreviousBuffer = false;
Marissa Walle2ffb422018-10-12 11:33:52 -0700553 return false;
554 }
555
556 const bool willPresent = willPresentCurrentTransaction();
557
558 for (const auto& handle : handles) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700559 // If this transaction set a buffer on this layer, release its previous buffer
560 handle->releasePreviousBuffer = mReleasePreviousBuffer;
561
Marissa Walle2ffb422018-10-12 11:33:52 -0700562 // If this layer will be presented in this frame
563 if (willPresent) {
Marissa Wallfda30bb2018-10-12 11:34:28 -0700564 // If this transaction set an acquire fence on this layer, set its acquire time
565 handle->acquireTime = mCallbackHandleAcquireTime;
Vishnu Nair935590e2021-02-10 13:05:52 -0800566 handle->frameNumber = mCurrentState.frameNumber;
Marissa Wallfda30bb2018-10-12 11:34:28 -0700567
Marissa Walle2ffb422018-10-12 11:33:52 -0700568 // Notify the transaction completed thread that there is a pending latched callback
569 // handle
Robert Carr9a803c32021-01-14 16:57:58 -0800570 mFlinger->getTransactionCallbackInvoker().registerPendingCallbackHandle(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700571
572 // Store so latched time and release fence can be set
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800573 mCurrentState.callbackHandles.push_back(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700574
575 } else { // If this layer will NOT need to be relatched and presented this frame
576 // Notify the transaction completed thread this handle is done
Robert Carr9a803c32021-01-14 16:57:58 -0800577 mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
Marissa Walle2ffb422018-10-12 11:33:52 -0700578 }
579 }
580
Marissa Wallfda30bb2018-10-12 11:34:28 -0700581 mReleasePreviousBuffer = false;
582 mCallbackHandleAcquireTime = -1;
583
Marissa Walle2ffb422018-10-12 11:33:52 -0700584 return willPresent;
585}
586
Marissa Wall61c58622018-07-18 10:12:20 -0700587bool BufferStateLayer::setTransparentRegionHint(const Region& transparent) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800588 mCurrentState.transparentRegionHint = transparent;
589 mCurrentState.modified = true;
Marissa Wall61c58622018-07-18 10:12:20 -0700590 setTransactionFlags(eTransactionNeeded);
591 return true;
592}
593
Marissa Wall861616d2018-10-22 12:52:23 -0700594Rect BufferStateLayer::getBufferSize(const State& s) const {
595 // for buffer state layers we use the display frame size as the buffer size.
Marissa Wall61c58622018-07-18 10:12:20 -0700596
chaviw7e72caf2020-12-02 16:50:43 -0800597 if (mBufferInfo.mBuffer == nullptr) {
598 return Rect::INVALID_RECT;
599 }
600
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700601 uint32_t bufWidth = mBufferInfo.mBuffer->getBuffer()->getWidth();
602 uint32_t bufHeight = mBufferInfo.mBuffer->getBuffer()->getHeight();
603
604 // Undo any transformations on the buffer and return the result.
605 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
606 std::swap(bufWidth, bufHeight);
607 }
608
609 if (getTransformToDisplayInverse()) {
610 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
611 if (invTransform & ui::Transform::ROT_90) {
612 std::swap(bufWidth, bufHeight);
Marissa Wall861616d2018-10-22 12:52:23 -0700613 }
614 }
615
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700616 return Rect(0, 0, bufWidth, bufHeight);
Marissa Wall61c58622018-07-18 10:12:20 -0700617}
Vishnu Nair4351ad52019-02-11 14:13:02 -0800618
619FloatRect BufferStateLayer::computeSourceBounds(const FloatRect& parentBounds) const {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700620 if (mBufferInfo.mBuffer == nullptr) {
621 return parentBounds;
Vishnu Nair4351ad52019-02-11 14:13:02 -0800622 }
623
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700624 return getBufferSize(getDrawingState()).toFloatRect();
Vishnu Nair4351ad52019-02-11 14:13:02 -0800625}
626
Marissa Wall61c58622018-07-18 10:12:20 -0700627// -----------------------------------------------------------------------
628
629// -----------------------------------------------------------------------
630// Interface implementation for BufferLayer
631// -----------------------------------------------------------------------
632bool BufferStateLayer::fenceHasSignaled() const {
Alec Mouri91f6df32020-01-30 08:48:58 -0800633 const bool fenceSignaled =
634 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
635 if (!fenceSignaled) {
636 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
637 TimeStats::LatchSkipReason::LateAcquire);
638 }
639
640 return fenceSignaled;
Marissa Wall61c58622018-07-18 10:12:20 -0700641}
642
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700643bool BufferStateLayer::framePresentTimeIsCurrent(nsecs_t expectedPresentTime) const {
Ady Abrahamcd1580c2019-04-29 15:40:03 -0700644 if (!hasFrameUpdate() || isRemovedFromCurrentState()) {
645 return true;
646 }
647
Ady Abrahamf0c56492020-12-17 18:04:15 -0800648 return mCurrentState.isAutoTimestamp || mCurrentState.desiredPresentTime <= expectedPresentTime;
Ady Abrahamcd1580c2019-04-29 15:40:03 -0700649}
650
Valerie Hau871d6352020-01-29 08:44:02 -0800651bool BufferStateLayer::onPreComposition(nsecs_t refreshStartTime) {
652 for (const auto& handle : mDrawingState.callbackHandles) {
653 handle->refreshStartTime = refreshStartTime;
654 }
655 return BufferLayer::onPreComposition(refreshStartTime);
656}
657
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700658uint64_t BufferStateLayer::getFrameNumber(nsecs_t /*expectedPresentTime*/) const {
Valerie Hau134651a2020-01-28 16:21:22 -0800659 return mDrawingState.frameNumber;
Marissa Wall61c58622018-07-18 10:12:20 -0700660}
661
Robert Carrfe1209c2020-02-11 12:25:35 -0800662/**
663 * This is the frameNumber used for deferred transaction signalling. We need to use this because
664 * of cases where we defer a transaction for a surface to itself. In the BLAST world this
665 * may not make a huge amount of sense (Why not just merge the Buffer transaction with the
666 * deferred transaction?) but this is an important legacy use case, for example moving
667 * a window at the same time it draws makes use of this kind of technique. So anyway
668 * imagine we have something like this:
669 *
670 * Transaction { // containing
671 * Buffer -> frameNumber = 2
672 * DeferTransactionUntil -> frameNumber = 2
673 * Random other stuff
674 * }
675 * Now imagine getHeadFrameNumber returned mDrawingState.mFrameNumber (or mCurrentFrameNumber).
676 * Prior to doTransaction SurfaceFlinger will call notifyAvailableFrames, but because we
677 * haven't swapped mCurrentState to mDrawingState yet we will think the sync point
678 * is not ready. So we will return false from applyPendingState and not swap
679 * current state to drawing state. But because we don't swap current state
680 * to drawing state the number will never update and we will be stuck. This way
681 * we can see we need to return the frame number for the buffer we are about
682 * to apply.
683 */
684uint64_t BufferStateLayer::getHeadFrameNumber(nsecs_t /* expectedPresentTime */) const {
685 return mCurrentState.frameNumber;
686}
687
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800688void BufferStateLayer::setAutoRefresh(bool autoRefresh) {
689 if (!mAutoRefresh.exchange(autoRefresh)) {
690 mFlinger->signalLayerUpdate();
691 }
Marissa Wall61c58622018-07-18 10:12:20 -0700692}
693
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800694bool BufferStateLayer::latchSidebandStream(bool& recomputeVisibleRegions) {
baocheng suna663c2b2021-05-13 18:51:28 +0800695 // We need to update the sideband stream if the layer has both a buffer and a sideband stream.
696 const bool updateSidebandStream = hasFrameUpdate() && mSidebandStream.get();
697
698 if (mSidebandStreamChanged.exchange(false) || updateSidebandStream) {
Marissa Wall61c58622018-07-18 10:12:20 -0700699 const State& s(getDrawingState());
700 // mSidebandStreamChanged was true
Lloyd Pique0b785d82018-12-04 17:25:27 -0800701 mSidebandStream = s.sidebandStream;
Lloyd Piquede196652020-01-22 17:29:58 -0800702 editCompositionState()->sidebandStream = mSidebandStream;
Lloyd Pique0b785d82018-12-04 17:25:27 -0800703 if (mSidebandStream != nullptr) {
Marissa Wall61c58622018-07-18 10:12:20 -0700704 setTransactionFlags(eTransactionNeeded);
705 mFlinger->setTransactionFlags(eTraversalNeeded);
706 }
707 recomputeVisibleRegions = true;
708
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800709 return true;
Marissa Wall61c58622018-07-18 10:12:20 -0700710 }
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800711 return false;
Marissa Wall61c58622018-07-18 10:12:20 -0700712}
713
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800714bool BufferStateLayer::hasFrameUpdate() const {
Valerie Hauaa194562019-02-05 16:21:38 -0800715 const State& c(getCurrentState());
716 return mCurrentStateModified && (c.buffer != nullptr || c.bgColorLayer != nullptr);
Marissa Wall61c58622018-07-18 10:12:20 -0700717}
718
Dominik Laskowskia8955dd2019-07-10 10:19:09 -0700719status_t BufferStateLayer::updateTexImage(bool& /*recomputeVisibleRegions*/, nsecs_t latchTime,
720 nsecs_t /*expectedPresentTime*/) {
Marissa Wall61c58622018-07-18 10:12:20 -0700721 const State& s(getDrawingState());
722
723 if (!s.buffer) {
Valerie Hauaa194562019-02-05 16:21:38 -0800724 if (s.bgColorLayer) {
725 for (auto& handle : mDrawingState.callbackHandles) {
726 handle->latchTime = latchTime;
727 }
728 }
Marissa Wall61c58622018-07-18 10:12:20 -0700729 return NO_ERROR;
730 }
731
Marissa Wall5a68a772018-12-22 17:43:42 -0800732 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair935590e2021-02-10 13:05:52 -0800733 if (handle->frameNumber == mDrawingState.frameNumber) {
734 handle->latchTime = latchTime;
735 }
Marissa Wall5a68a772018-12-22 17:43:42 -0800736 }
Marissa Walle2ffb422018-10-12 11:33:52 -0700737
Vishnu Nairea0de002020-11-17 17:42:37 -0800738 const int32_t layerId = getSequence();
Alec Mouria90a5702021-04-16 16:36:21 +0000739 const uint64_t bufferId = mDrawingState.buffer->getBuffer()->getId();
Adithya Srinivasanb238cd52021-02-04 17:54:05 +0000740 const uint64_t frameNumber = mDrawingState.frameNumber;
741 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
742 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
743 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
744
745 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
746 FrameTracer::FrameEvent::ACQUIRE_FENCE);
747 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
748 FrameTracer::FrameEvent::LATCH);
Marissa Wall61c58622018-07-18 10:12:20 -0700749
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000750 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
751 if (bufferSurfaceFrame != nullptr &&
752 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
753 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
754 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
755 // are processing the next state.
756 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
Ady Abraham6c1b7ac2021-03-31 16:56:03 -0700757 mDrawingState.acquireFenceTime->getSignalTime(),
758 latchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000759 }
760
Vishnu Nairfc46c1e2021-04-21 08:31:32 -0700761 std::deque<sp<CallbackHandle>> remainingHandles;
762 mFlinger->getTransactionCallbackInvoker()
763 .finalizeOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
764 mDrawingState.callbackHandles = remainingHandles;
765
Marissa Wall16c112d2019-03-20 13:21:13 -0700766 mCurrentStateModified = false;
767
Marissa Wall61c58622018-07-18 10:12:20 -0700768 return NO_ERROR;
769}
770
771status_t BufferStateLayer::updateActiveBuffer() {
772 const State& s(getDrawingState());
773
774 if (s.buffer == nullptr) {
775 return BAD_VALUE;
776 }
chaviwdf3c5e82021-01-07 13:00:37 -0800777
Alec Mouria90a5702021-04-16 16:36:21 +0000778 if (!mBufferInfo.mBuffer || s.buffer->getBuffer() != mBufferInfo.mBuffer->getBuffer()) {
chaviwdf3c5e82021-01-07 13:00:37 -0800779 decrementPendingBufferCount();
780 }
Marissa Wall61c58622018-07-18 10:12:20 -0700781
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700782 mPreviousBufferId = getCurrentBufferId();
chaviwd62d3062019-09-04 14:48:02 -0700783 mBufferInfo.mBuffer = s.buffer;
784 mBufferInfo.mFence = s.acquireFence;
Marissa Wall61c58622018-07-18 10:12:20 -0700785
786 return NO_ERROR;
787}
788
Valerie Haubf784642020-01-29 07:25:23 -0800789status_t BufferStateLayer::updateFrameNumber(nsecs_t latchTime) {
Marissa Wall61c58622018-07-18 10:12:20 -0700790 // TODO(marissaw): support frame history events
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700791 mPreviousFrameNumber = mCurrentFrameNumber;
Valerie Hau134651a2020-01-28 16:21:22 -0800792 mCurrentFrameNumber = mDrawingState.frameNumber;
Valerie Haubf784642020-01-29 07:25:23 -0800793 {
794 Mutex::Autolock lock(mFrameEventHistoryMutex);
795 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
796 }
Marissa Wall61c58622018-07-18 10:12:20 -0700797 return NO_ERROR;
798}
799
Marissa Wall947d34e2019-03-29 14:03:53 -0700800void BufferStateLayer::HwcSlotGenerator::bufferErased(const client_cache_t& clientCacheId) {
801 std::lock_guard lock(mMutex);
802 if (!clientCacheId.isValid()) {
803 ALOGE("invalid process, failed to erase buffer");
804 return;
805 }
806 eraseBufferLocked(clientCacheId);
807}
808
809uint32_t BufferStateLayer::HwcSlotGenerator::getHwcCacheSlot(const client_cache_t& clientCacheId) {
810 std::lock_guard<std::mutex> lock(mMutex);
811 auto itr = mCachedBuffers.find(clientCacheId);
812 if (itr == mCachedBuffers.end()) {
813 return addCachedBuffer(clientCacheId);
814 }
815 auto& [hwcCacheSlot, counter] = itr->second;
816 counter = mCounter++;
817 return hwcCacheSlot;
818}
819
820uint32_t BufferStateLayer::HwcSlotGenerator::addCachedBuffer(const client_cache_t& clientCacheId)
821 REQUIRES(mMutex) {
822 if (!clientCacheId.isValid()) {
823 ALOGE("invalid process, returning invalid slot");
824 return BufferQueue::INVALID_BUFFER_SLOT;
825 }
826
827 ClientCache::getInstance().registerErasedRecipient(clientCacheId, wp<ErasedRecipient>(this));
828
829 uint32_t hwcCacheSlot = getFreeHwcCacheSlot();
830 mCachedBuffers[clientCacheId] = {hwcCacheSlot, mCounter++};
831 return hwcCacheSlot;
832}
833
834uint32_t BufferStateLayer::HwcSlotGenerator::getFreeHwcCacheSlot() REQUIRES(mMutex) {
835 if (mFreeHwcCacheSlots.empty()) {
836 evictLeastRecentlyUsed();
837 }
838
839 uint32_t hwcCacheSlot = mFreeHwcCacheSlots.top();
840 mFreeHwcCacheSlots.pop();
841 return hwcCacheSlot;
842}
843
844void BufferStateLayer::HwcSlotGenerator::evictLeastRecentlyUsed() REQUIRES(mMutex) {
845 uint64_t minCounter = UINT_MAX;
846 client_cache_t minClientCacheId = {};
847 for (const auto& [clientCacheId, slotCounter] : mCachedBuffers) {
848 const auto& [hwcCacheSlot, counter] = slotCounter;
849 if (counter < minCounter) {
850 minCounter = counter;
851 minClientCacheId = clientCacheId;
852 }
853 }
854 eraseBufferLocked(minClientCacheId);
855
856 ClientCache::getInstance().unregisterErasedRecipient(minClientCacheId, this);
857}
858
859void BufferStateLayer::HwcSlotGenerator::eraseBufferLocked(const client_cache_t& clientCacheId)
860 REQUIRES(mMutex) {
861 auto itr = mCachedBuffers.find(clientCacheId);
862 if (itr == mCachedBuffers.end()) {
863 return;
864 }
865 auto& [hwcCacheSlot, counter] = itr->second;
866
867 // TODO send to hwc cache and resources
868
869 mFreeHwcCacheSlots.push(hwcCacheSlot);
870 mCachedBuffers.erase(clientCacheId);
871}
chaviw4244e032019-09-04 11:27:49 -0700872
873void BufferStateLayer::gatherBufferInfo() {
chaviwdebadb82020-03-26 14:57:24 -0700874 BufferLayer::gatherBufferInfo();
chaviw4244e032019-09-04 11:27:49 -0700875
chaviwdebadb82020-03-26 14:57:24 -0700876 const State& s(getDrawingState());
chaviw4244e032019-09-04 11:27:49 -0700877 mBufferInfo.mDesiredPresentTime = s.desiredPresentTime;
878 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(s.acquireFence);
879 mBufferInfo.mFence = s.acquireFence;
chaviw766c9c52021-02-10 17:36:47 -0800880 mBufferInfo.mTransform = s.bufferTransform;
chaviw4244e032019-09-04 11:27:49 -0700881 mBufferInfo.mDataspace = translateDataspace(s.dataspace);
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700882 mBufferInfo.mCrop = computeBufferCrop(s);
chaviw4244e032019-09-04 11:27:49 -0700883 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
884 mBufferInfo.mSurfaceDamage = s.surfaceDamageRegion;
885 mBufferInfo.mHdrMetadata = s.hdrMetadata;
886 mBufferInfo.mApi = s.api;
chaviw4244e032019-09-04 11:27:49 -0700887 mBufferInfo.mTransformToDisplayInverse = s.transformToDisplayInverse;
chaviwf83ce182019-09-12 14:43:08 -0700888 mBufferInfo.mBufferSlot = mHwcSlotGenerator->getHwcCacheSlot(s.clientCacheId);
chaviw4244e032019-09-04 11:27:49 -0700889}
890
Robert Carr916b0362020-10-06 13:53:03 -0700891uint32_t BufferStateLayer::getEffectiveScalingMode() const {
892 return NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
893}
894
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700895Rect BufferStateLayer::computeBufferCrop(const State& s) {
chaviwf3f40fe2021-04-27 15:54:02 -0500896 if (s.buffer && !s.bufferCrop.isEmpty()) {
897 Rect bufferCrop;
898 s.buffer->getBuffer()->getBounds().intersect(s.bufferCrop, &bufferCrop);
899 return bufferCrop;
900 } else if (s.buffer) {
Alec Mouria90a5702021-04-16 16:36:21 +0000901 return s.buffer->getBuffer()->getBounds();
chaviwf3f40fe2021-04-27 15:54:02 -0500902 } else {
903 return s.bufferCrop;
chaviw4244e032019-09-04 11:27:49 -0700904 }
chaviw4244e032019-09-04 11:27:49 -0700905}
906
chaviwb4c6e582019-08-16 14:35:07 -0700907sp<Layer> BufferStateLayer::createClone() {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700908 LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, 0, 0, LayerMetadata());
chaviwb4c6e582019-08-16 14:35:07 -0700909 args.textureName = mTextureName;
Lloyd Pique1c3a5eb2019-10-03 13:07:08 -0700910 sp<BufferStateLayer> layer = mFlinger->getFactory().createBufferStateLayer(args);
chaviwb4c6e582019-08-16 14:35:07 -0700911 layer->mHwcSlotGenerator = mHwcSlotGenerator;
912 layer->setInitialValuesForClone(this);
913 return layer;
914}
Valerie Hau92bf5482020-02-10 09:49:08 -0800915
Vishnu Naire7f79c52020-10-29 14:45:03 -0700916bool BufferStateLayer::bufferNeedsFiltering() const {
917 const State& s(getDrawingState());
918 if (!s.buffer) {
919 return false;
920 }
921
Alec Mouria90a5702021-04-16 16:36:21 +0000922 uint32_t bufferWidth = s.buffer->getBuffer()->width;
923 uint32_t bufferHeight = s.buffer->getBuffer()->height;
Vishnu Naire7f79c52020-10-29 14:45:03 -0700924
925 // Undo any transformations on the buffer and return the result.
chaviw766c9c52021-02-10 17:36:47 -0800926 if (s.bufferTransform & ui::Transform::ROT_90) {
Vishnu Naire7f79c52020-10-29 14:45:03 -0700927 std::swap(bufferWidth, bufferHeight);
928 }
929
930 if (s.transformToDisplayInverse) {
931 uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
932 if (invTransform & ui::Transform::ROT_90) {
933 std::swap(bufferWidth, bufferHeight);
934 }
935 }
936
937 const Rect layerSize{getBounds()};
938 return layerSize.width() != bufferWidth || layerSize.height() != bufferHeight;
939}
Robert Carr7121caf2020-12-15 13:07:32 -0800940
Robert Carr7121caf2020-12-15 13:07:32 -0800941void BufferStateLayer::decrementPendingBufferCount() {
Vishnu Nair8eda69e2021-02-26 10:42:10 -0800942 int32_t pendingBuffers = --mPendingBufferTransactions;
943 tracePendingBufferCount(pendingBuffers);
Robert Carr7121caf2020-12-15 13:07:32 -0800944}
945
Vishnu Nair8eda69e2021-02-26 10:42:10 -0800946void BufferStateLayer::tracePendingBufferCount(int32_t pendingBuffers) {
947 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
Robert Carr7121caf2020-12-15 13:07:32 -0800948}
949
Alec Mouria90a5702021-04-16 16:36:21 +0000950void BufferStateLayer::bufferMayChange(const sp<GraphicBuffer>& newBuffer) {
951 if (mDrawingState.buffer != nullptr &&
952 (!mBufferInfo.mBuffer ||
953 mDrawingState.buffer->getBuffer() != mBufferInfo.mBuffer->getBuffer()) &&
954 newBuffer != mDrawingState.buffer->getBuffer()) {
Robert Carr7121caf2020-12-15 13:07:32 -0800955 // If we are about to update mDrawingState.buffer but it has not yet latched
Vishnu Nair1506b182021-02-22 14:35:15 -0800956 // then we will drop a buffer and should decrement the pending buffer count and
957 // call any release buffer callbacks if set.
Alec Mouria90a5702021-04-16 16:36:21 +0000958 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
Robert Carr97e7cc02021-06-07 10:45:40 -0700959 mDrawingState.buffer->getBuffer(), mDrawingState.acquireFence,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700960 mTransformHint,
961 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
962 mOwnerUid));
Robert Carr7121caf2020-12-15 13:07:32 -0800963 decrementPendingBufferCount();
964 }
Robert Carr7121caf2020-12-15 13:07:32 -0800965}
966
chaviw39d01472021-04-08 14:26:24 -0500967/*
968 * We don't want to send the layer's transform to input, but rather the
969 * parent's transform. This is because BufferStateLayer's transform is
970 * information about how the buffer is placed on screen. The parent's
971 * transform makes more sense to send since it's information about how the
972 * layer is placed on screen. This transform is used by input to determine
973 * how to go from screen space back to window space.
974 */
975ui::Transform BufferStateLayer::getInputTransform() const {
976 sp<Layer> parent = mDrawingParent.promote();
977 if (parent == nullptr) {
978 return ui::Transform();
979 }
980
981 return parent->getTransform();
982}
983
984/**
985 * Similar to getInputTransform, we need to update the bounds to include the transform.
986 * This is because bounds for BSL doesn't include buffer transform, where the input assumes
987 * that's already included.
988 */
989Rect BufferStateLayer::getInputBounds() const {
990 Rect bufferBounds = getCroppedBufferSize(getDrawingState());
991 if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
992 return bufferBounds;
993 }
994 return mDrawingState.transform.transform(bufferBounds);
995}
996
Marissa Wall61c58622018-07-18 10:12:20 -0700997} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800998
999// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +01001000#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"