blob: 207fa4fd319e8bb795473a3059d10139b8a76e17 [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
liulijuneb489f62022-10-17 22:02:14 +080023#include <cutils/atomic.h>
Robert Carr78c25dd2019-08-15 14:10:33 -070024#include <gui/BLASTBufferQueue.h>
25#include <gui/BufferItemConsumer.h>
Vishnu Nair89496122020-12-14 17:14:53 -080026#include <gui/BufferQueueConsumer.h>
27#include <gui/BufferQueueCore.h>
28#include <gui/BufferQueueProducer.h>
Valerie Hau45e4b3b2019-12-03 10:49:17 -080029#include <gui/GLConsumer.h>
Vishnu Nair89496122020-12-14 17:14:53 -080030#include <gui/IProducerListener.h>
Robert Carr05086b22020-10-13 18:22:51 -070031#include <gui/Surface.h>
chaviw57ae4b22022-02-03 16:51:39 -060032#include <gui/TraceUtils.h>
Vishnu Nair89496122020-12-14 17:14:53 -080033#include <utils/Singleton.h>
Valerie Haua32c5522019-12-09 10:11:08 -080034#include <utils/Trace.h>
35
Ady Abraham0bde6b52021-05-18 13:57:02 -070036#include <private/gui/ComposerService.h>
Huihong Luo02186fb2022-02-23 14:21:54 -080037#include <private/gui/ComposerServiceAIDL.h>
Ady Abraham0bde6b52021-05-18 13:57:02 -070038
Chavi Weingartene0237bb2023-02-06 21:48:32 +000039#include <android-base/thread_annotations.h>
Robert Carr78c25dd2019-08-15 14:10:33 -070040#include <chrono>
41
42using namespace std::chrono_literals;
43
Vishnu Nairdab94092020-09-29 16:09:04 -070044namespace {
chaviw3277faf2021-05-19 16:45:23 -050045inline const char* boolToString(bool b) {
Vishnu Nairdab94092020-09-29 16:09:04 -070046 return b ? "true" : "false";
47}
48} // namespace
49
Robert Carr78c25dd2019-08-15 14:10:33 -070050namespace android {
51
Vishnu Nairdab94092020-09-29 16:09:04 -070052// Macros to include adapter info in log messages
chaviwd7deef72021-10-06 11:53:40 -050053#define BQA_LOGD(x, ...) \
54 ALOGD("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070055#define BQA_LOGV(x, ...) \
56 ALOGV("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairc6f89ee2020-12-11 14:27:32 -080057// enable logs for a single layer
58//#define BQA_LOGV(x, ...) \
59// ALOGV_IF((strstr(mName.c_str(), "SurfaceView") != nullptr), "[%s](f:%u,a:%u) " x, \
60// mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070061#define BQA_LOGE(x, ...) \
62 ALOGE("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
63
chaviw57ae4b22022-02-03 16:51:39 -060064#define BBQ_TRACE(x, ...) \
65 ATRACE_FORMAT("%s - %s(f:%u,a:%u)" x, __FUNCTION__, mName.c_str(), mNumFrameAvailable, \
66 mNumAcquired, ##__VA_ARGS__)
67
Chavi Weingartene0237bb2023-02-06 21:48:32 +000068#define UNIQUE_LOCK_WITH_ASSERTION(mutex) \
69 std::unique_lock _lock{mutex}; \
70 base::ScopedLockAssertion assumeLocked(mutex);
71
Valerie Hau871d6352020-01-29 08:44:02 -080072void BLASTBufferItemConsumer::onDisconnect() {
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000073 Mutex::Autolock lock(mMutex);
74 mPreviouslyConnected = mCurrentlyConnected;
75 mCurrentlyConnected = false;
76 if (mPreviouslyConnected) {
77 mDisconnectEvents.push(mCurrentFrameNumber);
Valerie Hau871d6352020-01-29 08:44:02 -080078 }
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000079 mFrameEventHistory.onDisconnect();
Valerie Hau871d6352020-01-29 08:44:02 -080080}
81
82void BLASTBufferItemConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
83 FrameEventHistoryDelta* outDelta) {
Hongguang Chen621ec582021-02-16 15:42:35 -080084 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080085 if (newTimestamps) {
86 // BufferQueueProducer only adds a new timestamp on
87 // queueBuffer
88 mCurrentFrameNumber = newTimestamps->frameNumber;
89 mFrameEventHistory.addQueue(*newTimestamps);
90 }
91 if (outDelta) {
92 // frame event histories will be processed
93 // only after the producer connects and requests
94 // deltas for the first time. Forward this intent
95 // to SF-side to turn event processing back on
96 mPreviouslyConnected = mCurrentlyConnected;
97 mCurrentlyConnected = true;
98 mFrameEventHistory.getAndResetDelta(outDelta);
99 }
100}
101
102void BLASTBufferItemConsumer::updateFrameTimestamps(uint64_t frameNumber, nsecs_t refreshStartTime,
103 const sp<Fence>& glDoneFence,
104 const sp<Fence>& presentFence,
105 const sp<Fence>& prevReleaseFence,
106 CompositorTiming compositorTiming,
107 nsecs_t latchTime, nsecs_t dequeueReadyTime) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800108 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800109
110 // if the producer is not connected, don't bother updating,
111 // the next producer that connects won't access this frame event
112 if (!mCurrentlyConnected) return;
113 std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
114 std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
115 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
116
117 mFrameEventHistory.addLatch(frameNumber, latchTime);
118 mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
119 mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
120 mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
121 compositorTiming);
122}
123
124void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
125 bool disconnect = false;
Hongguang Chen621ec582021-02-16 15:42:35 -0800126 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800127 while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
128 disconnect = true;
129 mDisconnectEvents.pop();
130 }
131 if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
132}
133
Hongguang Chen621ec582021-02-16 15:42:35 -0800134void BLASTBufferItemConsumer::onSidebandStreamChanged() {
Ady Abrahamdbca1352021-12-15 11:58:56 -0800135 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
136 if (bbq != nullptr) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800137 sp<NativeHandle> stream = getSidebandStream();
Ady Abrahamdbca1352021-12-15 11:58:56 -0800138 bbq->setSidebandStream(stream);
Hongguang Chen621ec582021-02-16 15:42:35 -0800139 }
140}
141
Brian Lindahlc794b692023-01-31 15:42:47 -0700142void BLASTBufferItemConsumer::resizeFrameEventHistory(size_t newSize) {
143 Mutex::Autolock lock(mMutex);
144 mFrameEventHistory.resize(newSize);
145}
146
Vishnu Naird2aaab12022-02-10 14:49:09 -0800147BLASTBufferQueue::BLASTBufferQueue(const std::string& name, bool updateDestinationFrame)
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800148 : mSurfaceControl(nullptr),
149 mSize(1, 1),
Vishnu Nairea0de002020-11-17 17:42:37 -0800150 mRequestedSize(mSize),
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800151 mFormat(PIXEL_FORMAT_RGBA_8888),
Tianhao Yao4861b102022-02-03 20:18:35 +0000152 mTransactionReadyCallback(nullptr),
Vishnu Naird2aaab12022-02-10 14:49:09 -0800153 mSyncTransaction(nullptr),
154 mUpdateDestinationFrame(updateDestinationFrame) {
Vishnu Nair89496122020-12-14 17:14:53 -0800155 createBufferQueue(&mProducer, &mConsumer);
Valerie Hau0889c622020-02-19 15:04:47 -0800156 // since the adapter is in the client process, set dequeue timeout
157 // explicitly so that dequeueBuffer will block
158 mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
Valerie Hau65b8e872020-02-13 09:45:14 -0800159
Vishnu Nairdebd1cb2021-03-16 10:06:01 -0700160 // safe default, most producers are expected to override this
161 mProducer->setMaxDequeuedBufferCount(2);
Vishnu Nair1618c672021-02-05 13:08:26 -0800162 mBufferItemConsumer = new BLASTBufferItemConsumer(mConsumer,
163 GraphicBuffer::USAGE_HW_COMPOSER |
164 GraphicBuffer::USAGE_HW_TEXTURE,
Ady Abrahamdbca1352021-12-15 11:58:56 -0800165 1, false, this);
liulijuneb489f62022-10-17 22:02:14 +0800166 static std::atomic<uint32_t> nextId = 0;
167 mProducerId = nextId++;
168 mName = name + "#" + std::to_string(mProducerId);
169 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(mProducerId);
170 mQueuedBufferTrace = "QueuedBuffer - " + mName + "BLAST#" + std::to_string(mProducerId);
Vishnu Nairdab94092020-09-29 16:09:04 -0700171 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700172 mBufferItemConsumer->setFrameAvailableListener(this);
Robert Carr9f133d72020-04-01 15:51:46 -0700173
Huihong Luo02186fb2022-02-23 14:21:54 -0800174 ComposerServiceAIDL::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);
Ady Abraham0bde6b52021-05-18 13:57:02 -0700175 mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
chaviw69058fb2021-09-27 09:37:30 -0500176 mCurrentMaxAcquiredBufferCount = mMaxAcquiredBuffers;
Valerie Haua32c5522019-12-09 10:11:08 -0800177 mNumAcquired = 0;
178 mNumFrameAvailable = 0;
Robert Carr4c1b6462021-12-21 10:30:50 -0800179
180 TransactionCompletedListener::getInstance()->addQueueStallListener(
Patrick Williamsf1e5df12022-10-17 21:37:42 +0000181 [&](const std::string& reason) {
182 std::function<void(const std::string&)> callbackCopy;
183 {
184 std::unique_lock _lock{mMutex};
185 callbackCopy = mTransactionHangCallback;
186 }
187 if (callbackCopy) callbackCopy(reason);
188 },
189 this);
Robert Carr4c1b6462021-12-21 10:30:50 -0800190
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800191 BQA_LOGV("BLASTBufferQueue created");
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800192}
193
194BLASTBufferQueue::BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface,
195 int width, int height, int32_t format)
196 : BLASTBufferQueue(name) {
197 update(surface, width, height, format);
Robert Carr78c25dd2019-08-15 14:10:33 -0700198}
199
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800200BLASTBufferQueue::~BLASTBufferQueue() {
Robert Carr4c1b6462021-12-21 10:30:50 -0800201 TransactionCompletedListener::getInstance()->removeQueueStallListener(this);
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800202 if (mPendingTransactions.empty()) {
203 return;
204 }
205 BQA_LOGE("Applying pending transactions on dtor %d",
206 static_cast<uint32_t>(mPendingTransactions.size()));
207 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800208 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
Robert Carr79dc06a2022-02-22 15:28:59 -0800209 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
210 t.setApplyToken(mApplyToken).apply(false, true);
chaviw3b4bdcf2022-03-17 09:27:03 -0500211
212 if (mTransactionReadyCallback) {
213 mTransactionReadyCallback(mSyncTransaction);
214 }
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800215}
216
chaviw565ee542021-01-14 10:21:23 -0800217void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Naird2aaab12022-02-10 14:49:09 -0800218 int32_t format) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800219 LOG_ALWAYS_FATAL_IF(surface == nullptr, "BLASTBufferQueue: mSurfaceControl must not be NULL");
220
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000221 std::lock_guard _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800222 if (mFormat != format) {
223 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800224 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800225 }
226
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800227 const bool surfaceControlChanged = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairab066512022-01-04 22:28:00 +0000228 if (surfaceControlChanged && mSurfaceControl != nullptr) {
229 BQA_LOGD("Updating SurfaceControl without recreating BBQ");
230 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800231 bool applyTransaction = false;
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800232
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700233 // Always update the native object even though they might have the same layer handle, so we can
234 // get the updated transform hint from WM.
235 mSurfaceControl = surface;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800236 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800237 if (surfaceControlChanged) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800238 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
239 layer_state_t::eEnableBackpressure);
240 applyTransaction = true;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800241 }
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800242 mTransformHint = mSurfaceControl->getTransformHint();
243 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700244 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
245 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800246
Vishnu Nairea0de002020-11-17 17:42:37 -0800247 ui::Size newSize(width, height);
248 if (mRequestedSize != newSize) {
249 mRequestedSize.set(newSize);
250 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000251 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800252 // If the buffer supports scaling, update the frame immediately since the client may
253 // want to scale the existing buffer to the new size.
254 mSize = mRequestedSize;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800255 if (mUpdateDestinationFrame) {
256 t.setDestinationFrame(mSurfaceControl, Rect(newSize));
257 applyTransaction = true;
258 }
Vishnu Nair53c936c2020-12-03 11:46:37 -0800259 }
Robert Carrfc416512020-04-02 12:32:44 -0700260 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800261 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800262 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
263 t.setApplyToken(mApplyToken).apply(false, true);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800264 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700265}
266
chaviwd7deef72021-10-06 11:53:40 -0500267static std::optional<SurfaceControlStats> findMatchingStat(
268 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
269 for (auto stat : stats) {
270 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
271 return stat;
272 }
273 }
274 return std::nullopt;
275}
276
277static void transactionCommittedCallbackThunk(void* context, nsecs_t latchTime,
278 const sp<Fence>& presentFence,
279 const std::vector<SurfaceControlStats>& stats) {
280 if (context == nullptr) {
281 return;
282 }
283 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
284 bq->transactionCommittedCallback(latchTime, presentFence, stats);
285}
286
287void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
288 const sp<Fence>& /*presentFence*/,
289 const std::vector<SurfaceControlStats>& stats) {
290 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000291 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600292 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500293 BQA_LOGV("transactionCommittedCallback");
294 if (!mSurfaceControlsWithPendingCallback.empty()) {
295 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
296 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
297 if (stat) {
298 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
299
300 // We need to check if we were waiting for a transaction callback in order to
301 // process any pending buffers and unblock. It's possible to get transaction
chaviwc1cf4022022-06-03 13:32:33 -0500302 // callbacks for previous requests so we need to ensure that there are no pending
303 // frame numbers that were in a sync. We remove the frame from mSyncedFrameNumbers
304 // set and then check if it's empty. If there are no more pending syncs, we can
305 // proceed with flushing the shadow queue.
chaviwc1cf4022022-06-03 13:32:33 -0500306 mSyncedFrameNumbers.erase(currFrameNumber);
Chavi Weingartend48797b2023-08-04 13:11:39 +0000307 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500308 flushShadowQueue();
309 }
310 } else {
chaviw768bfa02021-11-01 09:50:57 -0500311 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviwd7deef72021-10-06 11:53:40 -0500312 }
313 } else {
314 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
315 "empty.");
316 }
chaviwd7deef72021-10-06 11:53:40 -0500317 decStrong((void*)transactionCommittedCallbackThunk);
318 }
319}
320
Robert Carr78c25dd2019-08-15 14:10:33 -0700321static void transactionCallbackThunk(void* context, nsecs_t latchTime,
322 const sp<Fence>& presentFence,
323 const std::vector<SurfaceControlStats>& stats) {
324 if (context == nullptr) {
325 return;
326 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800327 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700328 bq->transactionCallback(latchTime, presentFence, stats);
329}
330
331void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
332 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700333 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000334 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600335 BBQ_TRACE();
chaviw71c2cc42020-10-23 16:42:02 -0700336 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700337
chaviw42026162021-04-16 15:46:12 -0500338 if (!mSurfaceControlsWithPendingCallback.empty()) {
339 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
340 mSurfaceControlsWithPendingCallback.pop();
chaviwd7deef72021-10-06 11:53:40 -0500341 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
342 if (statsOptional) {
343 SurfaceControlStats stat = *statsOptional;
Vishnu Nair71fcf912022-10-18 09:14:20 -0700344 if (stat.transformHint) {
345 mTransformHint = *stat.transformHint;
346 mBufferItemConsumer->setTransformHint(mTransformHint);
347 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
348 }
Vishnu Nairde66dc72021-06-17 17:54:41 -0700349 // Update frametime stamps if the frame was latched and presented, indicated by a
350 // valid latch time.
351 if (stat.latchTime > 0) {
352 mBufferItemConsumer
353 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
354 stat.frameEventStats.refreshStartTime,
355 stat.frameEventStats.gpuCompositionDoneFence,
356 stat.presentFence, stat.previousReleaseFence,
357 stat.frameEventStats.compositorTiming,
358 stat.latchTime,
359 stat.frameEventStats.dequeueReadyTime);
360 }
Robert Carr405e2f62021-12-31 16:59:34 -0800361 auto currFrameNumber = stat.frameEventStats.frameNumber;
362 std::vector<ReleaseCallbackId> staleReleases;
363 for (const auto& [key, value]: mSubmitted) {
364 if (currFrameNumber > key.framenumber) {
365 staleReleases.push_back(key);
366 }
367 }
368 for (const auto& staleRelease : staleReleases) {
Robert Carr405e2f62021-12-31 16:59:34 -0800369 releaseBufferCallbackLocked(staleRelease,
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700370 stat.previousReleaseFence
371 ? stat.previousReleaseFence
372 : Fence::NO_FENCE,
373 stat.currentMaxAcquiredBufferCount,
374 true /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800375 }
chaviwd7deef72021-10-06 11:53:40 -0500376 } else {
chaviw768bfa02021-11-01 09:50:57 -0500377 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500378 }
379 } else {
380 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
381 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800382 }
chaviw71c2cc42020-10-23 16:42:02 -0700383
chaviw71c2cc42020-10-23 16:42:02 -0700384 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700385 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700386}
387
Vishnu Nair1506b182021-02-22 14:35:15 -0800388// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
389// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
390// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
391// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700392static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
chaviw69058fb2021-09-27 09:37:30 -0500393 const sp<Fence>& releaseFence,
394 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800395 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800396 if (blastBufferQueue) {
chaviw69058fb2021-09-27 09:37:30 -0500397 blastBufferQueue->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700398 } else {
399 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800400 }
401}
402
chaviwd7deef72021-10-06 11:53:40 -0500403void BLASTBufferQueue::flushShadowQueue() {
404 BQA_LOGV("flushShadowQueue");
405 int numFramesToFlush = mNumFrameAvailable;
406 while (numFramesToFlush > 0) {
407 acquireNextBufferLocked(std::nullopt);
408 numFramesToFlush--;
409 }
410}
411
chaviw69058fb2021-09-27 09:37:30 -0500412void BLASTBufferQueue::releaseBufferCallback(
413 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
414 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000415 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600416 BBQ_TRACE();
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700417 releaseBufferCallbackLocked(id, releaseFence, currentMaxAcquiredBufferCount,
418 false /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800419}
420
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700421void BLASTBufferQueue::releaseBufferCallbackLocked(
422 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
423 std::optional<uint32_t> currentMaxAcquiredBufferCount, bool fakeRelease) {
Robert Carr405e2f62021-12-31 16:59:34 -0800424 ATRACE_CALL();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700425 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800426
Ady Abraham899dcdb2021-06-15 16:56:21 -0700427 // Calculate how many buffers we need to hold before we release them back
428 // to the buffer queue. This will prevent higher latency when we are running
429 // on a lower refresh rate than the max supported. We only do that for EGL
430 // clients as others don't care about latency
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000431 const auto it = mSubmitted.find(id);
432 const bool isEGL = it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
Ady Abraham899dcdb2021-06-15 16:56:21 -0700433
chaviw69058fb2021-09-27 09:37:30 -0500434 if (currentMaxAcquiredBufferCount) {
435 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
436 }
437
liulijunf90df632022-11-14 14:24:48 +0800438 const uint32_t numPendingBuffersToHold =
439 isEGL ? std::max(0, mMaxAcquiredBuffers - (int32_t)mCurrentMaxAcquiredBufferCount) : 0;
Robert Carr405e2f62021-12-31 16:59:34 -0800440
441 auto rb = ReleasedBuffer{id, releaseFence};
442 if (std::find(mPendingRelease.begin(), mPendingRelease.end(), rb) == mPendingRelease.end()) {
443 mPendingRelease.emplace_back(rb);
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700444 if (fakeRelease) {
445 BQA_LOGE("Faking releaseBufferCallback from transactionCompleteCallback %" PRIu64,
446 id.framenumber);
447 BBQ_TRACE("FakeReleaseCallback");
448 }
Robert Carr405e2f62021-12-31 16:59:34 -0800449 }
Ady Abraham899dcdb2021-06-15 16:56:21 -0700450
451 // Release all buffers that are beyond the ones that we need to hold
452 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500453 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700454 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500455 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwc1cf4022022-06-03 13:32:33 -0500456 // Don't process the transactions here if mSyncedFrameNumbers is not empty. That means
457 // are still transactions that have sync buffers in them that have not been applied or
458 // dropped. Instead, let onFrameAvailable handle processing them since it will merge with
459 // the syncTransaction.
460 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500461 acquireNextBufferLocked(std::nullopt);
462 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800463 }
464
Ady Abraham899dcdb2021-06-15 16:56:21 -0700465 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700466 ATRACE_INT(mQueuedBufferTrace.c_str(),
467 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800468 mCallbackCV.notify_all();
469}
470
chaviw0acd33a2021-11-02 11:55:37 -0500471void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
472 const sp<Fence>& releaseFence) {
473 auto it = mSubmitted.find(callbackId);
474 if (it == mSubmitted.end()) {
475 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
476 callbackId.to_string().c_str());
477 return;
478 }
479 mNumAcquired--;
chaviw57ae4b22022-02-03 16:51:39 -0600480 BBQ_TRACE("frame=%" PRIu64, callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500481 BQA_LOGV("released %s", callbackId.to_string().c_str());
482 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
483 mSubmitted.erase(it);
chaviwc1cf4022022-06-03 13:32:33 -0500484 // Remove the frame number from mSyncedFrameNumbers since we can get a release callback
485 // without getting a transaction committed if the buffer was dropped.
486 mSyncedFrameNumbers.erase(callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500487}
488
Chavi Weingarten70670e62023-02-22 17:36:40 +0000489static ui::Size getBufferSize(const BufferItem& item) {
490 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
491 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
492
493 // Take the buffer's orientation into account
494 if (item.mTransform & ui::Transform::ROT_90) {
495 std::swap(bufWidth, bufHeight);
496 }
497 return ui::Size(bufWidth, bufHeight);
498}
499
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000500status_t BLASTBufferQueue::acquireNextBufferLocked(
chaviwd7deef72021-10-06 11:53:40 -0500501 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800502 // Check if we have frames available and we have not acquired the maximum number of buffers.
503 // Even with this check, the consumer can fail to acquire an additional buffer if the consumer
504 // has already acquired (mMaxAcquiredBuffers + 1) and the new buffer is not droppable. In this
505 // case mBufferItemConsumer->acquireBuffer will return with NO_BUFFER_AVAILABLE.
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000506 if (mNumFrameAvailable == 0) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800507 BQA_LOGV("Can't acquire next buffer. No available frames");
508 return BufferQueue::NO_BUFFER_AVAILABLE;
509 }
510
511 if (mNumAcquired >= (mMaxAcquiredBuffers + 2)) {
512 BQA_LOGV("Can't acquire next buffer. Already acquired max frames %d max:%d + 2",
513 mNumAcquired, mMaxAcquiredBuffers);
514 return BufferQueue::NO_BUFFER_AVAILABLE;
Valerie Haud3b90d22019-11-06 09:37:31 -0800515 }
516
Valerie Haua32c5522019-12-09 10:11:08 -0800517 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700518 BQA_LOGE("ERROR : surface control is null");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000519 return NAME_NOT_FOUND;
Valerie Haud3b90d22019-11-06 09:37:31 -0800520 }
521
Robert Carr78c25dd2019-08-15 14:10:33 -0700522 SurfaceComposerClient::Transaction localTransaction;
523 bool applyTransaction = true;
524 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500525 if (transaction) {
526 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700527 applyTransaction = false;
528 }
529
Valerie Haua32c5522019-12-09 10:11:08 -0800530 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800531
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800532 status_t status =
533 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800534 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
535 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000536 return status;
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800537 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700538 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000539 return status;
Robert Carr78c25dd2019-08-15 14:10:33 -0700540 }
chaviw57ae4b22022-02-03 16:51:39 -0600541
Valerie Haua32c5522019-12-09 10:11:08 -0800542 auto buffer = bufferItem.mGraphicBuffer;
543 mNumFrameAvailable--;
chaviw57ae4b22022-02-03 16:51:39 -0600544 BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800545
546 if (buffer == nullptr) {
547 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700548 BQA_LOGE("Buffer was empty");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000549 return BAD_VALUE;
Valerie Haua32c5522019-12-09 10:11:08 -0800550 }
551
Vishnu Nair670b3f72020-09-29 17:52:18 -0700552 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700553 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800554 "buffer{size=%dx%d transform=%d}",
555 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
556 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
557 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000558 return acquireNextBufferLocked(transaction);
Vishnu Nair670b3f72020-09-29 17:52:18 -0700559 }
560
Valerie Haua32c5522019-12-09 10:11:08 -0800561 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700562 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
563 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
564 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700565
Valerie Hau871d6352020-01-29 08:44:02 -0800566 bool needsDisconnect = false;
567 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
568
569 // if producer disconnected before, notify SurfaceFlinger
570 if (needsDisconnect) {
571 t->notifyProducerDisconnect(mSurfaceControl);
572 }
573
Robert Carr78c25dd2019-08-15 14:10:33 -0700574 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
575 incStrong((void*)transactionCallbackThunk);
576
Chavi Weingarten70670e62023-02-22 17:36:40 +0000577 // Only update mSize for destination bounds if the incoming buffer matches the requested size.
578 // Otherwise, it could cause stretching since the destination bounds will update before the
579 // buffer with the new size is acquired.
Vishnu Nair5b5f6932023-04-12 16:28:19 -0700580 if (mRequestedSize == getBufferSize(bufferItem) ||
581 bufferItem.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Chavi Weingarten70670e62023-02-22 17:36:40 +0000582 mSize = mRequestedSize;
583 }
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700584 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000585 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
586 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700587 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800588
Vishnu Nair1506b182021-02-22 14:35:15 -0800589 auto releaseBufferCallback =
590 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
chaviw69058fb2021-09-27 09:37:30 -0500591 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
chaviwba4320c2021-09-15 15:20:53 -0500592 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
liulijuneb489f62022-10-17 22:02:14 +0800593 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, mProducerId,
594 releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500595 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
596 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
597 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700598 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviwf2dace72021-11-17 17:36:50 -0600599
chaviw42026162021-04-16 15:46:12 -0500600 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700601
Vishnu Naird2aaab12022-02-10 14:49:09 -0800602 if (mUpdateDestinationFrame) {
603 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
604 } else {
605 const bool ignoreDestinationFrame =
606 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
607 t->setFlags(mSurfaceControl,
608 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
609 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700610 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700611 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800612 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800613 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800614 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800615 if (!bufferItem.mIsAutoTimestamp) {
616 t->setDesiredPresentTime(bufferItem.mTimestamp);
617 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700618
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800619 // Drop stale frame timeline infos
620 while (!mPendingFrameTimelines.empty() &&
621 mPendingFrameTimelines.front().first < bufferItem.mFrameNumber) {
622 ATRACE_FORMAT_INSTANT("dropping stale frameNumber: %" PRIu64 " vsyncId: %" PRId64,
623 mPendingFrameTimelines.front().first,
624 mPendingFrameTimelines.front().second.vsyncId);
625 mPendingFrameTimelines.pop();
626 }
627
628 if (!mPendingFrameTimelines.empty() &&
629 mPendingFrameTimelines.front().first == bufferItem.mFrameNumber) {
630 ATRACE_FORMAT_INSTANT("Transaction::setFrameTimelineInfo frameNumber: %" PRIu64
631 " vsyncId: %" PRId64,
632 bufferItem.mFrameNumber,
633 mPendingFrameTimelines.front().second.vsyncId);
634 t->setFrameTimelineInfo(mPendingFrameTimelines.front().second);
635 mPendingFrameTimelines.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100636 }
637
Vishnu Nairadf632b2021-01-07 14:05:08 -0800638 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000639 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800640 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
641 if (dequeueTime != mDequeueTimestamps.end()) {
642 Parcel p;
643 p.writeInt64(dequeueTime->second);
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800644 t->setMetadata(mSurfaceControl, gui::METADATA_DEQUEUE_TIME, p);
Vishnu Nairadf632b2021-01-07 14:05:08 -0800645 mDequeueTimestamps.erase(dequeueTime);
646 }
647 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800648
chaviw6a195272021-09-03 16:14:25 -0500649 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700650 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800651 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
652 t->setApplyToken(mApplyToken).apply(false, true);
653 mAppliedLastTransaction = true;
654 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
655 } else {
656 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
657 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700658 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700659
chaviwd7deef72021-10-06 11:53:40 -0500660 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800661 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700662 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500663 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800664 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700665 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700666 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000667 return OK;
Robert Carr78c25dd2019-08-15 14:10:33 -0700668}
669
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800670Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
671 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800672 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800673 }
674 return item.mCrop;
675}
676
chaviwd7deef72021-10-06 11:53:40 -0500677void BLASTBufferQueue::acquireAndReleaseBuffer() {
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000678 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500679 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500680 status_t status =
681 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
682 if (status != OK) {
683 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
684 statusToString(status).c_str());
685 return;
686 }
chaviwd7deef72021-10-06 11:53:40 -0500687 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500688 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500689}
690
Vishnu Nairaef1de92020-10-22 12:15:53 -0700691void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000692 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
693 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
chaviwc1cf4022022-06-03 13:32:33 -0500694
Tianhao Yao4861b102022-02-03 20:18:35 +0000695 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000696 UNIQUE_LOCK_WITH_ASSERTION(mMutex);
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000697 BBQ_TRACE();
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000698 bool waitForTransactionCallback = !mSyncedFrameNumbers.empty();
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800699
Tianhao Yao4861b102022-02-03 20:18:35 +0000700 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
701 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800702
Tianhao Yao4861b102022-02-03 20:18:35 +0000703 if (syncTransactionSet) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000704 // If we are going to re-use the same mSyncTransaction, release the buffer that may
705 // already be set in the Transaction. This is to allow us a free slot early to continue
706 // processing a new buffer.
707 if (!mAcquireSingleBuffer) {
708 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
709 if (bufferData) {
710 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
711 bufferData->frameNumber);
712 releaseBuffer(bufferData->generateReleaseCallbackId(),
713 bufferData->acquireFence);
Tianhao Yao4861b102022-02-03 20:18:35 +0000714 }
715 }
chaviw0acd33a2021-11-02 11:55:37 -0500716
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000717 if (waitForTransactionCallback) {
718 // We are waiting on a previous sync's transaction callback so allow another sync
719 // transaction to proceed.
720 //
721 // We need to first flush out the transactions that were in between the two syncs.
722 // We do this by merging them into mSyncTransaction so any buffer merging will get
723 // a release callback invoked.
724 while (mNumFrameAvailable > 0) {
725 // flush out the shadow queue
726 acquireAndReleaseBuffer();
727 }
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800728 } else {
729 // Make sure the frame available count is 0 before proceeding with a sync to ensure
730 // the correct frame is used for the sync. The only way mNumFrameAvailable would be
731 // greater than 0 is if we already ran out of buffers previously. This means we
732 // need to flush the buffers before proceeding with the sync.
733 while (mNumFrameAvailable > 0) {
734 BQA_LOGD("waiting until no queued buffers");
735 mCallbackCV.wait(_lock);
736 }
chaviwd7deef72021-10-06 11:53:40 -0500737 }
738 }
739
Tianhao Yao4861b102022-02-03 20:18:35 +0000740 // add to shadow queue
741 mNumFrameAvailable++;
chaviwc1cf4022022-06-03 13:32:33 -0500742 if (waitForTransactionCallback && mNumFrameAvailable >= 2) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000743 acquireAndReleaseBuffer();
744 }
745 ATRACE_INT(mQueuedBufferTrace.c_str(),
746 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
747
748 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
749 item.mFrameNumber, boolToString(syncTransactionSet));
750
751 if (syncTransactionSet) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800752 // Add to mSyncedFrameNumbers before waiting in case any buffers are released
753 // while waiting for a free buffer. The release and commit callback will try to
754 // acquire buffers if there are any available, but we don't want it to acquire
755 // in the case where a sync transaction wants the buffer.
756 mSyncedFrameNumbers.emplace(item.mFrameNumber);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000757 // If there's no available buffer and we're in a sync transaction, we need to wait
758 // instead of returning since we guarantee a buffer will be acquired for the sync.
759 while (acquireNextBufferLocked(mSyncTransaction) == BufferQueue::NO_BUFFER_AVAILABLE) {
760 BQA_LOGD("waiting for available buffer");
761 mCallbackCV.wait(_lock);
762 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000763
764 // Only need a commit callback when syncing to ensure the buffer that's synced has been
765 // sent to SF
766 incStrong((void*)transactionCommittedCallbackThunk);
767 mSyncTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,
768 static_cast<void*>(this));
Tianhao Yao4861b102022-02-03 20:18:35 +0000769 if (mAcquireSingleBuffer) {
770 prevCallback = mTransactionReadyCallback;
771 prevTransaction = mSyncTransaction;
772 mTransactionReadyCallback = nullptr;
773 mSyncTransaction = nullptr;
774 }
chaviwc1cf4022022-06-03 13:32:33 -0500775 } else if (!waitForTransactionCallback) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000776 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800777 }
778 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000779 if (prevCallback) {
780 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500781 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800782}
783
Vishnu Nairaef1de92020-10-22 12:15:53 -0700784void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
785 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
786 // Do nothing since we are not storing unacquired buffer items locally.
787}
788
Vishnu Nairadf632b2021-01-07 14:05:08 -0800789void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000790 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800791 mDequeueTimestamps[bufferId] = systemTime();
792};
793
794void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000795 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800796 mDequeueTimestamps.erase(bufferId);
797};
798
Chavi Weingartenc398c012023-04-12 17:26:02 +0000799bool BLASTBufferQueue::syncNextTransaction(
Tianhao Yao4861b102022-02-03 20:18:35 +0000800 std::function<void(SurfaceComposerClient::Transaction*)> callback,
801 bool acquireSingleBuffer) {
Chavi Weingartenc398c012023-04-12 17:26:02 +0000802 LOG_ALWAYS_FATAL_IF(!callback,
803 "BLASTBufferQueue: callback passed in to syncNextTransaction must not be "
804 "NULL");
chaviw3b4bdcf2022-03-17 09:27:03 -0500805
Chavi Weingartenc398c012023-04-12 17:26:02 +0000806 std::lock_guard _lock{mMutex};
807 BBQ_TRACE();
808 if (mTransactionReadyCallback) {
809 ALOGW("Attempting to overwrite transaction callback in syncNextTransaction");
810 return false;
Tianhao Yao4861b102022-02-03 20:18:35 +0000811 }
chaviw3b4bdcf2022-03-17 09:27:03 -0500812
Chavi Weingartenc398c012023-04-12 17:26:02 +0000813 mTransactionReadyCallback = callback;
814 mSyncTransaction = new SurfaceComposerClient::Transaction();
815 mAcquireSingleBuffer = acquireSingleBuffer;
816 return true;
Tianhao Yao4861b102022-02-03 20:18:35 +0000817}
818
819void BLASTBufferQueue::stopContinuousSyncTransaction() {
820 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
821 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
822 {
823 std::lock_guard _lock{mMutex};
Chavi Weingartenc398c012023-04-12 17:26:02 +0000824 if (mAcquireSingleBuffer || !mTransactionReadyCallback) {
825 ALOGW("Attempting to stop continuous sync when none are active");
826 return;
Tianhao Yao4861b102022-02-03 20:18:35 +0000827 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000828
829 prevCallback = mTransactionReadyCallback;
830 prevTransaction = mSyncTransaction;
831
Tianhao Yao4861b102022-02-03 20:18:35 +0000832 mTransactionReadyCallback = nullptr;
833 mSyncTransaction = nullptr;
834 mAcquireSingleBuffer = true;
835 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000836
Tianhao Yao4861b102022-02-03 20:18:35 +0000837 if (prevCallback) {
838 prevCallback(prevTransaction);
839 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700840}
841
Chavi Weingartenc398c012023-04-12 17:26:02 +0000842void BLASTBufferQueue::clearSyncTransaction() {
843 std::lock_guard _lock{mMutex};
844 if (!mAcquireSingleBuffer) {
845 ALOGW("Attempting to clear sync transaction when none are active");
846 return;
847 }
848
849 mTransactionReadyCallback = nullptr;
850 mSyncTransaction = nullptr;
851}
852
Vishnu Nairea0de002020-11-17 17:42:37 -0800853bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700854 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
855 // Only reject buffers if scaling mode is freeze.
856 return false;
857 }
858
Chavi Weingarten70670e62023-02-22 17:36:40 +0000859 ui::Size bufferSize = getBufferSize(item);
Vishnu Nairea0de002020-11-17 17:42:37 -0800860 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800861 return false;
862 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700863
Vishnu Nair670b3f72020-09-29 17:52:18 -0700864 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800865 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700866}
Vishnu Nairbf255772020-10-16 10:54:41 -0700867
Robert Carr05086b22020-10-13 18:22:51 -0700868class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700869private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700870 std::mutex mMutex;
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000871 sp<BLASTBufferQueue> mBbq GUARDED_BY(mMutex);
872 bool mDestroyed GUARDED_BY(mMutex) = false;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700873
Robert Carr05086b22020-10-13 18:22:51 -0700874public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700875 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
876 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
877 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700878
Robert Carr05086b22020-10-13 18:22:51 -0700879 void allocateBuffers() override {
880 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
881 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
882 auto gbp = getIGraphicBufferProducer();
883 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
884 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
885 gbp->allocateBuffers(reqWidth, reqHeight,
886 reqFormat, reqUsage);
887
888 }).detach();
889 }
Robert Carr9c006e02020-10-14 13:41:57 -0700890
Marin Shalamanovc5986772021-03-16 16:09:49 +0100891 status_t setFrameRate(float frameRate, int8_t compatibility,
892 int8_t changeFrameRateStrategy) override {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000893 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700894 if (mDestroyed) {
895 return DEAD_OBJECT;
896 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100897 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
898 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700899 return BAD_VALUE;
900 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100901 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700902 }
Robert Carr9b611b72020-10-19 12:00:23 -0700903
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800904 status_t setFrameTimelineInfo(uint64_t frameNumber,
905 const FrameTimelineInfo& frameTimelineInfo) override {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000906 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700907 if (mDestroyed) {
908 return DEAD_OBJECT;
909 }
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800910 return mBbq->setFrameTimelineInfo(frameNumber, frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700911 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700912
913 void destroy() override {
914 Surface::destroy();
915
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000916 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700917 mDestroyed = true;
918 mBbq = nullptr;
919 }
Robert Carr05086b22020-10-13 18:22:51 -0700920};
921
Robert Carr9c006e02020-10-14 13:41:57 -0700922// TODO: Can we coalesce this with frame updates? Need to confirm
923// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200924status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
925 bool shouldBeSeamless) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000926 std::lock_guard _lock{mMutex};
Robert Carr9c006e02020-10-14 13:41:57 -0700927 SurfaceComposerClient::Transaction t;
928
Marin Shalamanov46084422020-10-13 12:33:42 +0200929 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700930}
931
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800932status_t BLASTBufferQueue::setFrameTimelineInfo(uint64_t frameNumber,
933 const FrameTimelineInfo& frameTimelineInfo) {
934 ATRACE_FORMAT("%s(%s) frameNumber: %" PRIu64 " vsyncId: %" PRId64, __func__, mName.c_str(),
935 frameNumber, frameTimelineInfo.vsyncId);
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000936 std::lock_guard _lock{mMutex};
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800937 mPendingFrameTimelines.push({frameNumber, frameTimelineInfo});
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100938 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700939}
940
Hongguang Chen621ec582021-02-16 15:42:35 -0800941void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000942 std::lock_guard _lock{mMutex};
Hongguang Chen621ec582021-02-16 15:42:35 -0800943 SurfaceComposerClient::Transaction t;
944
945 t.setSidebandStream(mSurfaceControl, stream).apply();
946}
947
Vishnu Nair992496b2020-10-22 17:27:21 -0700948sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000949 std::lock_guard _lock{mMutex};
Vishnu Nair992496b2020-10-22 17:27:21 -0700950 sp<IBinder> scHandle = nullptr;
951 if (includeSurfaceControlHandle && mSurfaceControl) {
952 scHandle = mSurfaceControl->getHandle();
953 }
954 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700955}
956
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800957void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
958 uint64_t frameNumber) {
959 std::lock_guard _lock{mMutex};
960 if (mLastAcquiredFrameNumber >= frameNumber) {
961 // Apply the transaction since we have already acquired the desired frame.
962 t->apply();
963 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500964 mPendingTransactions.emplace_back(frameNumber, *t);
965 // Clear the transaction so it can't be applied elsewhere.
966 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800967 }
968}
969
chaviw6a195272021-09-03 16:14:25 -0500970void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
971 std::lock_guard _lock{mMutex};
972
973 SurfaceComposerClient::Transaction t;
974 mergePendingTransactions(&t, frameNumber);
Robert Carr79dc06a2022-02-22 15:28:59 -0800975 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
976 t.setApplyToken(mApplyToken).apply(false, true);
chaviw6a195272021-09-03 16:14:25 -0500977}
978
979void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
980 uint64_t frameNumber) {
981 auto mergeTransaction =
982 [&t, currentFrameNumber = frameNumber](
983 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
984 auto& [targetFrameNumber, transaction] = pendingTransaction;
985 if (currentFrameNumber < targetFrameNumber) {
986 return false;
987 }
988 t->merge(std::move(transaction));
989 return true;
990 };
991
992 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
993 mPendingTransactions.end(), mergeTransaction),
994 mPendingTransactions.end());
995}
996
chaviwd84085a2022-02-08 11:07:04 -0600997SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
998 uint64_t frameNumber) {
999 std::lock_guard _lock{mMutex};
1000 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
1001 mergePendingTransactions(t, frameNumber);
1002 return t;
1003}
1004
Vishnu Nair89496122020-12-14 17:14:53 -08001005// Maintains a single worker thread per process that services a list of runnables.
1006class AsyncWorker : public Singleton<AsyncWorker> {
1007private:
1008 std::thread mThread;
1009 bool mDone = false;
1010 std::deque<std::function<void()>> mRunnables;
1011 std::mutex mMutex;
1012 std::condition_variable mCv;
1013 void run() {
1014 std::unique_lock<std::mutex> lock(mMutex);
1015 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -08001016 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001017 std::deque<std::function<void()>> runnables = std::move(mRunnables);
1018 mRunnables.clear();
1019 lock.unlock();
1020 // Run outside the lock since the runnable might trigger another
1021 // post to the async worker.
1022 execute(runnables);
1023 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -08001024 }
Wonsik Kim567533e2021-05-04 19:31:29 -07001025 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -08001026 }
1027 }
1028
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001029 void execute(std::deque<std::function<void()>>& runnables) {
1030 while (!runnables.empty()) {
1031 std::function<void()> runnable = runnables.front();
1032 runnables.pop_front();
1033 runnable();
1034 }
1035 }
1036
Vishnu Nair89496122020-12-14 17:14:53 -08001037public:
1038 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
1039
1040 ~AsyncWorker() {
1041 mDone = true;
1042 mCv.notify_all();
1043 if (mThread.joinable()) {
1044 mThread.join();
1045 }
1046 }
1047
1048 void post(std::function<void()> runnable) {
1049 std::unique_lock<std::mutex> lock(mMutex);
1050 mRunnables.emplace_back(std::move(runnable));
1051 mCv.notify_one();
1052 }
1053};
1054ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
1055
1056// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
1057class AsyncProducerListener : public BnProducerListener {
1058private:
1059 const sp<IProducerListener> mListener;
1060
1061public:
1062 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
1063
1064 void onBufferReleased() override {
1065 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
1066 }
1067
1068 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
1069 AsyncWorker::getInstance().post(
1070 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
1071 }
1072};
1073
1074// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
1075// can be non-blocking when the producer is in the client process.
1076class BBQBufferQueueProducer : public BufferQueueProducer {
1077public:
Brian Lindahlc794b692023-01-31 15:42:47 -07001078 BBQBufferQueueProducer(const sp<BufferQueueCore>& core, wp<BLASTBufferQueue> bbq)
1079 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/),
1080 mBLASTBufferQueue(std::move(bbq)) {}
Vishnu Nair89496122020-12-14 17:14:53 -08001081
1082 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
1083 QueueBufferOutput* output) override {
1084 if (!listener) {
1085 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
1086 }
1087
1088 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
1089 producerControlledByApp, output);
1090 }
Vishnu Nair17dde612020-12-28 11:39:59 -08001091
Brian Lindahlc794b692023-01-31 15:42:47 -07001092 // We want to resize the frame history when changing the size of the buffer queue
1093 status_t setMaxDequeuedBufferCount(int maxDequeuedBufferCount) override {
1094 int maxBufferCount;
1095 status_t status = BufferQueueProducer::setMaxDequeuedBufferCount(maxDequeuedBufferCount,
1096 &maxBufferCount);
1097 // if we can't determine the max buffer count, then just skip growing the history size
1098 if (status == OK) {
1099 size_t newFrameHistorySize = maxBufferCount + 2; // +2 because triple buffer rendering
1100 // optimize away resizing the frame history unless it will grow
1101 if (newFrameHistorySize > FrameEventHistory::INITIAL_MAX_FRAME_HISTORY) {
1102 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1103 if (bbq != nullptr) {
1104 ALOGV("increasing frame history size to %zu", newFrameHistorySize);
1105 bbq->resizeFrameEventHistory(newFrameHistorySize);
1106 }
1107 }
1108 }
1109 return status;
1110 }
1111
Vishnu Nair17dde612020-12-28 11:39:59 -08001112 int query(int what, int* value) override {
1113 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
1114 *value = 1;
1115 return NO_ERROR;
1116 }
1117 return BufferQueueProducer::query(what, value);
1118 }
Brian Lindahlc794b692023-01-31 15:42:47 -07001119
1120private:
1121 const wp<BLASTBufferQueue> mBLASTBufferQueue;
Vishnu Nair89496122020-12-14 17:14:53 -08001122};
1123
1124// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
1125// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
1126// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
1127// we can deadlock.
1128void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
1129 sp<IGraphicBufferConsumer>* outConsumer) {
1130 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
1131 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
1132
1133 sp<BufferQueueCore> core(new BufferQueueCore());
1134 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
1135
Brian Lindahlc794b692023-01-31 15:42:47 -07001136 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core, this));
Vishnu Nair89496122020-12-14 17:14:53 -08001137 LOG_ALWAYS_FATAL_IF(producer == nullptr,
1138 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
1139
Vishnu Nair8b30dd12021-01-25 14:16:54 -08001140 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
1141 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -08001142 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
1143 "BLASTBufferQueue: failed to create BufferQueueConsumer");
1144
1145 *outProducer = producer;
1146 *outConsumer = consumer;
1147}
1148
Brian Lindahlc794b692023-01-31 15:42:47 -07001149void BLASTBufferQueue::resizeFrameEventHistory(size_t newSize) {
1150 // This can be null during creation of the buffer queue, but resizing won't do anything at that
1151 // point in time, so just ignore. This can go away once the class relationships and lifetimes of
1152 // objects are cleaned up with a major refactor of BufferQueue as a whole.
1153 if (mBufferItemConsumer != nullptr) {
1154 std::unique_lock _lock{mMutex};
1155 mBufferItemConsumer->resizeFrameEventHistory(newSize);
1156 }
1157}
1158
chaviw497e81c2021-02-04 17:09:47 -08001159PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
1160 PixelFormat convertedFormat = format;
1161 switch (format) {
1162 case PIXEL_FORMAT_TRANSPARENT:
1163 case PIXEL_FORMAT_TRANSLUCENT:
1164 convertedFormat = PIXEL_FORMAT_RGBA_8888;
1165 break;
1166 case PIXEL_FORMAT_OPAQUE:
1167 convertedFormat = PIXEL_FORMAT_RGBX_8888;
1168 break;
1169 }
1170 return convertedFormat;
1171}
1172
Robert Carr82d07c92021-05-10 11:36:43 -07001173uint32_t BLASTBufferQueue::getLastTransformHint() const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001174 std::lock_guard _lock{mMutex};
Robert Carr82d07c92021-05-10 11:36:43 -07001175 if (mSurfaceControl != nullptr) {
1176 return mSurfaceControl->getTransformHint();
1177 } else {
1178 return 0;
1179 }
1180}
1181
chaviw0b020f82021-08-20 12:00:47 -05001182uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001183 std::lock_guard _lock{mMutex};
chaviw0b020f82021-08-20 12:00:47 -05001184 return mLastAcquiredFrameNumber;
1185}
1186
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001187bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001188 std::lock_guard _lock{mMutex};
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001189 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1190}
1191
Patrick Williamsf1e5df12022-10-17 21:37:42 +00001192void BLASTBufferQueue::setTransactionHangCallback(
1193 std::function<void(const std::string&)> callback) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001194 std::lock_guard _lock{mMutex};
Robert Carr4c1b6462021-12-21 10:30:50 -08001195 mTransactionHangCallback = callback;
1196}
1197
Robert Carr78c25dd2019-08-15 14:10:33 -07001198} // namespace android