blob: 5c92e60124c92520c7d9384671f1d716ea47915b [file] [log] [blame]
Robert Carr78c25dd2019-08-15 14:10:33 -07001/*
2 * Copyright (C) 2019 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
Valerie Haud3b90d22019-11-06 09:37:31 -080017#undef LOG_TAG
18#define LOG_TAG "BLASTBufferQueue"
19
Valerie Haua32c5522019-12-09 10:11:08 -080020#define ATRACE_TAG ATRACE_TAG_GRAPHICS
Vishnu Naire1a42322020-10-02 17:42:04 -070021//#define LOG_NDEBUG 0
Valerie Haua32c5522019-12-09 10:11:08 -080022
Robert Carr78c25dd2019-08-15 14:10:33 -070023#include <gui/BLASTBufferQueue.h>
24#include <gui/BufferItemConsumer.h>
Vishnu Nair89496122020-12-14 17:14:53 -080025#include <gui/BufferQueueConsumer.h>
26#include <gui/BufferQueueCore.h>
27#include <gui/BufferQueueProducer.h>
Valerie Hau45e4b3b2019-12-03 10:49:17 -080028#include <gui/GLConsumer.h>
Vishnu Nair89496122020-12-14 17:14:53 -080029#include <gui/IProducerListener.h>
Robert Carr05086b22020-10-13 18:22:51 -070030#include <gui/Surface.h>
chaviw57ae4b22022-02-03 16:51:39 -060031#include <gui/TraceUtils.h>
Vishnu Nair89496122020-12-14 17:14:53 -080032#include <utils/Singleton.h>
Valerie Haua32c5522019-12-09 10:11:08 -080033#include <utils/Trace.h>
34
Ady Abraham0bde6b52021-05-18 13:57:02 -070035#include <private/gui/ComposerService.h>
36
Robert Carr78c25dd2019-08-15 14:10:33 -070037#include <chrono>
38
39using namespace std::chrono_literals;
40
Vishnu Nairdab94092020-09-29 16:09:04 -070041namespace {
chaviw3277faf2021-05-19 16:45:23 -050042inline const char* boolToString(bool b) {
Vishnu Nairdab94092020-09-29 16:09:04 -070043 return b ? "true" : "false";
44}
45} // namespace
46
Robert Carr78c25dd2019-08-15 14:10:33 -070047namespace android {
48
Vishnu Nairdab94092020-09-29 16:09:04 -070049// Macros to include adapter info in log messages
chaviwd7deef72021-10-06 11:53:40 -050050#define BQA_LOGD(x, ...) \
51 ALOGD("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070052#define BQA_LOGV(x, ...) \
53 ALOGV("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairc6f89ee2020-12-11 14:27:32 -080054// enable logs for a single layer
55//#define BQA_LOGV(x, ...) \
56// ALOGV_IF((strstr(mName.c_str(), "SurfaceView") != nullptr), "[%s](f:%u,a:%u) " x, \
57// mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070058#define BQA_LOGE(x, ...) \
59 ALOGE("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
60
chaviw57ae4b22022-02-03 16:51:39 -060061#define BBQ_TRACE(x, ...) \
62 ATRACE_FORMAT("%s - %s(f:%u,a:%u)" x, __FUNCTION__, mName.c_str(), mNumFrameAvailable, \
63 mNumAcquired, ##__VA_ARGS__)
64
Valerie Hau871d6352020-01-29 08:44:02 -080065void BLASTBufferItemConsumer::onDisconnect() {
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000066 Mutex::Autolock lock(mMutex);
67 mPreviouslyConnected = mCurrentlyConnected;
68 mCurrentlyConnected = false;
69 if (mPreviouslyConnected) {
70 mDisconnectEvents.push(mCurrentFrameNumber);
Valerie Hau871d6352020-01-29 08:44:02 -080071 }
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000072 mFrameEventHistory.onDisconnect();
Valerie Hau871d6352020-01-29 08:44:02 -080073}
74
75void BLASTBufferItemConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
76 FrameEventHistoryDelta* outDelta) {
Hongguang Chen621ec582021-02-16 15:42:35 -080077 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080078 if (newTimestamps) {
79 // BufferQueueProducer only adds a new timestamp on
80 // queueBuffer
81 mCurrentFrameNumber = newTimestamps->frameNumber;
82 mFrameEventHistory.addQueue(*newTimestamps);
83 }
84 if (outDelta) {
85 // frame event histories will be processed
86 // only after the producer connects and requests
87 // deltas for the first time. Forward this intent
88 // to SF-side to turn event processing back on
89 mPreviouslyConnected = mCurrentlyConnected;
90 mCurrentlyConnected = true;
91 mFrameEventHistory.getAndResetDelta(outDelta);
92 }
93}
94
95void BLASTBufferItemConsumer::updateFrameTimestamps(uint64_t frameNumber, nsecs_t refreshStartTime,
96 const sp<Fence>& glDoneFence,
97 const sp<Fence>& presentFence,
98 const sp<Fence>& prevReleaseFence,
99 CompositorTiming compositorTiming,
100 nsecs_t latchTime, nsecs_t dequeueReadyTime) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800101 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800102
103 // if the producer is not connected, don't bother updating,
104 // the next producer that connects won't access this frame event
105 if (!mCurrentlyConnected) return;
106 std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
107 std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
108 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
109
110 mFrameEventHistory.addLatch(frameNumber, latchTime);
111 mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
112 mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
113 mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
114 compositorTiming);
115}
116
117void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
118 bool disconnect = false;
Hongguang Chen621ec582021-02-16 15:42:35 -0800119 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800120 while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
121 disconnect = true;
122 mDisconnectEvents.pop();
123 }
124 if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
125}
126
Hongguang Chen621ec582021-02-16 15:42:35 -0800127void BLASTBufferItemConsumer::onSidebandStreamChanged() {
Ady Abrahamdbca1352021-12-15 11:58:56 -0800128 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
129 if (bbq != nullptr) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800130 sp<NativeHandle> stream = getSidebandStream();
Ady Abrahamdbca1352021-12-15 11:58:56 -0800131 bbq->setSidebandStream(stream);
Hongguang Chen621ec582021-02-16 15:42:35 -0800132 }
133}
134
Vishnu Naird2aaab12022-02-10 14:49:09 -0800135BLASTBufferQueue::BLASTBufferQueue(const std::string& name, bool updateDestinationFrame)
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800136 : mSurfaceControl(nullptr),
137 mSize(1, 1),
Vishnu Nairea0de002020-11-17 17:42:37 -0800138 mRequestedSize(mSize),
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800139 mFormat(PIXEL_FORMAT_RGBA_8888),
Tianhao Yao4861b102022-02-03 20:18:35 +0000140 mTransactionReadyCallback(nullptr),
Vishnu Naird2aaab12022-02-10 14:49:09 -0800141 mSyncTransaction(nullptr),
142 mUpdateDestinationFrame(updateDestinationFrame) {
Vishnu Nair89496122020-12-14 17:14:53 -0800143 createBufferQueue(&mProducer, &mConsumer);
Valerie Hau0889c622020-02-19 15:04:47 -0800144 // since the adapter is in the client process, set dequeue timeout
145 // explicitly so that dequeueBuffer will block
146 mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
Valerie Hau65b8e872020-02-13 09:45:14 -0800147
Vishnu Nairdebd1cb2021-03-16 10:06:01 -0700148 // safe default, most producers are expected to override this
149 mProducer->setMaxDequeuedBufferCount(2);
Vishnu Nair1618c672021-02-05 13:08:26 -0800150 mBufferItemConsumer = new BLASTBufferItemConsumer(mConsumer,
151 GraphicBuffer::USAGE_HW_COMPOSER |
152 GraphicBuffer::USAGE_HW_TEXTURE,
Ady Abrahamdbca1352021-12-15 11:58:56 -0800153 1, false, this);
Valerie Haua32c5522019-12-09 10:11:08 -0800154 static int32_t id = 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700155 mName = name + "#" + std::to_string(id);
Vishnu Nairdab94092020-09-29 16:09:04 -0700156 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(id);
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700157 mQueuedBufferTrace = "QueuedBuffer - " + mName + "BLAST#" + std::to_string(id);
Valerie Haua32c5522019-12-09 10:11:08 -0800158 id++;
Vishnu Nairdab94092020-09-29 16:09:04 -0700159 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700160 mBufferItemConsumer->setFrameAvailableListener(this);
161 mBufferItemConsumer->setBufferFreedListener(this);
Robert Carr9f133d72020-04-01 15:51:46 -0700162
Ady Abraham899dcdb2021-06-15 16:56:21 -0700163 ComposerService::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);
Ady Abraham0bde6b52021-05-18 13:57:02 -0700164 mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
chaviw69058fb2021-09-27 09:37:30 -0500165 mCurrentMaxAcquiredBufferCount = mMaxAcquiredBuffers;
Valerie Haua32c5522019-12-09 10:11:08 -0800166 mNumAcquired = 0;
167 mNumFrameAvailable = 0;
Robert Carr4c1b6462021-12-21 10:30:50 -0800168
169 TransactionCompletedListener::getInstance()->addQueueStallListener(
170 [&]() {
171 std::function<void(bool)> callbackCopy;
172 {
173 std::unique_lock _lock{mMutex};
174 callbackCopy = mTransactionHangCallback;
175 }
176 if (callbackCopy) callbackCopy(true);
177 }, this);
178
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800179 BQA_LOGV("BLASTBufferQueue created");
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800180}
181
182BLASTBufferQueue::BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface,
183 int width, int height, int32_t format)
184 : BLASTBufferQueue(name) {
185 update(surface, width, height, format);
Robert Carr78c25dd2019-08-15 14:10:33 -0700186}
187
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800188BLASTBufferQueue::~BLASTBufferQueue() {
Robert Carr4c1b6462021-12-21 10:30:50 -0800189 TransactionCompletedListener::getInstance()->removeQueueStallListener(this);
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800190 if (mPendingTransactions.empty()) {
191 return;
192 }
193 BQA_LOGE("Applying pending transactions on dtor %d",
194 static_cast<uint32_t>(mPendingTransactions.size()));
195 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800196 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
Robert Carr79dc06a2022-02-22 15:28:59 -0800197 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
198 t.setApplyToken(mApplyToken).apply(false, true);
chaviw3b4bdcf2022-03-17 09:27:03 -0500199
200 if (mTransactionReadyCallback) {
201 mTransactionReadyCallback(mSyncTransaction);
202 }
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800203}
204
chaviw565ee542021-01-14 10:21:23 -0800205void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Naird2aaab12022-02-10 14:49:09 -0800206 int32_t format) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800207 LOG_ALWAYS_FATAL_IF(surface == nullptr, "BLASTBufferQueue: mSurfaceControl must not be NULL");
208
Robert Carr78c25dd2019-08-15 14:10:33 -0700209 std::unique_lock _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800210 if (mFormat != format) {
211 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800212 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800213 }
214
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800215 const bool surfaceControlChanged = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairab066512022-01-04 22:28:00 +0000216 if (surfaceControlChanged && mSurfaceControl != nullptr) {
217 BQA_LOGD("Updating SurfaceControl without recreating BBQ");
218 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800219 bool applyTransaction = false;
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800220
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700221 // Always update the native object even though they might have the same layer handle, so we can
222 // get the updated transform hint from WM.
223 mSurfaceControl = surface;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800224 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800225 if (surfaceControlChanged) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800226 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
227 layer_state_t::eEnableBackpressure);
228 applyTransaction = true;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800229 }
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800230 mTransformHint = mSurfaceControl->getTransformHint();
231 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700232 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
233 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800234
Vishnu Nairea0de002020-11-17 17:42:37 -0800235 ui::Size newSize(width, height);
236 if (mRequestedSize != newSize) {
237 mRequestedSize.set(newSize);
238 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000239 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800240 // If the buffer supports scaling, update the frame immediately since the client may
241 // want to scale the existing buffer to the new size.
242 mSize = mRequestedSize;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800243 if (mUpdateDestinationFrame) {
244 t.setDestinationFrame(mSurfaceControl, Rect(newSize));
245 applyTransaction = true;
246 }
Vishnu Nair53c936c2020-12-03 11:46:37 -0800247 }
Robert Carrfc416512020-04-02 12:32:44 -0700248 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800249 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800250 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
251 t.setApplyToken(mApplyToken).apply(false, true);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800252 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700253}
254
chaviwd7deef72021-10-06 11:53:40 -0500255static std::optional<SurfaceControlStats> findMatchingStat(
256 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
257 for (auto stat : stats) {
258 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
259 return stat;
260 }
261 }
262 return std::nullopt;
263}
264
265static void transactionCommittedCallbackThunk(void* context, nsecs_t latchTime,
266 const sp<Fence>& presentFence,
267 const std::vector<SurfaceControlStats>& stats) {
268 if (context == nullptr) {
269 return;
270 }
271 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
272 bq->transactionCommittedCallback(latchTime, presentFence, stats);
273}
274
275void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
276 const sp<Fence>& /*presentFence*/,
277 const std::vector<SurfaceControlStats>& stats) {
278 {
279 std::unique_lock _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600280 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500281 BQA_LOGV("transactionCommittedCallback");
282 if (!mSurfaceControlsWithPendingCallback.empty()) {
283 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
284 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
285 if (stat) {
286 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
287
288 // We need to check if we were waiting for a transaction callback in order to
289 // process any pending buffers and unblock. It's possible to get transaction
chaviwc1cf4022022-06-03 13:32:33 -0500290 // callbacks for previous requests so we need to ensure that there are no pending
291 // frame numbers that were in a sync. We remove the frame from mSyncedFrameNumbers
292 // set and then check if it's empty. If there are no more pending syncs, we can
293 // proceed with flushing the shadow queue.
294 // We also want to check if mSyncTransaction is null because it's possible another
chaviwd7deef72021-10-06 11:53:40 -0500295 // sync request came in while waiting, but it hasn't started processing yet. In that
296 // case, we don't actually want to flush the frames in between since they will get
297 // processed and merged with the sync transaction and released earlier than if they
298 // were sent to SF
chaviwc1cf4022022-06-03 13:32:33 -0500299 mSyncedFrameNumbers.erase(currFrameNumber);
300 if (mSyncedFrameNumbers.empty() && mSyncTransaction == nullptr) {
chaviwd7deef72021-10-06 11:53:40 -0500301 flushShadowQueue();
302 }
303 } else {
chaviw768bfa02021-11-01 09:50:57 -0500304 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviwd7deef72021-10-06 11:53:40 -0500305 }
306 } else {
307 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
308 "empty.");
309 }
chaviwd7deef72021-10-06 11:53:40 -0500310 decStrong((void*)transactionCommittedCallbackThunk);
311 }
312}
313
Robert Carr78c25dd2019-08-15 14:10:33 -0700314static void transactionCallbackThunk(void* context, nsecs_t latchTime,
315 const sp<Fence>& presentFence,
316 const std::vector<SurfaceControlStats>& stats) {
317 if (context == nullptr) {
318 return;
319 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800320 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700321 bq->transactionCallback(latchTime, presentFence, stats);
322}
323
324void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
325 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700326 {
327 std::unique_lock _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600328 BBQ_TRACE();
chaviw71c2cc42020-10-23 16:42:02 -0700329 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700330
chaviw42026162021-04-16 15:46:12 -0500331 if (!mSurfaceControlsWithPendingCallback.empty()) {
332 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
333 mSurfaceControlsWithPendingCallback.pop();
chaviwd7deef72021-10-06 11:53:40 -0500334 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
335 if (statsOptional) {
336 SurfaceControlStats stat = *statsOptional;
chaviw42026162021-04-16 15:46:12 -0500337 mTransformHint = stat.transformHint;
338 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700339 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
Vishnu Nairde66dc72021-06-17 17:54:41 -0700340 // Update frametime stamps if the frame was latched and presented, indicated by a
341 // valid latch time.
342 if (stat.latchTime > 0) {
343 mBufferItemConsumer
344 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
345 stat.frameEventStats.refreshStartTime,
346 stat.frameEventStats.gpuCompositionDoneFence,
347 stat.presentFence, stat.previousReleaseFence,
348 stat.frameEventStats.compositorTiming,
349 stat.latchTime,
350 stat.frameEventStats.dequeueReadyTime);
351 }
Robert Carr405e2f62021-12-31 16:59:34 -0800352 auto currFrameNumber = stat.frameEventStats.frameNumber;
353 std::vector<ReleaseCallbackId> staleReleases;
354 for (const auto& [key, value]: mSubmitted) {
355 if (currFrameNumber > key.framenumber) {
356 staleReleases.push_back(key);
357 }
358 }
359 for (const auto& staleRelease : staleReleases) {
Robert Carr405e2f62021-12-31 16:59:34 -0800360 releaseBufferCallbackLocked(staleRelease,
Vishnu Nair74ca6ab2022-11-01 14:29:10 -0700361 stat.previousReleaseFence
362 ? stat.previousReleaseFence
363 : Fence::NO_FENCE,
364 stat.currentMaxAcquiredBufferCount,
365 true /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800366 }
chaviwd7deef72021-10-06 11:53:40 -0500367 } else {
chaviw768bfa02021-11-01 09:50:57 -0500368 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500369 }
370 } else {
371 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
372 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800373 }
chaviw71c2cc42020-10-23 16:42:02 -0700374
chaviw71c2cc42020-10-23 16:42:02 -0700375 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700376 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700377}
378
Vishnu Nair1506b182021-02-22 14:35:15 -0800379// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
380// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
381// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
382// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700383static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
chaviw69058fb2021-09-27 09:37:30 -0500384 const sp<Fence>& releaseFence,
385 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800386 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800387 if (blastBufferQueue) {
chaviw69058fb2021-09-27 09:37:30 -0500388 blastBufferQueue->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700389 } else {
390 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800391 }
392}
393
chaviwd7deef72021-10-06 11:53:40 -0500394void BLASTBufferQueue::flushShadowQueue() {
395 BQA_LOGV("flushShadowQueue");
396 int numFramesToFlush = mNumFrameAvailable;
397 while (numFramesToFlush > 0) {
398 acquireNextBufferLocked(std::nullopt);
399 numFramesToFlush--;
400 }
401}
402
chaviw69058fb2021-09-27 09:37:30 -0500403void BLASTBufferQueue::releaseBufferCallback(
404 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
405 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
chaviw57ae4b22022-02-03 16:51:39 -0600406 BBQ_TRACE();
Robert Carr405e2f62021-12-31 16:59:34 -0800407
Vishnu Nair1506b182021-02-22 14:35:15 -0800408 std::unique_lock _lock{mMutex};
Vishnu Nair74ca6ab2022-11-01 14:29:10 -0700409 releaseBufferCallbackLocked(id, releaseFence, currentMaxAcquiredBufferCount,
410 false /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800411}
412
Vishnu Nair74ca6ab2022-11-01 14:29:10 -0700413void BLASTBufferQueue::releaseBufferCallbackLocked(
414 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
415 std::optional<uint32_t> currentMaxAcquiredBufferCount, bool fakeRelease) {
Robert Carr405e2f62021-12-31 16:59:34 -0800416 ATRACE_CALL();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700417 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800418
Ady Abraham899dcdb2021-06-15 16:56:21 -0700419 // Calculate how many buffers we need to hold before we release them back
420 // to the buffer queue. This will prevent higher latency when we are running
421 // on a lower refresh rate than the max supported. We only do that for EGL
422 // clients as others don't care about latency
423 const bool isEGL = [&] {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700424 const auto it = mSubmitted.find(id);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700425 return it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
426 }();
427
chaviw69058fb2021-09-27 09:37:30 -0500428 if (currentMaxAcquiredBufferCount) {
429 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
430 }
431
Ady Abraham899dcdb2021-06-15 16:56:21 -0700432 const auto numPendingBuffersToHold =
chaviw69058fb2021-09-27 09:37:30 -0500433 isEGL ? std::max(0u, mMaxAcquiredBuffers - mCurrentMaxAcquiredBufferCount) : 0;
Robert Carr405e2f62021-12-31 16:59:34 -0800434
435 auto rb = ReleasedBuffer{id, releaseFence};
436 if (std::find(mPendingRelease.begin(), mPendingRelease.end(), rb) == mPendingRelease.end()) {
437 mPendingRelease.emplace_back(rb);
Vishnu Nair74ca6ab2022-11-01 14:29:10 -0700438 if (fakeRelease) {
439 BQA_LOGE("Faking releaseBufferCallback from transactionCompleteCallback %" PRIu64,
440 id.framenumber);
441 BBQ_TRACE("FakeReleaseCallback");
442 }
Robert Carr405e2f62021-12-31 16:59:34 -0800443 }
Ady Abraham899dcdb2021-06-15 16:56:21 -0700444
445 // Release all buffers that are beyond the ones that we need to hold
446 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500447 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700448 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500449 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwc1cf4022022-06-03 13:32:33 -0500450 // Don't process the transactions here if mSyncedFrameNumbers is not empty. That means
451 // are still transactions that have sync buffers in them that have not been applied or
452 // dropped. Instead, let onFrameAvailable handle processing them since it will merge with
453 // the syncTransaction.
454 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500455 acquireNextBufferLocked(std::nullopt);
456 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800457 }
458
Ady Abraham899dcdb2021-06-15 16:56:21 -0700459 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700460 ATRACE_INT(mQueuedBufferTrace.c_str(),
461 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800462 mCallbackCV.notify_all();
463}
464
chaviw0acd33a2021-11-02 11:55:37 -0500465void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
466 const sp<Fence>& releaseFence) {
467 auto it = mSubmitted.find(callbackId);
468 if (it == mSubmitted.end()) {
469 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
470 callbackId.to_string().c_str());
471 return;
472 }
473 mNumAcquired--;
chaviw57ae4b22022-02-03 16:51:39 -0600474 BBQ_TRACE("frame=%" PRIu64, callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500475 BQA_LOGV("released %s", callbackId.to_string().c_str());
476 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
477 mSubmitted.erase(it);
chaviwc1cf4022022-06-03 13:32:33 -0500478 // Remove the frame number from mSyncedFrameNumbers since we can get a release callback
479 // without getting a transaction committed if the buffer was dropped.
480 mSyncedFrameNumbers.erase(callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500481}
482
Chavi Weingarten92bf8b02022-12-27 22:00:24 +0000483status_t BLASTBufferQueue::acquireNextBufferLocked(
chaviwd7deef72021-10-06 11:53:40 -0500484 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Vishnu Nair1e01c412023-01-20 10:00:18 -0800485 // Check if we have frames available and we have not acquired the maximum number of buffers.
486 // Even with this check, the consumer can fail to acquire an additional buffer if the consumer
487 // has already acquired (mMaxAcquiredBuffers + 1) and the new buffer is not droppable. In this
488 // case mBufferItemConsumer->acquireBuffer will return with NO_BUFFER_AVAILABLE.
Chavi Weingarten92bf8b02022-12-27 22:00:24 +0000489 if (mNumFrameAvailable == 0) {
Vishnu Nair1e01c412023-01-20 10:00:18 -0800490 BQA_LOGV("Can't acquire next buffer. No available frames");
491 return BufferQueue::NO_BUFFER_AVAILABLE;
492 }
493
494 if (mNumAcquired >= (mMaxAcquiredBuffers + 2)) {
495 BQA_LOGV("Can't acquire next buffer. Already acquired max frames %d max:%d + 2",
496 mNumAcquired, mMaxAcquiredBuffers);
497 return BufferQueue::NO_BUFFER_AVAILABLE;
Valerie Haud3b90d22019-11-06 09:37:31 -0800498 }
499
Valerie Haua32c5522019-12-09 10:11:08 -0800500 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700501 BQA_LOGE("ERROR : surface control is null");
Chavi Weingarten92bf8b02022-12-27 22:00:24 +0000502 return NAME_NOT_FOUND;
Valerie Haud3b90d22019-11-06 09:37:31 -0800503 }
504
Robert Carr78c25dd2019-08-15 14:10:33 -0700505 SurfaceComposerClient::Transaction localTransaction;
506 bool applyTransaction = true;
507 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500508 if (transaction) {
509 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700510 applyTransaction = false;
511 }
512
Valerie Haua32c5522019-12-09 10:11:08 -0800513 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800514
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800515 status_t status =
516 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800517 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
518 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
Chavi Weingarten92bf8b02022-12-27 22:00:24 +0000519 return status;
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800520 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700521 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Chavi Weingarten92bf8b02022-12-27 22:00:24 +0000522 return status;
Robert Carr78c25dd2019-08-15 14:10:33 -0700523 }
chaviw57ae4b22022-02-03 16:51:39 -0600524
Valerie Haua32c5522019-12-09 10:11:08 -0800525 auto buffer = bufferItem.mGraphicBuffer;
526 mNumFrameAvailable--;
chaviw57ae4b22022-02-03 16:51:39 -0600527 BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800528
529 if (buffer == nullptr) {
530 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700531 BQA_LOGE("Buffer was empty");
Chavi Weingarten92bf8b02022-12-27 22:00:24 +0000532 return BAD_VALUE;
Valerie Haua32c5522019-12-09 10:11:08 -0800533 }
534
Vishnu Nair670b3f72020-09-29 17:52:18 -0700535 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700536 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800537 "buffer{size=%dx%d transform=%d}",
538 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
539 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
540 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Chavi Weingarten92bf8b02022-12-27 22:00:24 +0000541 return acquireNextBufferLocked(transaction);
Vishnu Nair670b3f72020-09-29 17:52:18 -0700542 }
543
Valerie Haua32c5522019-12-09 10:11:08 -0800544 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700545 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
546 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
547 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700548
Valerie Hau871d6352020-01-29 08:44:02 -0800549 bool needsDisconnect = false;
550 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
551
552 // if producer disconnected before, notify SurfaceFlinger
553 if (needsDisconnect) {
554 t->notifyProducerDisconnect(mSurfaceControl);
555 }
556
Robert Carr78c25dd2019-08-15 14:10:33 -0700557 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
558 incStrong((void*)transactionCallbackThunk);
559
Vishnu Nair932f6ae2021-09-29 17:33:10 -0700560 mSize = mRequestedSize;
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700561 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000562 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
563 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700564 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800565
Vishnu Nair1506b182021-02-22 14:35:15 -0800566 auto releaseBufferCallback =
567 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
chaviw69058fb2021-09-27 09:37:30 -0500568 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
chaviwba4320c2021-09-15 15:20:53 -0500569 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
chaviw8dd181f2022-01-05 18:36:46 -0600570 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500571 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
572 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
573 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700574 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviwf2dace72021-11-17 17:36:50 -0600575
chaviw42026162021-04-16 15:46:12 -0500576 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700577
Vishnu Naird2aaab12022-02-10 14:49:09 -0800578 if (mUpdateDestinationFrame) {
579 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
580 } else {
581 const bool ignoreDestinationFrame =
582 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
583 t->setFlags(mSurfaceControl,
584 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
585 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700586 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700587 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800588 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800589 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800590 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800591 if (!bufferItem.mIsAutoTimestamp) {
592 t->setDesiredPresentTime(bufferItem.mTimestamp);
593 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700594
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000595 if (!mNextFrameTimelineInfoQueue.empty()) {
Ady Abraham8db10102021-03-15 17:19:23 -0700596 t->setFrameTimelineInfo(mNextFrameTimelineInfoQueue.front());
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000597 mNextFrameTimelineInfoQueue.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100598 }
599
Vishnu Nairadf632b2021-01-07 14:05:08 -0800600 {
601 std::unique_lock _lock{mTimestampMutex};
602 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
603 if (dequeueTime != mDequeueTimestamps.end()) {
604 Parcel p;
605 p.writeInt64(dequeueTime->second);
606 t->setMetadata(mSurfaceControl, METADATA_DEQUEUE_TIME, p);
607 mDequeueTimestamps.erase(dequeueTime);
608 }
609 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800610
chaviw6a195272021-09-03 16:14:25 -0500611 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700612 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800613 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
614 t->setApplyToken(mApplyToken).apply(false, true);
615 mAppliedLastTransaction = true;
616 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
617 } else {
618 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
619 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700620 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700621
chaviwd7deef72021-10-06 11:53:40 -0500622 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800623 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700624 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500625 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800626 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700627 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700628 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Chavi Weingarten92bf8b02022-12-27 22:00:24 +0000629 return OK;
Robert Carr78c25dd2019-08-15 14:10:33 -0700630}
631
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800632Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
633 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800634 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800635 }
636 return item.mCrop;
637}
638
chaviwd7deef72021-10-06 11:53:40 -0500639void BLASTBufferQueue::acquireAndReleaseBuffer() {
640 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500641 status_t status =
642 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
643 if (status != OK) {
644 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
645 statusToString(status).c_str());
646 return;
647 }
chaviwd7deef72021-10-06 11:53:40 -0500648 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500649 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500650}
651
Vishnu Nairaef1de92020-10-22 12:15:53 -0700652void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000653 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
654 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
chaviwc1cf4022022-06-03 13:32:33 -0500655
Tianhao Yao4861b102022-02-03 20:18:35 +0000656 {
Tianhao Yao4861b102022-02-03 20:18:35 +0000657 std::unique_lock _lock{mMutex};
Vishnu Nair1e01c412023-01-20 10:00:18 -0800658 BBQ_TRACE();
659
660 bool waitForTransactionCallback = !mSyncedFrameNumbers.empty();
Tianhao Yao4861b102022-02-03 20:18:35 +0000661 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
662 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800663
Tianhao Yao4861b102022-02-03 20:18:35 +0000664 if (syncTransactionSet) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000665 // If we are going to re-use the same mSyncTransaction, release the buffer that may
666 // already be set in the Transaction. This is to allow us a free slot early to continue
667 // processing a new buffer.
668 if (!mAcquireSingleBuffer) {
669 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
670 if (bufferData) {
671 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
672 bufferData->frameNumber);
673 releaseBuffer(bufferData->generateReleaseCallbackId(),
674 bufferData->acquireFence);
Tianhao Yao4861b102022-02-03 20:18:35 +0000675 }
676 }
chaviw0acd33a2021-11-02 11:55:37 -0500677
Chavi Weingarten92bf8b02022-12-27 22:00:24 +0000678 if (waitForTransactionCallback) {
679 // We are waiting on a previous sync's transaction callback so allow another sync
680 // transaction to proceed.
681 //
682 // We need to first flush out the transactions that were in between the two syncs.
683 // We do this by merging them into mSyncTransaction so any buffer merging will get
684 // a release callback invoked.
685 while (mNumFrameAvailable > 0) {
686 // flush out the shadow queue
687 acquireAndReleaseBuffer();
688 }
Vishnu Nair1e01c412023-01-20 10:00:18 -0800689 } else {
690 // Make sure the frame available count is 0 before proceeding with a sync to ensure
691 // the correct frame is used for the sync. The only way mNumFrameAvailable would be
692 // greater than 0 is if we already ran out of buffers previously. This means we
693 // need to flush the buffers before proceeding with the sync.
694 while (mNumFrameAvailable > 0) {
695 BQA_LOGD("waiting until no queued buffers");
696 mCallbackCV.wait(_lock);
697 }
chaviwd7deef72021-10-06 11:53:40 -0500698 }
699 }
700
Tianhao Yao4861b102022-02-03 20:18:35 +0000701 // add to shadow queue
702 mNumFrameAvailable++;
chaviwc1cf4022022-06-03 13:32:33 -0500703 if (waitForTransactionCallback && mNumFrameAvailable >= 2) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000704 acquireAndReleaseBuffer();
705 }
706 ATRACE_INT(mQueuedBufferTrace.c_str(),
707 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
708
709 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
710 item.mFrameNumber, boolToString(syncTransactionSet));
711
712 if (syncTransactionSet) {
Vishnu Nair1e01c412023-01-20 10:00:18 -0800713 // Add to mSyncedFrameNumbers before waiting in case any buffers are released
714 // while waiting for a free buffer. The release and commit callback will try to
715 // acquire buffers if there are any available, but we don't want it to acquire
716 // in the case where a sync transaction wants the buffer.
717 mSyncedFrameNumbers.emplace(item.mFrameNumber);
Chavi Weingarten92bf8b02022-12-27 22:00:24 +0000718 // If there's no available buffer and we're in a sync transaction, we need to wait
719 // instead of returning since we guarantee a buffer will be acquired for the sync.
720 while (acquireNextBufferLocked(mSyncTransaction) == BufferQueue::NO_BUFFER_AVAILABLE) {
721 BQA_LOGD("waiting for available buffer");
722 mCallbackCV.wait(_lock);
723 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000724
725 // Only need a commit callback when syncing to ensure the buffer that's synced has been
726 // sent to SF
727 incStrong((void*)transactionCommittedCallbackThunk);
728 mSyncTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,
729 static_cast<void*>(this));
Tianhao Yao4861b102022-02-03 20:18:35 +0000730 if (mAcquireSingleBuffer) {
731 prevCallback = mTransactionReadyCallback;
732 prevTransaction = mSyncTransaction;
733 mTransactionReadyCallback = nullptr;
734 mSyncTransaction = nullptr;
735 }
chaviwc1cf4022022-06-03 13:32:33 -0500736 } else if (!waitForTransactionCallback) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000737 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800738 }
739 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000740 if (prevCallback) {
741 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500742 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800743}
744
Vishnu Nairaef1de92020-10-22 12:15:53 -0700745void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
746 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
747 // Do nothing since we are not storing unacquired buffer items locally.
748}
749
Vishnu Nairadf632b2021-01-07 14:05:08 -0800750void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
751 std::unique_lock _lock{mTimestampMutex};
752 mDequeueTimestamps[bufferId] = systemTime();
753};
754
755void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
756 std::unique_lock _lock{mTimestampMutex};
757 mDequeueTimestamps.erase(bufferId);
758};
759
Tianhao Yao4861b102022-02-03 20:18:35 +0000760void BLASTBufferQueue::syncNextTransaction(
761 std::function<void(SurfaceComposerClient::Transaction*)> callback,
762 bool acquireSingleBuffer) {
chaviw57ae4b22022-02-03 16:51:39 -0600763 BBQ_TRACE();
chaviw3b4bdcf2022-03-17 09:27:03 -0500764
765 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
766 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
767
768 {
769 std::lock_guard _lock{mMutex};
770 // We're about to overwrite the previous call so we should invoke that callback
771 // immediately.
772 if (mTransactionReadyCallback) {
773 prevCallback = mTransactionReadyCallback;
774 prevTransaction = mSyncTransaction;
775 }
776
777 mTransactionReadyCallback = callback;
778 if (callback) {
779 mSyncTransaction = new SurfaceComposerClient::Transaction();
780 } else {
781 mSyncTransaction = nullptr;
782 }
783 mAcquireSingleBuffer = mTransactionReadyCallback ? acquireSingleBuffer : true;
Tianhao Yao4861b102022-02-03 20:18:35 +0000784 }
chaviw3b4bdcf2022-03-17 09:27:03 -0500785
786 if (prevCallback) {
787 prevCallback(prevTransaction);
788 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000789}
790
791void BLASTBufferQueue::stopContinuousSyncTransaction() {
792 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
793 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
794 {
795 std::lock_guard _lock{mMutex};
796 bool invokeCallback = mTransactionReadyCallback && !mAcquireSingleBuffer;
797 if (invokeCallback) {
798 prevCallback = mTransactionReadyCallback;
799 prevTransaction = mSyncTransaction;
800 }
801 mTransactionReadyCallback = nullptr;
802 mSyncTransaction = nullptr;
803 mAcquireSingleBuffer = true;
804 }
805 if (prevCallback) {
806 prevCallback(prevTransaction);
807 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700808}
809
Vishnu Nairea0de002020-11-17 17:42:37 -0800810bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700811 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
812 // Only reject buffers if scaling mode is freeze.
813 return false;
814 }
815
Vishnu Naire1a42322020-10-02 17:42:04 -0700816 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
817 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
818
819 // Take the buffer's orientation into account
820 if (item.mTransform & ui::Transform::ROT_90) {
821 std::swap(bufWidth, bufHeight);
822 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800823 ui::Size bufferSize(bufWidth, bufHeight);
824 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800825 return false;
826 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700827
Vishnu Nair670b3f72020-09-29 17:52:18 -0700828 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800829 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700830}
Vishnu Nairbf255772020-10-16 10:54:41 -0700831
Robert Carr05086b22020-10-13 18:22:51 -0700832class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700833private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700834 std::mutex mMutex;
Robert Carr9c006e02020-10-14 13:41:57 -0700835 sp<BLASTBufferQueue> mBbq;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700836 bool mDestroyed = false;
837
Robert Carr05086b22020-10-13 18:22:51 -0700838public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700839 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
840 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
841 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700842
Robert Carr05086b22020-10-13 18:22:51 -0700843 void allocateBuffers() override {
844 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
845 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
846 auto gbp = getIGraphicBufferProducer();
847 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
848 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
849 gbp->allocateBuffers(reqWidth, reqHeight,
850 reqFormat, reqUsage);
851
852 }).detach();
853 }
Robert Carr9c006e02020-10-14 13:41:57 -0700854
Marin Shalamanovc5986772021-03-16 16:09:49 +0100855 status_t setFrameRate(float frameRate, int8_t compatibility,
856 int8_t changeFrameRateStrategy) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700857 std::unique_lock _lock{mMutex};
858 if (mDestroyed) {
859 return DEAD_OBJECT;
860 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100861 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
862 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700863 return BAD_VALUE;
864 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100865 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700866 }
Robert Carr9b611b72020-10-19 12:00:23 -0700867
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000868 status_t setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700869 std::unique_lock _lock{mMutex};
870 if (mDestroyed) {
871 return DEAD_OBJECT;
872 }
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000873 return mBbq->setFrameTimelineInfo(frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700874 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700875
876 void destroy() override {
877 Surface::destroy();
878
879 std::unique_lock _lock{mMutex};
880 mDestroyed = true;
881 mBbq = nullptr;
882 }
Robert Carr05086b22020-10-13 18:22:51 -0700883};
884
Robert Carr9c006e02020-10-14 13:41:57 -0700885// TODO: Can we coalesce this with frame updates? Need to confirm
886// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200887status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
888 bool shouldBeSeamless) {
Robert Carr9c006e02020-10-14 13:41:57 -0700889 std::unique_lock _lock{mMutex};
890 SurfaceComposerClient::Transaction t;
891
Marin Shalamanov46084422020-10-13 12:33:42 +0200892 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700893}
894
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000895status_t BLASTBufferQueue::setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) {
Robert Carr9b611b72020-10-19 12:00:23 -0700896 std::unique_lock _lock{mMutex};
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000897 mNextFrameTimelineInfoQueue.push(frameTimelineInfo);
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100898 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700899}
900
Hongguang Chen621ec582021-02-16 15:42:35 -0800901void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
902 std::unique_lock _lock{mMutex};
903 SurfaceComposerClient::Transaction t;
904
905 t.setSidebandStream(mSurfaceControl, stream).apply();
906}
907
Vishnu Nair992496b2020-10-22 17:27:21 -0700908sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
909 std::unique_lock _lock{mMutex};
910 sp<IBinder> scHandle = nullptr;
911 if (includeSurfaceControlHandle && mSurfaceControl) {
912 scHandle = mSurfaceControl->getHandle();
913 }
914 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700915}
916
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800917void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
918 uint64_t frameNumber) {
919 std::lock_guard _lock{mMutex};
920 if (mLastAcquiredFrameNumber >= frameNumber) {
921 // Apply the transaction since we have already acquired the desired frame.
922 t->apply();
923 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500924 mPendingTransactions.emplace_back(frameNumber, *t);
925 // Clear the transaction so it can't be applied elsewhere.
926 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800927 }
928}
929
chaviw6a195272021-09-03 16:14:25 -0500930void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
931 std::lock_guard _lock{mMutex};
932
933 SurfaceComposerClient::Transaction t;
934 mergePendingTransactions(&t, frameNumber);
Robert Carr79dc06a2022-02-22 15:28:59 -0800935 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
936 t.setApplyToken(mApplyToken).apply(false, true);
chaviw6a195272021-09-03 16:14:25 -0500937}
938
939void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
940 uint64_t frameNumber) {
941 auto mergeTransaction =
942 [&t, currentFrameNumber = frameNumber](
943 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
944 auto& [targetFrameNumber, transaction] = pendingTransaction;
945 if (currentFrameNumber < targetFrameNumber) {
946 return false;
947 }
948 t->merge(std::move(transaction));
949 return true;
950 };
951
952 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
953 mPendingTransactions.end(), mergeTransaction),
954 mPendingTransactions.end());
955}
956
chaviwd84085a2022-02-08 11:07:04 -0600957SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
958 uint64_t frameNumber) {
959 std::lock_guard _lock{mMutex};
960 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
961 mergePendingTransactions(t, frameNumber);
962 return t;
963}
964
Vishnu Nair89496122020-12-14 17:14:53 -0800965// Maintains a single worker thread per process that services a list of runnables.
966class AsyncWorker : public Singleton<AsyncWorker> {
967private:
968 std::thread mThread;
969 bool mDone = false;
970 std::deque<std::function<void()>> mRunnables;
971 std::mutex mMutex;
972 std::condition_variable mCv;
973 void run() {
974 std::unique_lock<std::mutex> lock(mMutex);
975 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -0800976 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700977 std::deque<std::function<void()>> runnables = std::move(mRunnables);
978 mRunnables.clear();
979 lock.unlock();
980 // Run outside the lock since the runnable might trigger another
981 // post to the async worker.
982 execute(runnables);
983 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -0800984 }
Wonsik Kim567533e2021-05-04 19:31:29 -0700985 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -0800986 }
987 }
988
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700989 void execute(std::deque<std::function<void()>>& runnables) {
990 while (!runnables.empty()) {
991 std::function<void()> runnable = runnables.front();
992 runnables.pop_front();
993 runnable();
994 }
995 }
996
Vishnu Nair89496122020-12-14 17:14:53 -0800997public:
998 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
999
1000 ~AsyncWorker() {
1001 mDone = true;
1002 mCv.notify_all();
1003 if (mThread.joinable()) {
1004 mThread.join();
1005 }
1006 }
1007
1008 void post(std::function<void()> runnable) {
1009 std::unique_lock<std::mutex> lock(mMutex);
1010 mRunnables.emplace_back(std::move(runnable));
1011 mCv.notify_one();
1012 }
1013};
1014ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
1015
1016// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
1017class AsyncProducerListener : public BnProducerListener {
1018private:
1019 const sp<IProducerListener> mListener;
1020
1021public:
1022 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
1023
1024 void onBufferReleased() override {
1025 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
1026 }
1027
1028 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
1029 AsyncWorker::getInstance().post(
1030 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
1031 }
1032};
1033
1034// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
1035// can be non-blocking when the producer is in the client process.
1036class BBQBufferQueueProducer : public BufferQueueProducer {
1037public:
1038 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
1039 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
1040
1041 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
1042 QueueBufferOutput* output) override {
1043 if (!listener) {
1044 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
1045 }
1046
1047 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
1048 producerControlledByApp, output);
1049 }
Vishnu Nair17dde612020-12-28 11:39:59 -08001050
1051 int query(int what, int* value) override {
1052 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
1053 *value = 1;
1054 return NO_ERROR;
1055 }
1056 return BufferQueueProducer::query(what, value);
1057 }
Vishnu Nair89496122020-12-14 17:14:53 -08001058};
1059
1060// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
1061// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
1062// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
1063// we can deadlock.
1064void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
1065 sp<IGraphicBufferConsumer>* outConsumer) {
1066 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
1067 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
1068
1069 sp<BufferQueueCore> core(new BufferQueueCore());
1070 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
1071
1072 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
1073 LOG_ALWAYS_FATAL_IF(producer == nullptr,
1074 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
1075
Vishnu Nair8b30dd12021-01-25 14:16:54 -08001076 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
1077 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -08001078 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
1079 "BLASTBufferQueue: failed to create BufferQueueConsumer");
1080
1081 *outProducer = producer;
1082 *outConsumer = consumer;
1083}
1084
chaviw497e81c2021-02-04 17:09:47 -08001085PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
1086 PixelFormat convertedFormat = format;
1087 switch (format) {
1088 case PIXEL_FORMAT_TRANSPARENT:
1089 case PIXEL_FORMAT_TRANSLUCENT:
1090 convertedFormat = PIXEL_FORMAT_RGBA_8888;
1091 break;
1092 case PIXEL_FORMAT_OPAQUE:
1093 convertedFormat = PIXEL_FORMAT_RGBX_8888;
1094 break;
1095 }
1096 return convertedFormat;
1097}
1098
Robert Carr82d07c92021-05-10 11:36:43 -07001099uint32_t BLASTBufferQueue::getLastTransformHint() const {
1100 if (mSurfaceControl != nullptr) {
1101 return mSurfaceControl->getTransformHint();
1102 } else {
1103 return 0;
1104 }
1105}
1106
chaviw0b020f82021-08-20 12:00:47 -05001107uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
1108 std::unique_lock _lock{mMutex};
1109 return mLastAcquiredFrameNumber;
1110}
1111
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001112void BLASTBufferQueue::abandon() {
1113 std::unique_lock _lock{mMutex};
1114 // flush out the shadow queue
1115 while (mNumFrameAvailable > 0) {
1116 acquireAndReleaseBuffer();
1117 }
1118
1119 // Clear submitted buffer states
1120 mNumAcquired = 0;
1121 mSubmitted.clear();
1122 mPendingRelease.clear();
1123
1124 if (!mPendingTransactions.empty()) {
1125 BQA_LOGD("Applying pending transactions on abandon %d",
1126 static_cast<uint32_t>(mPendingTransactions.size()));
1127 SurfaceComposerClient::Transaction t;
1128 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
Robert Carr79dc06a2022-02-22 15:28:59 -08001129 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
1130 t.setApplyToken(mApplyToken).apply(false, true);
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001131 }
1132
1133 // Clear sync states
chaviwc1cf4022022-06-03 13:32:33 -05001134 if (!mSyncedFrameNumbers.empty()) {
1135 BQA_LOGD("mSyncedFrameNumbers cleared");
1136 mSyncedFrameNumbers.clear();
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001137 }
1138
1139 if (mSyncTransaction != nullptr) {
1140 BQA_LOGD("mSyncTransaction cleared mAcquireSingleBuffer=%s",
1141 mAcquireSingleBuffer ? "true" : "false");
1142 mSyncTransaction = nullptr;
1143 mAcquireSingleBuffer = false;
1144 }
1145
1146 // abandon buffer queue
1147 if (mBufferItemConsumer != nullptr) {
1148 mBufferItemConsumer->abandon();
1149 mBufferItemConsumer->setFrameAvailableListener(nullptr);
1150 mBufferItemConsumer->setBufferFreedListener(nullptr);
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001151 }
1152 mBufferItemConsumer = nullptr;
1153 mConsumer = nullptr;
1154 mProducer = nullptr;
1155}
1156
1157bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
1158 std::unique_lock _lock{mMutex};
1159 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1160}
1161
Robert Carr4c1b6462021-12-21 10:30:50 -08001162void BLASTBufferQueue::setTransactionHangCallback(std::function<void(bool)> callback) {
1163 std::unique_lock _lock{mMutex};
1164 mTransactionHangCallback = callback;
1165}
1166
Robert Carr78c25dd2019-08-15 14:10:33 -07001167} // namespace android