blob: fd42b33e49105357f33cde7e01b5950c94ec36c1 [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.
306 // We also want to check if mSyncTransaction is null because it's possible another
chaviwd7deef72021-10-06 11:53:40 -0500307 // sync request came in while waiting, but it hasn't started processing yet. In that
308 // case, we don't actually want to flush the frames in between since they will get
309 // processed and merged with the sync transaction and released earlier than if they
310 // were sent to SF
chaviwc1cf4022022-06-03 13:32:33 -0500311 mSyncedFrameNumbers.erase(currFrameNumber);
312 if (mSyncedFrameNumbers.empty() && mSyncTransaction == nullptr) {
chaviwd7deef72021-10-06 11:53:40 -0500313 flushShadowQueue();
314 }
315 } else {
chaviw768bfa02021-11-01 09:50:57 -0500316 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviwd7deef72021-10-06 11:53:40 -0500317 }
318 } else {
319 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
320 "empty.");
321 }
chaviwd7deef72021-10-06 11:53:40 -0500322 decStrong((void*)transactionCommittedCallbackThunk);
323 }
324}
325
Robert Carr78c25dd2019-08-15 14:10:33 -0700326static void transactionCallbackThunk(void* context, nsecs_t latchTime,
327 const sp<Fence>& presentFence,
328 const std::vector<SurfaceControlStats>& stats) {
329 if (context == nullptr) {
330 return;
331 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800332 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700333 bq->transactionCallback(latchTime, presentFence, stats);
334}
335
336void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
337 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700338 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000339 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600340 BBQ_TRACE();
chaviw71c2cc42020-10-23 16:42:02 -0700341 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700342
chaviw42026162021-04-16 15:46:12 -0500343 if (!mSurfaceControlsWithPendingCallback.empty()) {
344 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
345 mSurfaceControlsWithPendingCallback.pop();
chaviwd7deef72021-10-06 11:53:40 -0500346 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
347 if (statsOptional) {
348 SurfaceControlStats stat = *statsOptional;
Vishnu Nair71fcf912022-10-18 09:14:20 -0700349 if (stat.transformHint) {
350 mTransformHint = *stat.transformHint;
351 mBufferItemConsumer->setTransformHint(mTransformHint);
352 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
353 }
Vishnu Nairde66dc72021-06-17 17:54:41 -0700354 // Update frametime stamps if the frame was latched and presented, indicated by a
355 // valid latch time.
356 if (stat.latchTime > 0) {
357 mBufferItemConsumer
358 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
359 stat.frameEventStats.refreshStartTime,
360 stat.frameEventStats.gpuCompositionDoneFence,
361 stat.presentFence, stat.previousReleaseFence,
362 stat.frameEventStats.compositorTiming,
363 stat.latchTime,
364 stat.frameEventStats.dequeueReadyTime);
365 }
Robert Carr405e2f62021-12-31 16:59:34 -0800366 auto currFrameNumber = stat.frameEventStats.frameNumber;
367 std::vector<ReleaseCallbackId> staleReleases;
368 for (const auto& [key, value]: mSubmitted) {
369 if (currFrameNumber > key.framenumber) {
370 staleReleases.push_back(key);
371 }
372 }
373 for (const auto& staleRelease : staleReleases) {
Robert Carr405e2f62021-12-31 16:59:34 -0800374 releaseBufferCallbackLocked(staleRelease,
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700375 stat.previousReleaseFence
376 ? stat.previousReleaseFence
377 : Fence::NO_FENCE,
378 stat.currentMaxAcquiredBufferCount,
379 true /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800380 }
chaviwd7deef72021-10-06 11:53:40 -0500381 } else {
chaviw768bfa02021-11-01 09:50:57 -0500382 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500383 }
384 } else {
385 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
386 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800387 }
chaviw71c2cc42020-10-23 16:42:02 -0700388
chaviw71c2cc42020-10-23 16:42:02 -0700389 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700390 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700391}
392
Vishnu Nair1506b182021-02-22 14:35:15 -0800393// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
394// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
395// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
396// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700397static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
chaviw69058fb2021-09-27 09:37:30 -0500398 const sp<Fence>& releaseFence,
399 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800400 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800401 if (blastBufferQueue) {
chaviw69058fb2021-09-27 09:37:30 -0500402 blastBufferQueue->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700403 } else {
404 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800405 }
406}
407
chaviwd7deef72021-10-06 11:53:40 -0500408void BLASTBufferQueue::flushShadowQueue() {
409 BQA_LOGV("flushShadowQueue");
410 int numFramesToFlush = mNumFrameAvailable;
411 while (numFramesToFlush > 0) {
412 acquireNextBufferLocked(std::nullopt);
413 numFramesToFlush--;
414 }
415}
416
chaviw69058fb2021-09-27 09:37:30 -0500417void BLASTBufferQueue::releaseBufferCallback(
418 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
419 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000420 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600421 BBQ_TRACE();
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700422 releaseBufferCallbackLocked(id, releaseFence, currentMaxAcquiredBufferCount,
423 false /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800424}
425
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700426void BLASTBufferQueue::releaseBufferCallbackLocked(
427 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
428 std::optional<uint32_t> currentMaxAcquiredBufferCount, bool fakeRelease) {
Robert Carr405e2f62021-12-31 16:59:34 -0800429 ATRACE_CALL();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700430 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800431
Ady Abraham899dcdb2021-06-15 16:56:21 -0700432 // Calculate how many buffers we need to hold before we release them back
433 // to the buffer queue. This will prevent higher latency when we are running
434 // on a lower refresh rate than the max supported. We only do that for EGL
435 // clients as others don't care about latency
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000436 const auto it = mSubmitted.find(id);
437 const bool isEGL = it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
Ady Abraham899dcdb2021-06-15 16:56:21 -0700438
chaviw69058fb2021-09-27 09:37:30 -0500439 if (currentMaxAcquiredBufferCount) {
440 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
441 }
442
liulijunf90df632022-11-14 14:24:48 +0800443 const uint32_t numPendingBuffersToHold =
444 isEGL ? std::max(0, mMaxAcquiredBuffers - (int32_t)mCurrentMaxAcquiredBufferCount) : 0;
Robert Carr405e2f62021-12-31 16:59:34 -0800445
446 auto rb = ReleasedBuffer{id, releaseFence};
447 if (std::find(mPendingRelease.begin(), mPendingRelease.end(), rb) == mPendingRelease.end()) {
448 mPendingRelease.emplace_back(rb);
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700449 if (fakeRelease) {
450 BQA_LOGE("Faking releaseBufferCallback from transactionCompleteCallback %" PRIu64,
451 id.framenumber);
452 BBQ_TRACE("FakeReleaseCallback");
453 }
Robert Carr405e2f62021-12-31 16:59:34 -0800454 }
Ady Abraham899dcdb2021-06-15 16:56:21 -0700455
456 // Release all buffers that are beyond the ones that we need to hold
457 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500458 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700459 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500460 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwc1cf4022022-06-03 13:32:33 -0500461 // Don't process the transactions here if mSyncedFrameNumbers is not empty. That means
462 // are still transactions that have sync buffers in them that have not been applied or
463 // dropped. Instead, let onFrameAvailable handle processing them since it will merge with
464 // the syncTransaction.
465 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500466 acquireNextBufferLocked(std::nullopt);
467 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800468 }
469
Ady Abraham899dcdb2021-06-15 16:56:21 -0700470 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700471 ATRACE_INT(mQueuedBufferTrace.c_str(),
472 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800473 mCallbackCV.notify_all();
474}
475
chaviw0acd33a2021-11-02 11:55:37 -0500476void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
477 const sp<Fence>& releaseFence) {
478 auto it = mSubmitted.find(callbackId);
479 if (it == mSubmitted.end()) {
480 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
481 callbackId.to_string().c_str());
482 return;
483 }
484 mNumAcquired--;
chaviw57ae4b22022-02-03 16:51:39 -0600485 BBQ_TRACE("frame=%" PRIu64, callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500486 BQA_LOGV("released %s", callbackId.to_string().c_str());
487 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
488 mSubmitted.erase(it);
chaviwc1cf4022022-06-03 13:32:33 -0500489 // Remove the frame number from mSyncedFrameNumbers since we can get a release callback
490 // without getting a transaction committed if the buffer was dropped.
491 mSyncedFrameNumbers.erase(callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500492}
493
Chavi Weingarten70670e62023-02-22 17:36:40 +0000494static ui::Size getBufferSize(const BufferItem& item) {
495 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
496 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
497
498 // Take the buffer's orientation into account
499 if (item.mTransform & ui::Transform::ROT_90) {
500 std::swap(bufWidth, bufHeight);
501 }
502 return ui::Size(bufWidth, bufHeight);
503}
504
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000505status_t BLASTBufferQueue::acquireNextBufferLocked(
chaviwd7deef72021-10-06 11:53:40 -0500506 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800507 // Check if we have frames available and we have not acquired the maximum number of buffers.
508 // Even with this check, the consumer can fail to acquire an additional buffer if the consumer
509 // has already acquired (mMaxAcquiredBuffers + 1) and the new buffer is not droppable. In this
510 // case mBufferItemConsumer->acquireBuffer will return with NO_BUFFER_AVAILABLE.
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000511 if (mNumFrameAvailable == 0) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800512 BQA_LOGV("Can't acquire next buffer. No available frames");
513 return BufferQueue::NO_BUFFER_AVAILABLE;
514 }
515
516 if (mNumAcquired >= (mMaxAcquiredBuffers + 2)) {
517 BQA_LOGV("Can't acquire next buffer. Already acquired max frames %d max:%d + 2",
518 mNumAcquired, mMaxAcquiredBuffers);
519 return BufferQueue::NO_BUFFER_AVAILABLE;
Valerie Haud3b90d22019-11-06 09:37:31 -0800520 }
521
Valerie Haua32c5522019-12-09 10:11:08 -0800522 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700523 BQA_LOGE("ERROR : surface control is null");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000524 return NAME_NOT_FOUND;
Valerie Haud3b90d22019-11-06 09:37:31 -0800525 }
526
Robert Carr78c25dd2019-08-15 14:10:33 -0700527 SurfaceComposerClient::Transaction localTransaction;
528 bool applyTransaction = true;
529 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500530 if (transaction) {
531 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700532 applyTransaction = false;
533 }
534
Valerie Haua32c5522019-12-09 10:11:08 -0800535 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800536
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800537 status_t status =
538 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800539 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
540 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000541 return status;
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800542 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700543 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000544 return status;
Robert Carr78c25dd2019-08-15 14:10:33 -0700545 }
chaviw57ae4b22022-02-03 16:51:39 -0600546
Valerie Haua32c5522019-12-09 10:11:08 -0800547 auto buffer = bufferItem.mGraphicBuffer;
548 mNumFrameAvailable--;
chaviw57ae4b22022-02-03 16:51:39 -0600549 BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800550
551 if (buffer == nullptr) {
552 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700553 BQA_LOGE("Buffer was empty");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000554 return BAD_VALUE;
Valerie Haua32c5522019-12-09 10:11:08 -0800555 }
556
Vishnu Nair670b3f72020-09-29 17:52:18 -0700557 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700558 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800559 "buffer{size=%dx%d transform=%d}",
560 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
561 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
562 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000563 return acquireNextBufferLocked(transaction);
Vishnu Nair670b3f72020-09-29 17:52:18 -0700564 }
565
Valerie Haua32c5522019-12-09 10:11:08 -0800566 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700567 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
568 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
569 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700570
Valerie Hau871d6352020-01-29 08:44:02 -0800571 bool needsDisconnect = false;
572 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
573
574 // if producer disconnected before, notify SurfaceFlinger
575 if (needsDisconnect) {
576 t->notifyProducerDisconnect(mSurfaceControl);
577 }
578
Robert Carr78c25dd2019-08-15 14:10:33 -0700579 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
580 incStrong((void*)transactionCallbackThunk);
581
Chavi Weingarten70670e62023-02-22 17:36:40 +0000582 // Only update mSize for destination bounds if the incoming buffer matches the requested size.
583 // Otherwise, it could cause stretching since the destination bounds will update before the
584 // buffer with the new size is acquired.
Vishnu Nair5b5f6932023-04-12 16:28:19 -0700585 if (mRequestedSize == getBufferSize(bufferItem) ||
586 bufferItem.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Chavi Weingarten70670e62023-02-22 17:36:40 +0000587 mSize = mRequestedSize;
588 }
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700589 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000590 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
591 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700592 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800593
Vishnu Nair1506b182021-02-22 14:35:15 -0800594 auto releaseBufferCallback =
595 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
chaviw69058fb2021-09-27 09:37:30 -0500596 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
chaviwba4320c2021-09-15 15:20:53 -0500597 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
liulijuneb489f62022-10-17 22:02:14 +0800598 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, mProducerId,
599 releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500600 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
601 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
602 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700603 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviwf2dace72021-11-17 17:36:50 -0600604
chaviw42026162021-04-16 15:46:12 -0500605 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700606
Vishnu Naird2aaab12022-02-10 14:49:09 -0800607 if (mUpdateDestinationFrame) {
608 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
609 } else {
610 const bool ignoreDestinationFrame =
611 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
612 t->setFlags(mSurfaceControl,
613 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
614 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700615 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700616 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800617 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800618 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800619 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800620 if (!bufferItem.mIsAutoTimestamp) {
621 t->setDesiredPresentTime(bufferItem.mTimestamp);
622 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700623
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800624 // Drop stale frame timeline infos
625 while (!mPendingFrameTimelines.empty() &&
626 mPendingFrameTimelines.front().first < bufferItem.mFrameNumber) {
627 ATRACE_FORMAT_INSTANT("dropping stale frameNumber: %" PRIu64 " vsyncId: %" PRId64,
628 mPendingFrameTimelines.front().first,
629 mPendingFrameTimelines.front().second.vsyncId);
630 mPendingFrameTimelines.pop();
631 }
632
633 if (!mPendingFrameTimelines.empty() &&
634 mPendingFrameTimelines.front().first == bufferItem.mFrameNumber) {
635 ATRACE_FORMAT_INSTANT("Transaction::setFrameTimelineInfo frameNumber: %" PRIu64
636 " vsyncId: %" PRId64,
637 bufferItem.mFrameNumber,
638 mPendingFrameTimelines.front().second.vsyncId);
639 t->setFrameTimelineInfo(mPendingFrameTimelines.front().second);
640 mPendingFrameTimelines.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100641 }
642
Vishnu Nairadf632b2021-01-07 14:05:08 -0800643 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000644 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800645 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
646 if (dequeueTime != mDequeueTimestamps.end()) {
647 Parcel p;
648 p.writeInt64(dequeueTime->second);
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800649 t->setMetadata(mSurfaceControl, gui::METADATA_DEQUEUE_TIME, p);
Vishnu Nairadf632b2021-01-07 14:05:08 -0800650 mDequeueTimestamps.erase(dequeueTime);
651 }
652 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800653
chaviw6a195272021-09-03 16:14:25 -0500654 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700655 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800656 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
657 t->setApplyToken(mApplyToken).apply(false, true);
658 mAppliedLastTransaction = true;
659 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
660 } else {
661 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
662 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700663 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700664
chaviwd7deef72021-10-06 11:53:40 -0500665 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800666 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700667 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500668 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800669 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700670 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700671 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000672 return OK;
Robert Carr78c25dd2019-08-15 14:10:33 -0700673}
674
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800675Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
676 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800677 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800678 }
679 return item.mCrop;
680}
681
chaviwd7deef72021-10-06 11:53:40 -0500682void BLASTBufferQueue::acquireAndReleaseBuffer() {
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000683 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500684 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500685 status_t status =
686 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
687 if (status != OK) {
688 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
689 statusToString(status).c_str());
690 return;
691 }
chaviwd7deef72021-10-06 11:53:40 -0500692 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500693 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500694}
695
Vishnu Nairaef1de92020-10-22 12:15:53 -0700696void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000697 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
698 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
chaviwc1cf4022022-06-03 13:32:33 -0500699
Tianhao Yao4861b102022-02-03 20:18:35 +0000700 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000701 UNIQUE_LOCK_WITH_ASSERTION(mMutex);
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000702 BBQ_TRACE();
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000703 bool waitForTransactionCallback = !mSyncedFrameNumbers.empty();
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800704
Tianhao Yao4861b102022-02-03 20:18:35 +0000705 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
706 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800707
Tianhao Yao4861b102022-02-03 20:18:35 +0000708 if (syncTransactionSet) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000709 // If we are going to re-use the same mSyncTransaction, release the buffer that may
710 // already be set in the Transaction. This is to allow us a free slot early to continue
711 // processing a new buffer.
712 if (!mAcquireSingleBuffer) {
713 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
714 if (bufferData) {
715 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
716 bufferData->frameNumber);
717 releaseBuffer(bufferData->generateReleaseCallbackId(),
718 bufferData->acquireFence);
Tianhao Yao4861b102022-02-03 20:18:35 +0000719 }
720 }
chaviw0acd33a2021-11-02 11:55:37 -0500721
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000722 if (waitForTransactionCallback) {
723 // We are waiting on a previous sync's transaction callback so allow another sync
724 // transaction to proceed.
725 //
726 // We need to first flush out the transactions that were in between the two syncs.
727 // We do this by merging them into mSyncTransaction so any buffer merging will get
728 // a release callback invoked.
729 while (mNumFrameAvailable > 0) {
730 // flush out the shadow queue
731 acquireAndReleaseBuffer();
732 }
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800733 } else {
734 // Make sure the frame available count is 0 before proceeding with a sync to ensure
735 // the correct frame is used for the sync. The only way mNumFrameAvailable would be
736 // greater than 0 is if we already ran out of buffers previously. This means we
737 // need to flush the buffers before proceeding with the sync.
738 while (mNumFrameAvailable > 0) {
739 BQA_LOGD("waiting until no queued buffers");
740 mCallbackCV.wait(_lock);
741 }
chaviwd7deef72021-10-06 11:53:40 -0500742 }
743 }
744
Tianhao Yao4861b102022-02-03 20:18:35 +0000745 // add to shadow queue
746 mNumFrameAvailable++;
chaviwc1cf4022022-06-03 13:32:33 -0500747 if (waitForTransactionCallback && mNumFrameAvailable >= 2) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000748 acquireAndReleaseBuffer();
749 }
750 ATRACE_INT(mQueuedBufferTrace.c_str(),
751 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
752
753 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
754 item.mFrameNumber, boolToString(syncTransactionSet));
755
756 if (syncTransactionSet) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800757 // Add to mSyncedFrameNumbers before waiting in case any buffers are released
758 // while waiting for a free buffer. The release and commit callback will try to
759 // acquire buffers if there are any available, but we don't want it to acquire
760 // in the case where a sync transaction wants the buffer.
761 mSyncedFrameNumbers.emplace(item.mFrameNumber);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000762 // If there's no available buffer and we're in a sync transaction, we need to wait
763 // instead of returning since we guarantee a buffer will be acquired for the sync.
764 while (acquireNextBufferLocked(mSyncTransaction) == BufferQueue::NO_BUFFER_AVAILABLE) {
765 BQA_LOGD("waiting for available buffer");
766 mCallbackCV.wait(_lock);
767 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000768
769 // Only need a commit callback when syncing to ensure the buffer that's synced has been
770 // sent to SF
771 incStrong((void*)transactionCommittedCallbackThunk);
772 mSyncTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,
773 static_cast<void*>(this));
Tianhao Yao4861b102022-02-03 20:18:35 +0000774 if (mAcquireSingleBuffer) {
775 prevCallback = mTransactionReadyCallback;
776 prevTransaction = mSyncTransaction;
777 mTransactionReadyCallback = nullptr;
778 mSyncTransaction = nullptr;
779 }
chaviwc1cf4022022-06-03 13:32:33 -0500780 } else if (!waitForTransactionCallback) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000781 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800782 }
783 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000784 if (prevCallback) {
785 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500786 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800787}
788
Vishnu Nairaef1de92020-10-22 12:15:53 -0700789void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
790 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
791 // Do nothing since we are not storing unacquired buffer items locally.
792}
793
Vishnu Nairadf632b2021-01-07 14:05:08 -0800794void BLASTBufferQueue::onFrameDequeued(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[bufferId] = systemTime();
797};
798
799void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000800 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800801 mDequeueTimestamps.erase(bufferId);
802};
803
Tianhao Yao4861b102022-02-03 20:18:35 +0000804void BLASTBufferQueue::syncNextTransaction(
805 std::function<void(SurfaceComposerClient::Transaction*)> callback,
806 bool acquireSingleBuffer) {
chaviw3b4bdcf2022-03-17 09:27:03 -0500807 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
808 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
809
810 {
811 std::lock_guard _lock{mMutex};
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000812 BBQ_TRACE();
chaviw3b4bdcf2022-03-17 09:27:03 -0500813 // We're about to overwrite the previous call so we should invoke that callback
814 // immediately.
815 if (mTransactionReadyCallback) {
816 prevCallback = mTransactionReadyCallback;
817 prevTransaction = mSyncTransaction;
818 }
819
820 mTransactionReadyCallback = callback;
821 if (callback) {
822 mSyncTransaction = new SurfaceComposerClient::Transaction();
823 } else {
824 mSyncTransaction = nullptr;
825 }
826 mAcquireSingleBuffer = mTransactionReadyCallback ? acquireSingleBuffer : true;
Tianhao Yao4861b102022-02-03 20:18:35 +0000827 }
chaviw3b4bdcf2022-03-17 09:27:03 -0500828
829 if (prevCallback) {
830 prevCallback(prevTransaction);
831 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000832}
833
834void BLASTBufferQueue::stopContinuousSyncTransaction() {
835 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
836 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
837 {
838 std::lock_guard _lock{mMutex};
839 bool invokeCallback = mTransactionReadyCallback && !mAcquireSingleBuffer;
840 if (invokeCallback) {
841 prevCallback = mTransactionReadyCallback;
842 prevTransaction = mSyncTransaction;
843 }
844 mTransactionReadyCallback = nullptr;
845 mSyncTransaction = nullptr;
846 mAcquireSingleBuffer = true;
847 }
848 if (prevCallback) {
849 prevCallback(prevTransaction);
850 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700851}
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