blob: dd0a028865492e7e097571c85d9350deebd40ec4 [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>
Ady Abraham6cdd3fd2023-09-07 18:45:58 -070029#include <gui/Flags.h>
30#include <gui/FrameRateUtils.h>
Valerie Hau45e4b3b2019-12-03 10:49:17 -080031#include <gui/GLConsumer.h>
Vishnu Nair89496122020-12-14 17:14:53 -080032#include <gui/IProducerListener.h>
Robert Carr05086b22020-10-13 18:22:51 -070033#include <gui/Surface.h>
chaviw57ae4b22022-02-03 16:51:39 -060034#include <gui/TraceUtils.h>
Vishnu Nair89496122020-12-14 17:14:53 -080035#include <utils/Singleton.h>
Valerie Haua32c5522019-12-09 10:11:08 -080036#include <utils/Trace.h>
37
Ady Abraham0bde6b52021-05-18 13:57:02 -070038#include <private/gui/ComposerService.h>
Huihong Luo02186fb2022-02-23 14:21:54 -080039#include <private/gui/ComposerServiceAIDL.h>
Ady Abraham0bde6b52021-05-18 13:57:02 -070040
Chavi Weingartene0237bb2023-02-06 21:48:32 +000041#include <android-base/thread_annotations.h>
Robert Carr78c25dd2019-08-15 14:10:33 -070042#include <chrono>
43
Ady Abraham6cdd3fd2023-09-07 18:45:58 -070044#include <com_android_graphics_libgui_flags.h>
45
46using namespace com::android::graphics::libgui;
Robert Carr78c25dd2019-08-15 14:10:33 -070047using namespace std::chrono_literals;
48
Vishnu Nairdab94092020-09-29 16:09:04 -070049namespace {
chaviw3277faf2021-05-19 16:45:23 -050050inline const char* boolToString(bool b) {
Vishnu Nairdab94092020-09-29 16:09:04 -070051 return b ? "true" : "false";
52}
53} // namespace
54
Robert Carr78c25dd2019-08-15 14:10:33 -070055namespace android {
56
Vishnu Nairdab94092020-09-29 16:09:04 -070057// Macros to include adapter info in log messages
chaviwd7deef72021-10-06 11:53:40 -050058#define BQA_LOGD(x, ...) \
59 ALOGD("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070060#define BQA_LOGV(x, ...) \
61 ALOGV("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairc6f89ee2020-12-11 14:27:32 -080062// enable logs for a single layer
63//#define BQA_LOGV(x, ...) \
64// ALOGV_IF((strstr(mName.c_str(), "SurfaceView") != nullptr), "[%s](f:%u,a:%u) " x, \
65// mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070066#define BQA_LOGE(x, ...) \
67 ALOGE("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
68
chaviw57ae4b22022-02-03 16:51:39 -060069#define BBQ_TRACE(x, ...) \
70 ATRACE_FORMAT("%s - %s(f:%u,a:%u)" x, __FUNCTION__, mName.c_str(), mNumFrameAvailable, \
71 mNumAcquired, ##__VA_ARGS__)
72
Chavi Weingartene0237bb2023-02-06 21:48:32 +000073#define UNIQUE_LOCK_WITH_ASSERTION(mutex) \
74 std::unique_lock _lock{mutex}; \
75 base::ScopedLockAssertion assumeLocked(mutex);
76
Valerie Hau871d6352020-01-29 08:44:02 -080077void BLASTBufferItemConsumer::onDisconnect() {
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000078 Mutex::Autolock lock(mMutex);
79 mPreviouslyConnected = mCurrentlyConnected;
80 mCurrentlyConnected = false;
81 if (mPreviouslyConnected) {
82 mDisconnectEvents.push(mCurrentFrameNumber);
Valerie Hau871d6352020-01-29 08:44:02 -080083 }
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000084 mFrameEventHistory.onDisconnect();
Valerie Hau871d6352020-01-29 08:44:02 -080085}
86
87void BLASTBufferItemConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
88 FrameEventHistoryDelta* outDelta) {
Hongguang Chen621ec582021-02-16 15:42:35 -080089 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080090 if (newTimestamps) {
91 // BufferQueueProducer only adds a new timestamp on
92 // queueBuffer
93 mCurrentFrameNumber = newTimestamps->frameNumber;
94 mFrameEventHistory.addQueue(*newTimestamps);
95 }
96 if (outDelta) {
97 // frame event histories will be processed
98 // only after the producer connects and requests
99 // deltas for the first time. Forward this intent
100 // to SF-side to turn event processing back on
101 mPreviouslyConnected = mCurrentlyConnected;
102 mCurrentlyConnected = true;
103 mFrameEventHistory.getAndResetDelta(outDelta);
104 }
105}
106
107void BLASTBufferItemConsumer::updateFrameTimestamps(uint64_t frameNumber, nsecs_t refreshStartTime,
108 const sp<Fence>& glDoneFence,
109 const sp<Fence>& presentFence,
110 const sp<Fence>& prevReleaseFence,
111 CompositorTiming compositorTiming,
112 nsecs_t latchTime, nsecs_t dequeueReadyTime) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800113 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800114
115 // if the producer is not connected, don't bother updating,
116 // the next producer that connects won't access this frame event
117 if (!mCurrentlyConnected) return;
118 std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
119 std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
120 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
121
122 mFrameEventHistory.addLatch(frameNumber, latchTime);
123 mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
124 mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
125 mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
126 compositorTiming);
127}
128
129void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
130 bool disconnect = false;
Hongguang Chen621ec582021-02-16 15:42:35 -0800131 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800132 while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
133 disconnect = true;
134 mDisconnectEvents.pop();
135 }
136 if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
137}
138
Hongguang Chen621ec582021-02-16 15:42:35 -0800139void BLASTBufferItemConsumer::onSidebandStreamChanged() {
Ady Abrahamdbca1352021-12-15 11:58:56 -0800140 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
141 if (bbq != nullptr) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800142 sp<NativeHandle> stream = getSidebandStream();
Ady Abrahamdbca1352021-12-15 11:58:56 -0800143 bbq->setSidebandStream(stream);
Hongguang Chen621ec582021-02-16 15:42:35 -0800144 }
145}
146
Ady Abraham6cdd3fd2023-09-07 18:45:58 -0700147#if FLAG_BQ_SET_FRAME_RATE
148void BLASTBufferItemConsumer::onSetFrameRate(float frameRate, int8_t compatibility,
149 int8_t changeFrameRateStrategy) {
150 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
151 if (bbq != nullptr) {
152 bbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
153 }
154}
155#endif
156
Brian Lindahlc794b692023-01-31 15:42:47 -0700157void BLASTBufferItemConsumer::resizeFrameEventHistory(size_t newSize) {
158 Mutex::Autolock lock(mMutex);
159 mFrameEventHistory.resize(newSize);
160}
161
Vishnu Naird2aaab12022-02-10 14:49:09 -0800162BLASTBufferQueue::BLASTBufferQueue(const std::string& name, bool updateDestinationFrame)
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800163 : mSurfaceControl(nullptr),
164 mSize(1, 1),
Vishnu Nairea0de002020-11-17 17:42:37 -0800165 mRequestedSize(mSize),
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800166 mFormat(PIXEL_FORMAT_RGBA_8888),
Tianhao Yao4861b102022-02-03 20:18:35 +0000167 mTransactionReadyCallback(nullptr),
Vishnu Naird2aaab12022-02-10 14:49:09 -0800168 mSyncTransaction(nullptr),
169 mUpdateDestinationFrame(updateDestinationFrame) {
Vishnu Nair89496122020-12-14 17:14:53 -0800170 createBufferQueue(&mProducer, &mConsumer);
Valerie Hau0889c622020-02-19 15:04:47 -0800171 // since the adapter is in the client process, set dequeue timeout
172 // explicitly so that dequeueBuffer will block
173 mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
Valerie Hau65b8e872020-02-13 09:45:14 -0800174
Vishnu Nairdebd1cb2021-03-16 10:06:01 -0700175 // safe default, most producers are expected to override this
176 mProducer->setMaxDequeuedBufferCount(2);
Vishnu Nair1618c672021-02-05 13:08:26 -0800177 mBufferItemConsumer = new BLASTBufferItemConsumer(mConsumer,
178 GraphicBuffer::USAGE_HW_COMPOSER |
179 GraphicBuffer::USAGE_HW_TEXTURE,
Ady Abrahamdbca1352021-12-15 11:58:56 -0800180 1, false, this);
liulijuneb489f62022-10-17 22:02:14 +0800181 static std::atomic<uint32_t> nextId = 0;
182 mProducerId = nextId++;
183 mName = name + "#" + std::to_string(mProducerId);
184 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(mProducerId);
185 mQueuedBufferTrace = "QueuedBuffer - " + mName + "BLAST#" + std::to_string(mProducerId);
Vishnu Nairdab94092020-09-29 16:09:04 -0700186 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700187 mBufferItemConsumer->setFrameAvailableListener(this);
Robert Carr9f133d72020-04-01 15:51:46 -0700188
Huihong Luo02186fb2022-02-23 14:21:54 -0800189 ComposerServiceAIDL::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);
Ady Abraham0bde6b52021-05-18 13:57:02 -0700190 mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
chaviw69058fb2021-09-27 09:37:30 -0500191 mCurrentMaxAcquiredBufferCount = mMaxAcquiredBuffers;
Valerie Haua32c5522019-12-09 10:11:08 -0800192 mNumAcquired = 0;
193 mNumFrameAvailable = 0;
Robert Carr4c1b6462021-12-21 10:30:50 -0800194
195 TransactionCompletedListener::getInstance()->addQueueStallListener(
Patrick Williamsf1e5df12022-10-17 21:37:42 +0000196 [&](const std::string& reason) {
197 std::function<void(const std::string&)> callbackCopy;
198 {
199 std::unique_lock _lock{mMutex};
200 callbackCopy = mTransactionHangCallback;
201 }
202 if (callbackCopy) callbackCopy(reason);
203 },
204 this);
Robert Carr4c1b6462021-12-21 10:30:50 -0800205
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800206 BQA_LOGV("BLASTBufferQueue created");
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800207}
208
209BLASTBufferQueue::BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface,
210 int width, int height, int32_t format)
211 : BLASTBufferQueue(name) {
212 update(surface, width, height, format);
Robert Carr78c25dd2019-08-15 14:10:33 -0700213}
214
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800215BLASTBufferQueue::~BLASTBufferQueue() {
Robert Carr4c1b6462021-12-21 10:30:50 -0800216 TransactionCompletedListener::getInstance()->removeQueueStallListener(this);
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800217 if (mPendingTransactions.empty()) {
218 return;
219 }
220 BQA_LOGE("Applying pending transactions on dtor %d",
221 static_cast<uint32_t>(mPendingTransactions.size()));
222 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800223 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
Robert Carr79dc06a2022-02-22 15:28:59 -0800224 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
225 t.setApplyToken(mApplyToken).apply(false, true);
chaviw3b4bdcf2022-03-17 09:27:03 -0500226
227 if (mTransactionReadyCallback) {
228 mTransactionReadyCallback(mSyncTransaction);
229 }
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800230}
231
chaviw565ee542021-01-14 10:21:23 -0800232void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Naird2aaab12022-02-10 14:49:09 -0800233 int32_t format) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800234 LOG_ALWAYS_FATAL_IF(surface == nullptr, "BLASTBufferQueue: mSurfaceControl must not be NULL");
235
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000236 std::lock_guard _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800237 if (mFormat != format) {
238 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800239 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800240 }
241
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800242 const bool surfaceControlChanged = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairab066512022-01-04 22:28:00 +0000243 if (surfaceControlChanged && mSurfaceControl != nullptr) {
244 BQA_LOGD("Updating SurfaceControl without recreating BBQ");
245 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800246 bool applyTransaction = false;
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800247
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700248 // Always update the native object even though they might have the same layer handle, so we can
249 // get the updated transform hint from WM.
250 mSurfaceControl = surface;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800251 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800252 if (surfaceControlChanged) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800253 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
254 layer_state_t::eEnableBackpressure);
255 applyTransaction = true;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800256 }
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800257 mTransformHint = mSurfaceControl->getTransformHint();
258 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700259 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
260 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800261
Vishnu Nairea0de002020-11-17 17:42:37 -0800262 ui::Size newSize(width, height);
263 if (mRequestedSize != newSize) {
264 mRequestedSize.set(newSize);
265 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000266 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800267 // If the buffer supports scaling, update the frame immediately since the client may
268 // want to scale the existing buffer to the new size.
269 mSize = mRequestedSize;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800270 if (mUpdateDestinationFrame) {
271 t.setDestinationFrame(mSurfaceControl, Rect(newSize));
272 applyTransaction = true;
273 }
Vishnu Nair53c936c2020-12-03 11:46:37 -0800274 }
Robert Carrfc416512020-04-02 12:32:44 -0700275 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800276 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800277 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
278 t.setApplyToken(mApplyToken).apply(false, true);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800279 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700280}
281
chaviwd7deef72021-10-06 11:53:40 -0500282static std::optional<SurfaceControlStats> findMatchingStat(
283 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
284 for (auto stat : stats) {
285 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
286 return stat;
287 }
288 }
289 return std::nullopt;
290}
291
292static void transactionCommittedCallbackThunk(void* context, nsecs_t latchTime,
293 const sp<Fence>& presentFence,
294 const std::vector<SurfaceControlStats>& stats) {
295 if (context == nullptr) {
296 return;
297 }
298 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
299 bq->transactionCommittedCallback(latchTime, presentFence, stats);
300}
301
302void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
303 const sp<Fence>& /*presentFence*/,
304 const std::vector<SurfaceControlStats>& stats) {
305 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000306 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600307 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500308 BQA_LOGV("transactionCommittedCallback");
309 if (!mSurfaceControlsWithPendingCallback.empty()) {
310 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
311 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
312 if (stat) {
313 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
314
315 // We need to check if we were waiting for a transaction callback in order to
316 // process any pending buffers and unblock. It's possible to get transaction
chaviwc1cf4022022-06-03 13:32:33 -0500317 // callbacks for previous requests so we need to ensure that there are no pending
318 // frame numbers that were in a sync. We remove the frame from mSyncedFrameNumbers
319 // set and then check if it's empty. If there are no more pending syncs, we can
320 // proceed with flushing the shadow queue.
chaviwc1cf4022022-06-03 13:32:33 -0500321 mSyncedFrameNumbers.erase(currFrameNumber);
Chavi Weingartend48797b2023-08-04 13:11:39 +0000322 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500323 flushShadowQueue();
324 }
325 } else {
chaviw768bfa02021-11-01 09:50:57 -0500326 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviwd7deef72021-10-06 11:53:40 -0500327 }
328 } else {
329 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
330 "empty.");
331 }
chaviwd7deef72021-10-06 11:53:40 -0500332 decStrong((void*)transactionCommittedCallbackThunk);
333 }
334}
335
Robert Carr78c25dd2019-08-15 14:10:33 -0700336static void transactionCallbackThunk(void* context, nsecs_t latchTime,
337 const sp<Fence>& presentFence,
338 const std::vector<SurfaceControlStats>& stats) {
339 if (context == nullptr) {
340 return;
341 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800342 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700343 bq->transactionCallback(latchTime, presentFence, stats);
344}
345
346void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
347 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700348 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000349 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600350 BBQ_TRACE();
chaviw71c2cc42020-10-23 16:42:02 -0700351 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700352
chaviw42026162021-04-16 15:46:12 -0500353 if (!mSurfaceControlsWithPendingCallback.empty()) {
354 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
355 mSurfaceControlsWithPendingCallback.pop();
chaviwd7deef72021-10-06 11:53:40 -0500356 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
357 if (statsOptional) {
358 SurfaceControlStats stat = *statsOptional;
Vishnu Nair71fcf912022-10-18 09:14:20 -0700359 if (stat.transformHint) {
360 mTransformHint = *stat.transformHint;
361 mBufferItemConsumer->setTransformHint(mTransformHint);
362 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
363 }
Vishnu Nairde66dc72021-06-17 17:54:41 -0700364 // Update frametime stamps if the frame was latched and presented, indicated by a
365 // valid latch time.
366 if (stat.latchTime > 0) {
367 mBufferItemConsumer
368 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
369 stat.frameEventStats.refreshStartTime,
370 stat.frameEventStats.gpuCompositionDoneFence,
371 stat.presentFence, stat.previousReleaseFence,
372 stat.frameEventStats.compositorTiming,
373 stat.latchTime,
374 stat.frameEventStats.dequeueReadyTime);
375 }
Robert Carr405e2f62021-12-31 16:59:34 -0800376 auto currFrameNumber = stat.frameEventStats.frameNumber;
377 std::vector<ReleaseCallbackId> staleReleases;
378 for (const auto& [key, value]: mSubmitted) {
379 if (currFrameNumber > key.framenumber) {
380 staleReleases.push_back(key);
381 }
382 }
383 for (const auto& staleRelease : staleReleases) {
Robert Carr405e2f62021-12-31 16:59:34 -0800384 releaseBufferCallbackLocked(staleRelease,
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700385 stat.previousReleaseFence
386 ? stat.previousReleaseFence
387 : Fence::NO_FENCE,
388 stat.currentMaxAcquiredBufferCount,
389 true /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800390 }
chaviwd7deef72021-10-06 11:53:40 -0500391 } else {
chaviw768bfa02021-11-01 09:50:57 -0500392 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500393 }
394 } else {
395 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
396 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800397 }
chaviw71c2cc42020-10-23 16:42:02 -0700398
chaviw71c2cc42020-10-23 16:42:02 -0700399 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700400 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700401}
402
Vishnu Nair1506b182021-02-22 14:35:15 -0800403// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
404// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
405// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
406// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700407static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
chaviw69058fb2021-09-27 09:37:30 -0500408 const sp<Fence>& releaseFence,
409 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800410 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800411 if (blastBufferQueue) {
chaviw69058fb2021-09-27 09:37:30 -0500412 blastBufferQueue->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700413 } else {
414 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800415 }
416}
417
chaviwd7deef72021-10-06 11:53:40 -0500418void BLASTBufferQueue::flushShadowQueue() {
419 BQA_LOGV("flushShadowQueue");
420 int numFramesToFlush = mNumFrameAvailable;
421 while (numFramesToFlush > 0) {
422 acquireNextBufferLocked(std::nullopt);
423 numFramesToFlush--;
424 }
425}
426
chaviw69058fb2021-09-27 09:37:30 -0500427void BLASTBufferQueue::releaseBufferCallback(
428 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
429 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000430 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600431 BBQ_TRACE();
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700432 releaseBufferCallbackLocked(id, releaseFence, currentMaxAcquiredBufferCount,
433 false /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800434}
435
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700436void BLASTBufferQueue::releaseBufferCallbackLocked(
437 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
438 std::optional<uint32_t> currentMaxAcquiredBufferCount, bool fakeRelease) {
Robert Carr405e2f62021-12-31 16:59:34 -0800439 ATRACE_CALL();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700440 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800441
Ady Abraham899dcdb2021-06-15 16:56:21 -0700442 // Calculate how many buffers we need to hold before we release them back
443 // to the buffer queue. This will prevent higher latency when we are running
444 // on a lower refresh rate than the max supported. We only do that for EGL
445 // clients as others don't care about latency
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000446 const auto it = mSubmitted.find(id);
447 const bool isEGL = it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
Ady Abraham899dcdb2021-06-15 16:56:21 -0700448
chaviw69058fb2021-09-27 09:37:30 -0500449 if (currentMaxAcquiredBufferCount) {
450 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
451 }
452
liulijunf90df632022-11-14 14:24:48 +0800453 const uint32_t numPendingBuffersToHold =
454 isEGL ? std::max(0, mMaxAcquiredBuffers - (int32_t)mCurrentMaxAcquiredBufferCount) : 0;
Robert Carr405e2f62021-12-31 16:59:34 -0800455
456 auto rb = ReleasedBuffer{id, releaseFence};
457 if (std::find(mPendingRelease.begin(), mPendingRelease.end(), rb) == mPendingRelease.end()) {
458 mPendingRelease.emplace_back(rb);
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700459 if (fakeRelease) {
460 BQA_LOGE("Faking releaseBufferCallback from transactionCompleteCallback %" PRIu64,
461 id.framenumber);
462 BBQ_TRACE("FakeReleaseCallback");
463 }
Robert Carr405e2f62021-12-31 16:59:34 -0800464 }
Ady Abraham899dcdb2021-06-15 16:56:21 -0700465
466 // Release all buffers that are beyond the ones that we need to hold
467 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500468 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700469 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500470 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwc1cf4022022-06-03 13:32:33 -0500471 // Don't process the transactions here if mSyncedFrameNumbers is not empty. That means
472 // are still transactions that have sync buffers in them that have not been applied or
473 // dropped. Instead, let onFrameAvailable handle processing them since it will merge with
474 // the syncTransaction.
475 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500476 acquireNextBufferLocked(std::nullopt);
477 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800478 }
479
Ady Abraham899dcdb2021-06-15 16:56:21 -0700480 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700481 ATRACE_INT(mQueuedBufferTrace.c_str(),
482 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800483 mCallbackCV.notify_all();
484}
485
chaviw0acd33a2021-11-02 11:55:37 -0500486void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
487 const sp<Fence>& releaseFence) {
488 auto it = mSubmitted.find(callbackId);
489 if (it == mSubmitted.end()) {
490 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
491 callbackId.to_string().c_str());
492 return;
493 }
494 mNumAcquired--;
chaviw57ae4b22022-02-03 16:51:39 -0600495 BBQ_TRACE("frame=%" PRIu64, callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500496 BQA_LOGV("released %s", callbackId.to_string().c_str());
497 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
498 mSubmitted.erase(it);
chaviwc1cf4022022-06-03 13:32:33 -0500499 // Remove the frame number from mSyncedFrameNumbers since we can get a release callback
500 // without getting a transaction committed if the buffer was dropped.
501 mSyncedFrameNumbers.erase(callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500502}
503
Chavi Weingarten70670e62023-02-22 17:36:40 +0000504static ui::Size getBufferSize(const BufferItem& item) {
505 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
506 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
507
508 // Take the buffer's orientation into account
509 if (item.mTransform & ui::Transform::ROT_90) {
510 std::swap(bufWidth, bufHeight);
511 }
512 return ui::Size(bufWidth, bufHeight);
513}
514
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000515status_t BLASTBufferQueue::acquireNextBufferLocked(
chaviwd7deef72021-10-06 11:53:40 -0500516 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800517 // Check if we have frames available and we have not acquired the maximum number of buffers.
518 // Even with this check, the consumer can fail to acquire an additional buffer if the consumer
519 // has already acquired (mMaxAcquiredBuffers + 1) and the new buffer is not droppable. In this
520 // case mBufferItemConsumer->acquireBuffer will return with NO_BUFFER_AVAILABLE.
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000521 if (mNumFrameAvailable == 0) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800522 BQA_LOGV("Can't acquire next buffer. No available frames");
523 return BufferQueue::NO_BUFFER_AVAILABLE;
524 }
525
526 if (mNumAcquired >= (mMaxAcquiredBuffers + 2)) {
527 BQA_LOGV("Can't acquire next buffer. Already acquired max frames %d max:%d + 2",
528 mNumAcquired, mMaxAcquiredBuffers);
529 return BufferQueue::NO_BUFFER_AVAILABLE;
Valerie Haud3b90d22019-11-06 09:37:31 -0800530 }
531
Valerie Haua32c5522019-12-09 10:11:08 -0800532 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700533 BQA_LOGE("ERROR : surface control is null");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000534 return NAME_NOT_FOUND;
Valerie Haud3b90d22019-11-06 09:37:31 -0800535 }
536
Robert Carr78c25dd2019-08-15 14:10:33 -0700537 SurfaceComposerClient::Transaction localTransaction;
538 bool applyTransaction = true;
539 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500540 if (transaction) {
541 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700542 applyTransaction = false;
543 }
544
Valerie Haua32c5522019-12-09 10:11:08 -0800545 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800546
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800547 status_t status =
548 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800549 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
550 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000551 return status;
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800552 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700553 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000554 return status;
Robert Carr78c25dd2019-08-15 14:10:33 -0700555 }
chaviw57ae4b22022-02-03 16:51:39 -0600556
Valerie Haua32c5522019-12-09 10:11:08 -0800557 auto buffer = bufferItem.mGraphicBuffer;
558 mNumFrameAvailable--;
chaviw57ae4b22022-02-03 16:51:39 -0600559 BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800560
561 if (buffer == nullptr) {
562 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700563 BQA_LOGE("Buffer was empty");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000564 return BAD_VALUE;
Valerie Haua32c5522019-12-09 10:11:08 -0800565 }
566
Vishnu Nair670b3f72020-09-29 17:52:18 -0700567 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700568 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800569 "buffer{size=%dx%d transform=%d}",
570 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
571 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
572 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000573 return acquireNextBufferLocked(transaction);
Vishnu Nair670b3f72020-09-29 17:52:18 -0700574 }
575
Valerie Haua32c5522019-12-09 10:11:08 -0800576 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700577 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
578 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
579 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700580
Valerie Hau871d6352020-01-29 08:44:02 -0800581 bool needsDisconnect = false;
582 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
583
584 // if producer disconnected before, notify SurfaceFlinger
585 if (needsDisconnect) {
586 t->notifyProducerDisconnect(mSurfaceControl);
587 }
588
Robert Carr78c25dd2019-08-15 14:10:33 -0700589 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
590 incStrong((void*)transactionCallbackThunk);
591
Chavi Weingarten70670e62023-02-22 17:36:40 +0000592 // Only update mSize for destination bounds if the incoming buffer matches the requested size.
593 // Otherwise, it could cause stretching since the destination bounds will update before the
594 // buffer with the new size is acquired.
Vishnu Nair5b5f6932023-04-12 16:28:19 -0700595 if (mRequestedSize == getBufferSize(bufferItem) ||
596 bufferItem.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Chavi Weingarten70670e62023-02-22 17:36:40 +0000597 mSize = mRequestedSize;
598 }
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700599 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000600 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
601 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700602 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800603
Vishnu Nair1506b182021-02-22 14:35:15 -0800604 auto releaseBufferCallback =
605 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
chaviw69058fb2021-09-27 09:37:30 -0500606 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
chaviwba4320c2021-09-15 15:20:53 -0500607 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
liulijuneb489f62022-10-17 22:02:14 +0800608 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, mProducerId,
609 releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500610 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
611 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
612 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700613 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviwf2dace72021-11-17 17:36:50 -0600614
chaviw42026162021-04-16 15:46:12 -0500615 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700616
Vishnu Naird2aaab12022-02-10 14:49:09 -0800617 if (mUpdateDestinationFrame) {
618 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
619 } else {
620 const bool ignoreDestinationFrame =
621 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
622 t->setFlags(mSurfaceControl,
623 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
624 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700625 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700626 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800627 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800628 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800629 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800630 if (!bufferItem.mIsAutoTimestamp) {
631 t->setDesiredPresentTime(bufferItem.mTimestamp);
632 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700633
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800634 // Drop stale frame timeline infos
635 while (!mPendingFrameTimelines.empty() &&
636 mPendingFrameTimelines.front().first < bufferItem.mFrameNumber) {
637 ATRACE_FORMAT_INSTANT("dropping stale frameNumber: %" PRIu64 " vsyncId: %" PRId64,
638 mPendingFrameTimelines.front().first,
639 mPendingFrameTimelines.front().second.vsyncId);
640 mPendingFrameTimelines.pop();
641 }
642
643 if (!mPendingFrameTimelines.empty() &&
644 mPendingFrameTimelines.front().first == bufferItem.mFrameNumber) {
645 ATRACE_FORMAT_INSTANT("Transaction::setFrameTimelineInfo frameNumber: %" PRIu64
646 " vsyncId: %" PRId64,
647 bufferItem.mFrameNumber,
648 mPendingFrameTimelines.front().second.vsyncId);
649 t->setFrameTimelineInfo(mPendingFrameTimelines.front().second);
650 mPendingFrameTimelines.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100651 }
652
Vishnu Nairadf632b2021-01-07 14:05:08 -0800653 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000654 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800655 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
656 if (dequeueTime != mDequeueTimestamps.end()) {
657 Parcel p;
658 p.writeInt64(dequeueTime->second);
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800659 t->setMetadata(mSurfaceControl, gui::METADATA_DEQUEUE_TIME, p);
Vishnu Nairadf632b2021-01-07 14:05:08 -0800660 mDequeueTimestamps.erase(dequeueTime);
661 }
662 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800663
chaviw6a195272021-09-03 16:14:25 -0500664 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700665 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800666 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
667 t->setApplyToken(mApplyToken).apply(false, true);
668 mAppliedLastTransaction = true;
669 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
670 } else {
671 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
672 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700673 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700674
chaviwd7deef72021-10-06 11:53:40 -0500675 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800676 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700677 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500678 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800679 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700680 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700681 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000682 return OK;
Robert Carr78c25dd2019-08-15 14:10:33 -0700683}
684
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800685Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
686 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800687 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800688 }
689 return item.mCrop;
690}
691
chaviwd7deef72021-10-06 11:53:40 -0500692void BLASTBufferQueue::acquireAndReleaseBuffer() {
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000693 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500694 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500695 status_t status =
696 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
697 if (status != OK) {
698 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
699 statusToString(status).c_str());
700 return;
701 }
chaviwd7deef72021-10-06 11:53:40 -0500702 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500703 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500704}
705
Vishnu Nairaef1de92020-10-22 12:15:53 -0700706void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000707 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
708 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
chaviwc1cf4022022-06-03 13:32:33 -0500709
Tianhao Yao4861b102022-02-03 20:18:35 +0000710 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000711 UNIQUE_LOCK_WITH_ASSERTION(mMutex);
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000712 BBQ_TRACE();
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000713 bool waitForTransactionCallback = !mSyncedFrameNumbers.empty();
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800714
Tianhao Yao4861b102022-02-03 20:18:35 +0000715 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
716 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800717
Tianhao Yao4861b102022-02-03 20:18:35 +0000718 if (syncTransactionSet) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000719 // If we are going to re-use the same mSyncTransaction, release the buffer that may
720 // already be set in the Transaction. This is to allow us a free slot early to continue
721 // processing a new buffer.
722 if (!mAcquireSingleBuffer) {
723 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
724 if (bufferData) {
725 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
726 bufferData->frameNumber);
727 releaseBuffer(bufferData->generateReleaseCallbackId(),
728 bufferData->acquireFence);
Tianhao Yao4861b102022-02-03 20:18:35 +0000729 }
730 }
chaviw0acd33a2021-11-02 11:55:37 -0500731
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000732 if (waitForTransactionCallback) {
733 // We are waiting on a previous sync's transaction callback so allow another sync
734 // transaction to proceed.
735 //
736 // We need to first flush out the transactions that were in between the two syncs.
737 // We do this by merging them into mSyncTransaction so any buffer merging will get
738 // a release callback invoked.
739 while (mNumFrameAvailable > 0) {
740 // flush out the shadow queue
741 acquireAndReleaseBuffer();
742 }
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800743 } else {
744 // Make sure the frame available count is 0 before proceeding with a sync to ensure
745 // the correct frame is used for the sync. The only way mNumFrameAvailable would be
746 // greater than 0 is if we already ran out of buffers previously. This means we
747 // need to flush the buffers before proceeding with the sync.
748 while (mNumFrameAvailable > 0) {
749 BQA_LOGD("waiting until no queued buffers");
750 mCallbackCV.wait(_lock);
751 }
chaviwd7deef72021-10-06 11:53:40 -0500752 }
753 }
754
Tianhao Yao4861b102022-02-03 20:18:35 +0000755 // add to shadow queue
756 mNumFrameAvailable++;
chaviwc1cf4022022-06-03 13:32:33 -0500757 if (waitForTransactionCallback && mNumFrameAvailable >= 2) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000758 acquireAndReleaseBuffer();
759 }
760 ATRACE_INT(mQueuedBufferTrace.c_str(),
761 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
762
763 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
764 item.mFrameNumber, boolToString(syncTransactionSet));
765
766 if (syncTransactionSet) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800767 // Add to mSyncedFrameNumbers before waiting in case any buffers are released
768 // while waiting for a free buffer. The release and commit callback will try to
769 // acquire buffers if there are any available, but we don't want it to acquire
770 // in the case where a sync transaction wants the buffer.
771 mSyncedFrameNumbers.emplace(item.mFrameNumber);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000772 // If there's no available buffer and we're in a sync transaction, we need to wait
773 // instead of returning since we guarantee a buffer will be acquired for the sync.
774 while (acquireNextBufferLocked(mSyncTransaction) == BufferQueue::NO_BUFFER_AVAILABLE) {
775 BQA_LOGD("waiting for available buffer");
776 mCallbackCV.wait(_lock);
777 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000778
779 // Only need a commit callback when syncing to ensure the buffer that's synced has been
780 // sent to SF
781 incStrong((void*)transactionCommittedCallbackThunk);
782 mSyncTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,
783 static_cast<void*>(this));
Tianhao Yao4861b102022-02-03 20:18:35 +0000784 if (mAcquireSingleBuffer) {
785 prevCallback = mTransactionReadyCallback;
786 prevTransaction = mSyncTransaction;
787 mTransactionReadyCallback = nullptr;
788 mSyncTransaction = nullptr;
789 }
chaviwc1cf4022022-06-03 13:32:33 -0500790 } else if (!waitForTransactionCallback) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000791 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800792 }
793 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000794 if (prevCallback) {
795 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500796 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800797}
798
Vishnu Nairaef1de92020-10-22 12:15:53 -0700799void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
800 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
801 // Do nothing since we are not storing unacquired buffer items locally.
802}
803
Vishnu Nairadf632b2021-01-07 14:05:08 -0800804void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000805 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800806 mDequeueTimestamps[bufferId] = systemTime();
807};
808
809void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000810 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800811 mDequeueTimestamps.erase(bufferId);
812};
813
Chavi Weingartenc398c012023-04-12 17:26:02 +0000814bool BLASTBufferQueue::syncNextTransaction(
Tianhao Yao4861b102022-02-03 20:18:35 +0000815 std::function<void(SurfaceComposerClient::Transaction*)> callback,
816 bool acquireSingleBuffer) {
Chavi Weingartenc398c012023-04-12 17:26:02 +0000817 LOG_ALWAYS_FATAL_IF(!callback,
818 "BLASTBufferQueue: callback passed in to syncNextTransaction must not be "
819 "NULL");
chaviw3b4bdcf2022-03-17 09:27:03 -0500820
Chavi Weingartenc398c012023-04-12 17:26:02 +0000821 std::lock_guard _lock{mMutex};
822 BBQ_TRACE();
823 if (mTransactionReadyCallback) {
824 ALOGW("Attempting to overwrite transaction callback in syncNextTransaction");
825 return false;
Tianhao Yao4861b102022-02-03 20:18:35 +0000826 }
chaviw3b4bdcf2022-03-17 09:27:03 -0500827
Chavi Weingartenc398c012023-04-12 17:26:02 +0000828 mTransactionReadyCallback = callback;
829 mSyncTransaction = new SurfaceComposerClient::Transaction();
830 mAcquireSingleBuffer = acquireSingleBuffer;
831 return true;
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};
Chavi Weingartenc398c012023-04-12 17:26:02 +0000839 if (mAcquireSingleBuffer || !mTransactionReadyCallback) {
840 ALOGW("Attempting to stop continuous sync when none are active");
841 return;
Tianhao Yao4861b102022-02-03 20:18:35 +0000842 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000843
844 prevCallback = mTransactionReadyCallback;
845 prevTransaction = mSyncTransaction;
846
Tianhao Yao4861b102022-02-03 20:18:35 +0000847 mTransactionReadyCallback = nullptr;
848 mSyncTransaction = nullptr;
849 mAcquireSingleBuffer = true;
850 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000851
Tianhao Yao4861b102022-02-03 20:18:35 +0000852 if (prevCallback) {
853 prevCallback(prevTransaction);
854 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700855}
856
Chavi Weingartenc398c012023-04-12 17:26:02 +0000857void BLASTBufferQueue::clearSyncTransaction() {
858 std::lock_guard _lock{mMutex};
859 if (!mAcquireSingleBuffer) {
860 ALOGW("Attempting to clear sync transaction when none are active");
861 return;
862 }
863
864 mTransactionReadyCallback = nullptr;
865 mSyncTransaction = nullptr;
866}
867
Vishnu Nairea0de002020-11-17 17:42:37 -0800868bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700869 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
870 // Only reject buffers if scaling mode is freeze.
871 return false;
872 }
873
Chavi Weingarten70670e62023-02-22 17:36:40 +0000874 ui::Size bufferSize = getBufferSize(item);
Vishnu Nairea0de002020-11-17 17:42:37 -0800875 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800876 return false;
877 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700878
Vishnu Nair670b3f72020-09-29 17:52:18 -0700879 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800880 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700881}
Vishnu Nairbf255772020-10-16 10:54:41 -0700882
Robert Carr05086b22020-10-13 18:22:51 -0700883class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700884private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700885 std::mutex mMutex;
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000886 sp<BLASTBufferQueue> mBbq GUARDED_BY(mMutex);
887 bool mDestroyed GUARDED_BY(mMutex) = false;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700888
Robert Carr05086b22020-10-13 18:22:51 -0700889public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700890 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
891 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
892 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700893
Robert Carr05086b22020-10-13 18:22:51 -0700894 void allocateBuffers() override {
895 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
896 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
897 auto gbp = getIGraphicBufferProducer();
898 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
899 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
900 gbp->allocateBuffers(reqWidth, reqHeight,
901 reqFormat, reqUsage);
902
903 }).detach();
904 }
Robert Carr9c006e02020-10-14 13:41:57 -0700905
Marin Shalamanovc5986772021-03-16 16:09:49 +0100906 status_t setFrameRate(float frameRate, int8_t compatibility,
907 int8_t changeFrameRateStrategy) override {
Ady Abraham6cdd3fd2023-09-07 18:45:58 -0700908 if (flags::bq_setframerate()) {
909 return Surface::setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
910 }
911
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000912 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700913 if (mDestroyed) {
914 return DEAD_OBJECT;
915 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100916 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
917 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700918 return BAD_VALUE;
919 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100920 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700921 }
Robert Carr9b611b72020-10-19 12:00:23 -0700922
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800923 status_t setFrameTimelineInfo(uint64_t frameNumber,
924 const FrameTimelineInfo& frameTimelineInfo) override {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000925 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700926 if (mDestroyed) {
927 return DEAD_OBJECT;
928 }
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800929 return mBbq->setFrameTimelineInfo(frameNumber, frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700930 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700931
932 void destroy() override {
933 Surface::destroy();
934
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000935 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700936 mDestroyed = true;
937 mBbq = nullptr;
938 }
Robert Carr05086b22020-10-13 18:22:51 -0700939};
940
Robert Carr9c006e02020-10-14 13:41:57 -0700941// TODO: Can we coalesce this with frame updates? Need to confirm
942// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200943status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
944 bool shouldBeSeamless) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000945 std::lock_guard _lock{mMutex};
Robert Carr9c006e02020-10-14 13:41:57 -0700946 SurfaceComposerClient::Transaction t;
947
Marin Shalamanov46084422020-10-13 12:33:42 +0200948 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700949}
950
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800951status_t BLASTBufferQueue::setFrameTimelineInfo(uint64_t frameNumber,
952 const FrameTimelineInfo& frameTimelineInfo) {
953 ATRACE_FORMAT("%s(%s) frameNumber: %" PRIu64 " vsyncId: %" PRId64, __func__, mName.c_str(),
954 frameNumber, frameTimelineInfo.vsyncId);
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000955 std::lock_guard _lock{mMutex};
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800956 mPendingFrameTimelines.push({frameNumber, frameTimelineInfo});
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100957 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700958}
959
Hongguang Chen621ec582021-02-16 15:42:35 -0800960void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000961 std::lock_guard _lock{mMutex};
Hongguang Chen621ec582021-02-16 15:42:35 -0800962 SurfaceComposerClient::Transaction t;
963
964 t.setSidebandStream(mSurfaceControl, stream).apply();
965}
966
Vishnu Nair992496b2020-10-22 17:27:21 -0700967sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000968 std::lock_guard _lock{mMutex};
Vishnu Nair992496b2020-10-22 17:27:21 -0700969 sp<IBinder> scHandle = nullptr;
970 if (includeSurfaceControlHandle && mSurfaceControl) {
971 scHandle = mSurfaceControl->getHandle();
972 }
973 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700974}
975
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800976void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
977 uint64_t frameNumber) {
978 std::lock_guard _lock{mMutex};
979 if (mLastAcquiredFrameNumber >= frameNumber) {
980 // Apply the transaction since we have already acquired the desired frame.
981 t->apply();
982 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500983 mPendingTransactions.emplace_back(frameNumber, *t);
984 // Clear the transaction so it can't be applied elsewhere.
985 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800986 }
987}
988
chaviw6a195272021-09-03 16:14:25 -0500989void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
990 std::lock_guard _lock{mMutex};
991
992 SurfaceComposerClient::Transaction t;
993 mergePendingTransactions(&t, frameNumber);
Robert Carr79dc06a2022-02-22 15:28:59 -0800994 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
995 t.setApplyToken(mApplyToken).apply(false, true);
chaviw6a195272021-09-03 16:14:25 -0500996}
997
998void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
999 uint64_t frameNumber) {
1000 auto mergeTransaction =
1001 [&t, currentFrameNumber = frameNumber](
1002 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
1003 auto& [targetFrameNumber, transaction] = pendingTransaction;
1004 if (currentFrameNumber < targetFrameNumber) {
1005 return false;
1006 }
1007 t->merge(std::move(transaction));
1008 return true;
1009 };
1010
1011 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
1012 mPendingTransactions.end(), mergeTransaction),
1013 mPendingTransactions.end());
1014}
1015
chaviwd84085a2022-02-08 11:07:04 -06001016SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
1017 uint64_t frameNumber) {
1018 std::lock_guard _lock{mMutex};
1019 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
1020 mergePendingTransactions(t, frameNumber);
1021 return t;
1022}
1023
Vishnu Nair89496122020-12-14 17:14:53 -08001024// Maintains a single worker thread per process that services a list of runnables.
1025class AsyncWorker : public Singleton<AsyncWorker> {
1026private:
1027 std::thread mThread;
1028 bool mDone = false;
1029 std::deque<std::function<void()>> mRunnables;
1030 std::mutex mMutex;
1031 std::condition_variable mCv;
1032 void run() {
1033 std::unique_lock<std::mutex> lock(mMutex);
1034 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -08001035 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001036 std::deque<std::function<void()>> runnables = std::move(mRunnables);
1037 mRunnables.clear();
1038 lock.unlock();
1039 // Run outside the lock since the runnable might trigger another
1040 // post to the async worker.
1041 execute(runnables);
1042 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -08001043 }
Wonsik Kim567533e2021-05-04 19:31:29 -07001044 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -08001045 }
1046 }
1047
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001048 void execute(std::deque<std::function<void()>>& runnables) {
1049 while (!runnables.empty()) {
1050 std::function<void()> runnable = runnables.front();
1051 runnables.pop_front();
1052 runnable();
1053 }
1054 }
1055
Vishnu Nair89496122020-12-14 17:14:53 -08001056public:
1057 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
1058
1059 ~AsyncWorker() {
1060 mDone = true;
1061 mCv.notify_all();
1062 if (mThread.joinable()) {
1063 mThread.join();
1064 }
1065 }
1066
1067 void post(std::function<void()> runnable) {
1068 std::unique_lock<std::mutex> lock(mMutex);
1069 mRunnables.emplace_back(std::move(runnable));
1070 mCv.notify_one();
1071 }
1072};
1073ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
1074
1075// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
1076class AsyncProducerListener : public BnProducerListener {
1077private:
1078 const sp<IProducerListener> mListener;
1079
1080public:
1081 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
1082
1083 void onBufferReleased() override {
1084 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
1085 }
1086
1087 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
1088 AsyncWorker::getInstance().post(
1089 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
1090 }
1091};
1092
1093// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
1094// can be non-blocking when the producer is in the client process.
1095class BBQBufferQueueProducer : public BufferQueueProducer {
1096public:
Brian Lindahlc794b692023-01-31 15:42:47 -07001097 BBQBufferQueueProducer(const sp<BufferQueueCore>& core, wp<BLASTBufferQueue> bbq)
1098 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/),
1099 mBLASTBufferQueue(std::move(bbq)) {}
Vishnu Nair89496122020-12-14 17:14:53 -08001100
1101 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
1102 QueueBufferOutput* output) override {
1103 if (!listener) {
1104 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
1105 }
1106
1107 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
1108 producerControlledByApp, output);
1109 }
Vishnu Nair17dde612020-12-28 11:39:59 -08001110
Brian Lindahlc794b692023-01-31 15:42:47 -07001111 // We want to resize the frame history when changing the size of the buffer queue
1112 status_t setMaxDequeuedBufferCount(int maxDequeuedBufferCount) override {
1113 int maxBufferCount;
1114 status_t status = BufferQueueProducer::setMaxDequeuedBufferCount(maxDequeuedBufferCount,
1115 &maxBufferCount);
1116 // if we can't determine the max buffer count, then just skip growing the history size
1117 if (status == OK) {
1118 size_t newFrameHistorySize = maxBufferCount + 2; // +2 because triple buffer rendering
1119 // optimize away resizing the frame history unless it will grow
1120 if (newFrameHistorySize > FrameEventHistory::INITIAL_MAX_FRAME_HISTORY) {
1121 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1122 if (bbq != nullptr) {
1123 ALOGV("increasing frame history size to %zu", newFrameHistorySize);
1124 bbq->resizeFrameEventHistory(newFrameHistorySize);
1125 }
1126 }
1127 }
1128 return status;
1129 }
1130
Vishnu Nair17dde612020-12-28 11:39:59 -08001131 int query(int what, int* value) override {
1132 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
1133 *value = 1;
1134 return NO_ERROR;
1135 }
1136 return BufferQueueProducer::query(what, value);
1137 }
Brian Lindahlc794b692023-01-31 15:42:47 -07001138
1139private:
1140 const wp<BLASTBufferQueue> mBLASTBufferQueue;
Vishnu Nair89496122020-12-14 17:14:53 -08001141};
1142
1143// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
1144// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
1145// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
1146// we can deadlock.
1147void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
1148 sp<IGraphicBufferConsumer>* outConsumer) {
1149 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
1150 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
1151
1152 sp<BufferQueueCore> core(new BufferQueueCore());
1153 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
1154
Brian Lindahlc794b692023-01-31 15:42:47 -07001155 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core, this));
Vishnu Nair89496122020-12-14 17:14:53 -08001156 LOG_ALWAYS_FATAL_IF(producer == nullptr,
1157 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
1158
Vishnu Nair8b30dd12021-01-25 14:16:54 -08001159 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
1160 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -08001161 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
1162 "BLASTBufferQueue: failed to create BufferQueueConsumer");
1163
1164 *outProducer = producer;
1165 *outConsumer = consumer;
1166}
1167
Brian Lindahlc794b692023-01-31 15:42:47 -07001168void BLASTBufferQueue::resizeFrameEventHistory(size_t newSize) {
1169 // This can be null during creation of the buffer queue, but resizing won't do anything at that
1170 // point in time, so just ignore. This can go away once the class relationships and lifetimes of
1171 // objects are cleaned up with a major refactor of BufferQueue as a whole.
1172 if (mBufferItemConsumer != nullptr) {
1173 std::unique_lock _lock{mMutex};
1174 mBufferItemConsumer->resizeFrameEventHistory(newSize);
1175 }
1176}
1177
chaviw497e81c2021-02-04 17:09:47 -08001178PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
1179 PixelFormat convertedFormat = format;
1180 switch (format) {
1181 case PIXEL_FORMAT_TRANSPARENT:
1182 case PIXEL_FORMAT_TRANSLUCENT:
1183 convertedFormat = PIXEL_FORMAT_RGBA_8888;
1184 break;
1185 case PIXEL_FORMAT_OPAQUE:
1186 convertedFormat = PIXEL_FORMAT_RGBX_8888;
1187 break;
1188 }
1189 return convertedFormat;
1190}
1191
Robert Carr82d07c92021-05-10 11:36:43 -07001192uint32_t BLASTBufferQueue::getLastTransformHint() const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001193 std::lock_guard _lock{mMutex};
Robert Carr82d07c92021-05-10 11:36:43 -07001194 if (mSurfaceControl != nullptr) {
1195 return mSurfaceControl->getTransformHint();
1196 } else {
1197 return 0;
1198 }
1199}
1200
chaviw0b020f82021-08-20 12:00:47 -05001201uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001202 std::lock_guard _lock{mMutex};
chaviw0b020f82021-08-20 12:00:47 -05001203 return mLastAcquiredFrameNumber;
1204}
1205
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001206bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001207 std::lock_guard _lock{mMutex};
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001208 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1209}
1210
Patrick Williamsf1e5df12022-10-17 21:37:42 +00001211void BLASTBufferQueue::setTransactionHangCallback(
1212 std::function<void(const std::string&)> callback) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001213 std::lock_guard _lock{mMutex};
Robert Carr4c1b6462021-12-21 10:30:50 -08001214 mTransactionHangCallback = callback;
1215}
1216
Robert Carr78c25dd2019-08-15 14:10:33 -07001217} // namespace android