blob: 1fb59fd8e0d5a737e1c986518ace9c911e2d498a [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
Jim Shargod30823a2024-07-27 02:49:39 +000023#include <com_android_graphics_libgui_flags.h>
liulijuneb489f62022-10-17 22:02:14 +080024#include <cutils/atomic.h>
Robert Carr78c25dd2019-08-15 14:10:33 -070025#include <gui/BLASTBufferQueue.h>
26#include <gui/BufferItemConsumer.h>
Vishnu Nair89496122020-12-14 17:14:53 -080027#include <gui/BufferQueueConsumer.h>
28#include <gui/BufferQueueCore.h>
29#include <gui/BufferQueueProducer.h>
Ady Abraham107788e2023-10-17 12:31:08 -070030
Ady Abraham6cdd3fd2023-09-07 18:45:58 -070031#include <gui/FrameRateUtils.h>
Valerie Hau45e4b3b2019-12-03 10:49:17 -080032#include <gui/GLConsumer.h>
Vishnu Nair89496122020-12-14 17:14:53 -080033#include <gui/IProducerListener.h>
Robert Carr05086b22020-10-13 18:22:51 -070034#include <gui/Surface.h>
chaviw57ae4b22022-02-03 16:51:39 -060035#include <gui/TraceUtils.h>
Vishnu Nair89496122020-12-14 17:14:53 -080036#include <utils/Singleton.h>
Valerie Haua32c5522019-12-09 10:11:08 -080037#include <utils/Trace.h>
38
Ady Abraham0bde6b52021-05-18 13:57:02 -070039#include <private/gui/ComposerService.h>
Huihong Luo02186fb2022-02-23 14:21:54 -080040#include <private/gui/ComposerServiceAIDL.h>
Ady Abraham0bde6b52021-05-18 13:57:02 -070041
Chavi Weingartene0237bb2023-02-06 21:48:32 +000042#include <android-base/thread_annotations.h>
Robert Carr78c25dd2019-08-15 14:10:33 -070043
Alec Mouri21d94322023-10-17 19:51:39 +000044#include <com_android_graphics_libgui_flags.h>
45
Ady Abraham6cdd3fd2023-09-07 18:45:58 -070046using 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
Alec Mouri21d94322023-10-17 19:51:39 +0000107void BLASTBufferItemConsumer::updateFrameTimestamps(
108 uint64_t frameNumber, uint64_t previousFrameNumber, nsecs_t refreshStartTime,
109 const sp<Fence>& glDoneFence, const sp<Fence>& presentFence,
110 const sp<Fence>& prevReleaseFence, CompositorTiming compositorTiming, nsecs_t latchTime,
111 nsecs_t dequeueReadyTime) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800112 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800113
114 // if the producer is not connected, don't bother updating,
115 // the next producer that connects won't access this frame event
116 if (!mCurrentlyConnected) return;
117 std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
118 std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
119 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
120
121 mFrameEventHistory.addLatch(frameNumber, latchTime);
Alec Mouri21d94322023-10-17 19:51:39 +0000122 if (flags::frametimestamps_previousrelease()) {
123 if (previousFrameNumber > 0) {
124 mFrameEventHistory.addRelease(previousFrameNumber, dequeueReadyTime,
125 std::move(releaseFenceTime));
126 }
127 } else {
128 mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
129 }
130
Valerie Hau871d6352020-01-29 08:44:02 -0800131 mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
132 mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
133 compositorTiming);
134}
135
136void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
137 bool disconnect = false;
Hongguang Chen621ec582021-02-16 15:42:35 -0800138 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800139 while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
140 disconnect = true;
141 mDisconnectEvents.pop();
142 }
143 if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
144}
145
Hongguang Chen621ec582021-02-16 15:42:35 -0800146void BLASTBufferItemConsumer::onSidebandStreamChanged() {
Ady Abrahamdbca1352021-12-15 11:58:56 -0800147 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
148 if (bbq != nullptr) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800149 sp<NativeHandle> stream = getSidebandStream();
Ady Abrahamdbca1352021-12-15 11:58:56 -0800150 bbq->setSidebandStream(stream);
Hongguang Chen621ec582021-02-16 15:42:35 -0800151 }
152}
153
Ady Abraham107788e2023-10-17 12:31:08 -0700154#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_SETFRAMERATE)
Ady Abraham6cdd3fd2023-09-07 18:45:58 -0700155void BLASTBufferItemConsumer::onSetFrameRate(float frameRate, int8_t compatibility,
156 int8_t changeFrameRateStrategy) {
157 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
158 if (bbq != nullptr) {
159 bbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
160 }
161}
162#endif
163
Brian Lindahlc794b692023-01-31 15:42:47 -0700164void BLASTBufferItemConsumer::resizeFrameEventHistory(size_t newSize) {
165 Mutex::Autolock lock(mMutex);
166 mFrameEventHistory.resize(newSize);
167}
168
Vishnu Naird2aaab12022-02-10 14:49:09 -0800169BLASTBufferQueue::BLASTBufferQueue(const std::string& name, bool updateDestinationFrame)
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800170 : mSurfaceControl(nullptr),
171 mSize(1, 1),
Vishnu Nairea0de002020-11-17 17:42:37 -0800172 mRequestedSize(mSize),
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800173 mFormat(PIXEL_FORMAT_RGBA_8888),
Tianhao Yao4861b102022-02-03 20:18:35 +0000174 mTransactionReadyCallback(nullptr),
Vishnu Naird2aaab12022-02-10 14:49:09 -0800175 mSyncTransaction(nullptr),
176 mUpdateDestinationFrame(updateDestinationFrame) {
Vishnu Nair89496122020-12-14 17:14:53 -0800177 createBufferQueue(&mProducer, &mConsumer);
Jim Shargod30823a2024-07-27 02:49:39 +0000178#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_CONSUMER_BASE_OWNS_BQ)
179 mBufferItemConsumer = new BLASTBufferItemConsumer(mProducer, mConsumer,
180 GraphicBuffer::USAGE_HW_COMPOSER |
181 GraphicBuffer::USAGE_HW_TEXTURE,
182 1, false, this);
183#else
Vishnu Nair1618c672021-02-05 13:08:26 -0800184 mBufferItemConsumer = new BLASTBufferItemConsumer(mConsumer,
185 GraphicBuffer::USAGE_HW_COMPOSER |
186 GraphicBuffer::USAGE_HW_TEXTURE,
Ady Abrahamdbca1352021-12-15 11:58:56 -0800187 1, false, this);
Jim Shargod30823a2024-07-27 02:49:39 +0000188#endif // COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_CONSUMER_BASE_OWNS_BQ)
189 // since the adapter is in the client process, set dequeue timeout
190 // explicitly so that dequeueBuffer will block
191 mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
192
liulijuneb489f62022-10-17 22:02:14 +0800193 static std::atomic<uint32_t> nextId = 0;
194 mProducerId = nextId++;
195 mName = name + "#" + std::to_string(mProducerId);
196 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(mProducerId);
197 mQueuedBufferTrace = "QueuedBuffer - " + mName + "BLAST#" + std::to_string(mProducerId);
Vishnu Nairdab94092020-09-29 16:09:04 -0700198 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700199 mBufferItemConsumer->setFrameAvailableListener(this);
Robert Carr9f133d72020-04-01 15:51:46 -0700200
Huihong Luo02186fb2022-02-23 14:21:54 -0800201 ComposerServiceAIDL::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);
Ady Abraham0bde6b52021-05-18 13:57:02 -0700202 mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
chaviw69058fb2021-09-27 09:37:30 -0500203 mCurrentMaxAcquiredBufferCount = mMaxAcquiredBuffers;
Valerie Haua32c5522019-12-09 10:11:08 -0800204 mNumAcquired = 0;
205 mNumFrameAvailable = 0;
Robert Carr4c1b6462021-12-21 10:30:50 -0800206
207 TransactionCompletedListener::getInstance()->addQueueStallListener(
Patrick Williamsf1e5df12022-10-17 21:37:42 +0000208 [&](const std::string& reason) {
209 std::function<void(const std::string&)> callbackCopy;
210 {
211 std::unique_lock _lock{mMutex};
212 callbackCopy = mTransactionHangCallback;
213 }
214 if (callbackCopy) callbackCopy(reason);
215 },
216 this);
Robert Carr4c1b6462021-12-21 10:30:50 -0800217
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800218 BQA_LOGV("BLASTBufferQueue created");
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800219}
220
221BLASTBufferQueue::BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface,
222 int width, int height, int32_t format)
223 : BLASTBufferQueue(name) {
224 update(surface, width, height, format);
Robert Carr78c25dd2019-08-15 14:10:33 -0700225}
226
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800227BLASTBufferQueue::~BLASTBufferQueue() {
Robert Carr4c1b6462021-12-21 10:30:50 -0800228 TransactionCompletedListener::getInstance()->removeQueueStallListener(this);
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800229 if (mPendingTransactions.empty()) {
230 return;
231 }
232 BQA_LOGE("Applying pending transactions on dtor %d",
233 static_cast<uint32_t>(mPendingTransactions.size()));
234 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800235 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
Robert Carr79dc06a2022-02-22 15:28:59 -0800236 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
237 t.setApplyToken(mApplyToken).apply(false, true);
chaviw3b4bdcf2022-03-17 09:27:03 -0500238
239 if (mTransactionReadyCallback) {
240 mTransactionReadyCallback(mSyncTransaction);
241 }
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800242}
243
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500244void BLASTBufferQueue::onFirstRef() {
245 // safe default, most producers are expected to override this
246 mProducer->setMaxDequeuedBufferCount(2);
247}
248
chaviw565ee542021-01-14 10:21:23 -0800249void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Naird2aaab12022-02-10 14:49:09 -0800250 int32_t format) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800251 LOG_ALWAYS_FATAL_IF(surface == nullptr, "BLASTBufferQueue: mSurfaceControl must not be NULL");
252
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000253 std::lock_guard _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800254 if (mFormat != format) {
255 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800256 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800257 }
258
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800259 const bool surfaceControlChanged = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairab066512022-01-04 22:28:00 +0000260 if (surfaceControlChanged && mSurfaceControl != nullptr) {
261 BQA_LOGD("Updating SurfaceControl without recreating BBQ");
262 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800263 bool applyTransaction = false;
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800264
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700265 // Always update the native object even though they might have the same layer handle, so we can
266 // get the updated transform hint from WM.
267 mSurfaceControl = surface;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800268 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800269 if (surfaceControlChanged) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800270 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
271 layer_state_t::eEnableBackpressure);
272 applyTransaction = true;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800273 }
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800274 mTransformHint = mSurfaceControl->getTransformHint();
275 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700276 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
277 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800278
Vishnu Nairea0de002020-11-17 17:42:37 -0800279 ui::Size newSize(width, height);
280 if (mRequestedSize != newSize) {
281 mRequestedSize.set(newSize);
282 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000283 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800284 // If the buffer supports scaling, update the frame immediately since the client may
285 // want to scale the existing buffer to the new size.
286 mSize = mRequestedSize;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800287 if (mUpdateDestinationFrame) {
288 t.setDestinationFrame(mSurfaceControl, Rect(newSize));
289 applyTransaction = true;
290 }
Vishnu Nair53c936c2020-12-03 11:46:37 -0800291 }
Robert Carrfc416512020-04-02 12:32:44 -0700292 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800293 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800294 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
295 t.setApplyToken(mApplyToken).apply(false, true);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800296 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700297}
298
chaviwd7deef72021-10-06 11:53:40 -0500299static std::optional<SurfaceControlStats> findMatchingStat(
300 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
301 for (auto stat : stats) {
302 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
303 return stat;
304 }
305 }
306 return std::nullopt;
307}
308
309static void transactionCommittedCallbackThunk(void* context, nsecs_t latchTime,
310 const sp<Fence>& presentFence,
311 const std::vector<SurfaceControlStats>& stats) {
312 if (context == nullptr) {
313 return;
314 }
315 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
316 bq->transactionCommittedCallback(latchTime, presentFence, stats);
317}
318
319void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
320 const sp<Fence>& /*presentFence*/,
321 const std::vector<SurfaceControlStats>& stats) {
322 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000323 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600324 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500325 BQA_LOGV("transactionCommittedCallback");
326 if (!mSurfaceControlsWithPendingCallback.empty()) {
327 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
328 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
329 if (stat) {
330 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
331
332 // We need to check if we were waiting for a transaction callback in order to
333 // process any pending buffers and unblock. It's possible to get transaction
chaviwc1cf4022022-06-03 13:32:33 -0500334 // callbacks for previous requests so we need to ensure that there are no pending
335 // frame numbers that were in a sync. We remove the frame from mSyncedFrameNumbers
336 // set and then check if it's empty. If there are no more pending syncs, we can
337 // proceed with flushing the shadow queue.
chaviwc1cf4022022-06-03 13:32:33 -0500338 mSyncedFrameNumbers.erase(currFrameNumber);
Chavi Weingartend48797b2023-08-04 13:11:39 +0000339 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500340 flushShadowQueue();
341 }
342 } else {
chaviw768bfa02021-11-01 09:50:57 -0500343 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviwd7deef72021-10-06 11:53:40 -0500344 }
345 } else {
346 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
347 "empty.");
348 }
chaviwd7deef72021-10-06 11:53:40 -0500349 decStrong((void*)transactionCommittedCallbackThunk);
350 }
351}
352
Robert Carr78c25dd2019-08-15 14:10:33 -0700353static void transactionCallbackThunk(void* context, nsecs_t latchTime,
354 const sp<Fence>& presentFence,
355 const std::vector<SurfaceControlStats>& stats) {
356 if (context == nullptr) {
357 return;
358 }
Patrick Williams1a37b732024-08-22 15:00:50 -0500359 auto bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700360 bq->transactionCallback(latchTime, presentFence, stats);
Patrick Williams1a37b732024-08-22 15:00:50 -0500361 bq->decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700362}
363
364void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
365 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700366 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000367 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600368 BBQ_TRACE();
chaviw71c2cc42020-10-23 16:42:02 -0700369 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700370
chaviw42026162021-04-16 15:46:12 -0500371 if (!mSurfaceControlsWithPendingCallback.empty()) {
372 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
373 mSurfaceControlsWithPendingCallback.pop();
chaviwd7deef72021-10-06 11:53:40 -0500374 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
375 if (statsOptional) {
376 SurfaceControlStats stat = *statsOptional;
Vishnu Nair71fcf912022-10-18 09:14:20 -0700377 if (stat.transformHint) {
378 mTransformHint = *stat.transformHint;
379 mBufferItemConsumer->setTransformHint(mTransformHint);
380 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
381 }
Vishnu Nairde66dc72021-06-17 17:54:41 -0700382 // Update frametime stamps if the frame was latched and presented, indicated by a
383 // valid latch time.
384 if (stat.latchTime > 0) {
385 mBufferItemConsumer
386 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
Alec Mouri21d94322023-10-17 19:51:39 +0000387 stat.frameEventStats.previousFrameNumber,
Vishnu Nairde66dc72021-06-17 17:54:41 -0700388 stat.frameEventStats.refreshStartTime,
389 stat.frameEventStats.gpuCompositionDoneFence,
390 stat.presentFence, stat.previousReleaseFence,
391 stat.frameEventStats.compositorTiming,
392 stat.latchTime,
393 stat.frameEventStats.dequeueReadyTime);
394 }
Robert Carr405e2f62021-12-31 16:59:34 -0800395 auto currFrameNumber = stat.frameEventStats.frameNumber;
396 std::vector<ReleaseCallbackId> staleReleases;
397 for (const auto& [key, value]: mSubmitted) {
398 if (currFrameNumber > key.framenumber) {
399 staleReleases.push_back(key);
400 }
401 }
402 for (const auto& staleRelease : staleReleases) {
Robert Carr405e2f62021-12-31 16:59:34 -0800403 releaseBufferCallbackLocked(staleRelease,
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700404 stat.previousReleaseFence
405 ? stat.previousReleaseFence
406 : Fence::NO_FENCE,
407 stat.currentMaxAcquiredBufferCount,
408 true /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800409 }
chaviwd7deef72021-10-06 11:53:40 -0500410 } else {
chaviw768bfa02021-11-01 09:50:57 -0500411 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500412 }
413 } else {
414 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
415 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800416 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700417 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700418}
419
Vishnu Nair1506b182021-02-22 14:35:15 -0800420// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
421// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
422// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
423// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700424static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
chaviw69058fb2021-09-27 09:37:30 -0500425 const sp<Fence>& releaseFence,
426 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800427 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800428 if (blastBufferQueue) {
chaviw69058fb2021-09-27 09:37:30 -0500429 blastBufferQueue->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700430 } else {
431 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800432 }
433}
434
chaviwd7deef72021-10-06 11:53:40 -0500435void BLASTBufferQueue::flushShadowQueue() {
436 BQA_LOGV("flushShadowQueue");
437 int numFramesToFlush = mNumFrameAvailable;
438 while (numFramesToFlush > 0) {
439 acquireNextBufferLocked(std::nullopt);
440 numFramesToFlush--;
441 }
442}
443
chaviw69058fb2021-09-27 09:37:30 -0500444void BLASTBufferQueue::releaseBufferCallback(
445 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
446 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000447 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600448 BBQ_TRACE();
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700449 releaseBufferCallbackLocked(id, releaseFence, currentMaxAcquiredBufferCount,
450 false /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800451}
452
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700453void BLASTBufferQueue::releaseBufferCallbackLocked(
454 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
455 std::optional<uint32_t> currentMaxAcquiredBufferCount, bool fakeRelease) {
Robert Carr405e2f62021-12-31 16:59:34 -0800456 ATRACE_CALL();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700457 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800458
Ady Abraham899dcdb2021-06-15 16:56:21 -0700459 // Calculate how many buffers we need to hold before we release them back
460 // to the buffer queue. This will prevent higher latency when we are running
461 // on a lower refresh rate than the max supported. We only do that for EGL
462 // clients as others don't care about latency
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000463 const auto it = mSubmitted.find(id);
464 const bool isEGL = it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
Ady Abraham899dcdb2021-06-15 16:56:21 -0700465
chaviw69058fb2021-09-27 09:37:30 -0500466 if (currentMaxAcquiredBufferCount) {
467 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
468 }
469
liulijunf90df632022-11-14 14:24:48 +0800470 const uint32_t numPendingBuffersToHold =
471 isEGL ? std::max(0, mMaxAcquiredBuffers - (int32_t)mCurrentMaxAcquiredBufferCount) : 0;
Robert Carr405e2f62021-12-31 16:59:34 -0800472
473 auto rb = ReleasedBuffer{id, releaseFence};
474 if (std::find(mPendingRelease.begin(), mPendingRelease.end(), rb) == mPendingRelease.end()) {
475 mPendingRelease.emplace_back(rb);
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700476 if (fakeRelease) {
477 BQA_LOGE("Faking releaseBufferCallback from transactionCompleteCallback %" PRIu64,
478 id.framenumber);
479 BBQ_TRACE("FakeReleaseCallback");
480 }
Robert Carr405e2f62021-12-31 16:59:34 -0800481 }
Ady Abraham899dcdb2021-06-15 16:56:21 -0700482
483 // Release all buffers that are beyond the ones that we need to hold
484 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500485 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700486 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500487 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwc1cf4022022-06-03 13:32:33 -0500488 // Don't process the transactions here if mSyncedFrameNumbers is not empty. That means
489 // are still transactions that have sync buffers in them that have not been applied or
490 // dropped. Instead, let onFrameAvailable handle processing them since it will merge with
491 // the syncTransaction.
492 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500493 acquireNextBufferLocked(std::nullopt);
494 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800495 }
496
Ady Abraham899dcdb2021-06-15 16:56:21 -0700497 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700498 ATRACE_INT(mQueuedBufferTrace.c_str(),
499 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800500 mCallbackCV.notify_all();
501}
502
chaviw0acd33a2021-11-02 11:55:37 -0500503void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
504 const sp<Fence>& releaseFence) {
505 auto it = mSubmitted.find(callbackId);
506 if (it == mSubmitted.end()) {
Patrick Williams4b9507d2024-07-25 09:55:52 -0500507 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
508 callbackId.to_string().c_str());
chaviw0acd33a2021-11-02 11:55:37 -0500509 return;
510 }
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500511#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
Patrick Williamsca81c052024-08-15 12:38:34 -0500512 if (!it->second.disconnectedAfterAcquired) {
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500513 mNumAcquired--;
514 }
515#else
chaviw0acd33a2021-11-02 11:55:37 -0500516 mNumAcquired--;
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500517#endif
chaviw57ae4b22022-02-03 16:51:39 -0600518 BBQ_TRACE("frame=%" PRIu64, callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500519 BQA_LOGV("released %s", callbackId.to_string().c_str());
520 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
521 mSubmitted.erase(it);
chaviwc1cf4022022-06-03 13:32:33 -0500522 // Remove the frame number from mSyncedFrameNumbers since we can get a release callback
523 // without getting a transaction committed if the buffer was dropped.
524 mSyncedFrameNumbers.erase(callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500525}
526
Chavi Weingarten70670e62023-02-22 17:36:40 +0000527static ui::Size getBufferSize(const BufferItem& item) {
528 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
529 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
530
531 // Take the buffer's orientation into account
532 if (item.mTransform & ui::Transform::ROT_90) {
533 std::swap(bufWidth, bufHeight);
534 }
535 return ui::Size(bufWidth, bufHeight);
536}
537
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000538status_t BLASTBufferQueue::acquireNextBufferLocked(
chaviwd7deef72021-10-06 11:53:40 -0500539 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800540 // Check if we have frames available and we have not acquired the maximum number of buffers.
541 // Even with this check, the consumer can fail to acquire an additional buffer if the consumer
542 // has already acquired (mMaxAcquiredBuffers + 1) and the new buffer is not droppable. In this
543 // case mBufferItemConsumer->acquireBuffer will return with NO_BUFFER_AVAILABLE.
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000544 if (mNumFrameAvailable == 0) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800545 BQA_LOGV("Can't acquire next buffer. No available frames");
546 return BufferQueue::NO_BUFFER_AVAILABLE;
547 }
548
549 if (mNumAcquired >= (mMaxAcquiredBuffers + 2)) {
550 BQA_LOGV("Can't acquire next buffer. Already acquired max frames %d max:%d + 2",
551 mNumAcquired, mMaxAcquiredBuffers);
552 return BufferQueue::NO_BUFFER_AVAILABLE;
Valerie Haud3b90d22019-11-06 09:37:31 -0800553 }
554
Valerie Haua32c5522019-12-09 10:11:08 -0800555 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700556 BQA_LOGE("ERROR : surface control is null");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000557 return NAME_NOT_FOUND;
Valerie Haud3b90d22019-11-06 09:37:31 -0800558 }
559
Robert Carr78c25dd2019-08-15 14:10:33 -0700560 SurfaceComposerClient::Transaction localTransaction;
561 bool applyTransaction = true;
562 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500563 if (transaction) {
564 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700565 applyTransaction = false;
566 }
567
Patrick Williamsca81c052024-08-15 12:38:34 -0500568 BLASTBufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800569
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800570 status_t status =
571 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800572 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
573 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000574 return status;
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800575 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700576 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000577 return status;
Robert Carr78c25dd2019-08-15 14:10:33 -0700578 }
chaviw57ae4b22022-02-03 16:51:39 -0600579
Valerie Haua32c5522019-12-09 10:11:08 -0800580 auto buffer = bufferItem.mGraphicBuffer;
581 mNumFrameAvailable--;
chaviw57ae4b22022-02-03 16:51:39 -0600582 BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800583
584 if (buffer == nullptr) {
585 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700586 BQA_LOGE("Buffer was empty");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000587 return BAD_VALUE;
Valerie Haua32c5522019-12-09 10:11:08 -0800588 }
589
Vishnu Nair670b3f72020-09-29 17:52:18 -0700590 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700591 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800592 "buffer{size=%dx%d transform=%d}",
593 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
594 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
595 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000596 return acquireNextBufferLocked(transaction);
Vishnu Nair670b3f72020-09-29 17:52:18 -0700597 }
598
Valerie Haua32c5522019-12-09 10:11:08 -0800599 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700600 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
601 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
602 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700603
Valerie Hau871d6352020-01-29 08:44:02 -0800604 bool needsDisconnect = false;
605 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
606
607 // if producer disconnected before, notify SurfaceFlinger
608 if (needsDisconnect) {
609 t->notifyProducerDisconnect(mSurfaceControl);
610 }
611
Robert Carr78c25dd2019-08-15 14:10:33 -0700612 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
613 incStrong((void*)transactionCallbackThunk);
614
Chavi Weingarten70670e62023-02-22 17:36:40 +0000615 // Only update mSize for destination bounds if the incoming buffer matches the requested size.
616 // Otherwise, it could cause stretching since the destination bounds will update before the
617 // buffer with the new size is acquired.
Vishnu Nair5b5f6932023-04-12 16:28:19 -0700618 if (mRequestedSize == getBufferSize(bufferItem) ||
619 bufferItem.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Chavi Weingarten70670e62023-02-22 17:36:40 +0000620 mSize = mRequestedSize;
621 }
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700622 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000623 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
624 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700625 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800626
Vishnu Nair1506b182021-02-22 14:35:15 -0800627 auto releaseBufferCallback =
628 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
chaviw69058fb2021-09-27 09:37:30 -0500629 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
chaviwba4320c2021-09-15 15:20:53 -0500630 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900631
632 nsecs_t dequeueTime = -1;
633 {
634 std::lock_guard _lock{mTimestampMutex};
635 auto dequeueTimeIt = mDequeueTimestamps.find(buffer->getId());
636 if (dequeueTimeIt != mDequeueTimestamps.end()) {
637 dequeueTime = dequeueTimeIt->second;
638 mDequeueTimestamps.erase(dequeueTimeIt);
639 }
640 }
641
liulijuneb489f62022-10-17 22:02:14 +0800642 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, mProducerId,
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900643 releaseBufferCallback, dequeueTime);
John Reck137069e2020-12-10 22:07:37 -0500644 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
645 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
646 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700647 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviwf2dace72021-11-17 17:36:50 -0600648
chaviw42026162021-04-16 15:46:12 -0500649 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700650
Vishnu Naird2aaab12022-02-10 14:49:09 -0800651 if (mUpdateDestinationFrame) {
652 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
653 } else {
654 const bool ignoreDestinationFrame =
655 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
656 t->setFlags(mSurfaceControl,
657 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
658 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700659 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700660 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800661 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800662 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800663 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800664 if (!bufferItem.mIsAutoTimestamp) {
665 t->setDesiredPresentTime(bufferItem.mTimestamp);
666 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700667
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800668 // Drop stale frame timeline infos
669 while (!mPendingFrameTimelines.empty() &&
670 mPendingFrameTimelines.front().first < bufferItem.mFrameNumber) {
671 ATRACE_FORMAT_INSTANT("dropping stale frameNumber: %" PRIu64 " vsyncId: %" PRId64,
672 mPendingFrameTimelines.front().first,
673 mPendingFrameTimelines.front().second.vsyncId);
674 mPendingFrameTimelines.pop();
675 }
676
677 if (!mPendingFrameTimelines.empty() &&
678 mPendingFrameTimelines.front().first == bufferItem.mFrameNumber) {
679 ATRACE_FORMAT_INSTANT("Transaction::setFrameTimelineInfo frameNumber: %" PRIu64
680 " vsyncId: %" PRId64,
681 bufferItem.mFrameNumber,
682 mPendingFrameTimelines.front().second.vsyncId);
683 t->setFrameTimelineInfo(mPendingFrameTimelines.front().second);
684 mPendingFrameTimelines.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100685 }
686
chaviw6a195272021-09-03 16:14:25 -0500687 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700688 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800689 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
690 t->setApplyToken(mApplyToken).apply(false, true);
691 mAppliedLastTransaction = true;
692 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
693 } else {
694 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
695 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700696 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700697
chaviwd7deef72021-10-06 11:53:40 -0500698 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800699 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700700 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500701 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800702 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700703 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700704 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000705 return OK;
Robert Carr78c25dd2019-08-15 14:10:33 -0700706}
707
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800708Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
709 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800710 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800711 }
712 return item.mCrop;
713}
714
chaviwd7deef72021-10-06 11:53:40 -0500715void BLASTBufferQueue::acquireAndReleaseBuffer() {
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000716 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500717 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500718 status_t status =
719 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
720 if (status != OK) {
721 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
722 statusToString(status).c_str());
723 return;
724 }
chaviwd7deef72021-10-06 11:53:40 -0500725 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500726 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500727}
728
Vishnu Nairaef1de92020-10-22 12:15:53 -0700729void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000730 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
731 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
chaviwc1cf4022022-06-03 13:32:33 -0500732
Tianhao Yao4861b102022-02-03 20:18:35 +0000733 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000734 UNIQUE_LOCK_WITH_ASSERTION(mMutex);
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000735 BBQ_TRACE();
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000736 bool waitForTransactionCallback = !mSyncedFrameNumbers.empty();
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800737
Tianhao Yao4861b102022-02-03 20:18:35 +0000738 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
739 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800740
Tianhao Yao4861b102022-02-03 20:18:35 +0000741 if (syncTransactionSet) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000742 // If we are going to re-use the same mSyncTransaction, release the buffer that may
743 // already be set in the Transaction. This is to allow us a free slot early to continue
744 // processing a new buffer.
745 if (!mAcquireSingleBuffer) {
746 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
747 if (bufferData) {
748 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
749 bufferData->frameNumber);
750 releaseBuffer(bufferData->generateReleaseCallbackId(),
751 bufferData->acquireFence);
Tianhao Yao4861b102022-02-03 20:18:35 +0000752 }
753 }
chaviw0acd33a2021-11-02 11:55:37 -0500754
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000755 if (waitForTransactionCallback) {
756 // We are waiting on a previous sync's transaction callback so allow another sync
757 // transaction to proceed.
758 //
759 // We need to first flush out the transactions that were in between the two syncs.
760 // We do this by merging them into mSyncTransaction so any buffer merging will get
761 // a release callback invoked.
762 while (mNumFrameAvailable > 0) {
763 // flush out the shadow queue
764 acquireAndReleaseBuffer();
765 }
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800766 } else {
767 // Make sure the frame available count is 0 before proceeding with a sync to ensure
768 // the correct frame is used for the sync. The only way mNumFrameAvailable would be
769 // greater than 0 is if we already ran out of buffers previously. This means we
770 // need to flush the buffers before proceeding with the sync.
771 while (mNumFrameAvailable > 0) {
772 BQA_LOGD("waiting until no queued buffers");
773 mCallbackCV.wait(_lock);
774 }
chaviwd7deef72021-10-06 11:53:40 -0500775 }
776 }
777
Tianhao Yao4861b102022-02-03 20:18:35 +0000778 // add to shadow queue
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500779#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
780 mNumDequeued--;
781#endif
Tianhao Yao4861b102022-02-03 20:18:35 +0000782 mNumFrameAvailable++;
chaviwc1cf4022022-06-03 13:32:33 -0500783 if (waitForTransactionCallback && mNumFrameAvailable >= 2) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000784 acquireAndReleaseBuffer();
785 }
786 ATRACE_INT(mQueuedBufferTrace.c_str(),
787 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
788
789 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
790 item.mFrameNumber, boolToString(syncTransactionSet));
791
792 if (syncTransactionSet) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800793 // Add to mSyncedFrameNumbers before waiting in case any buffers are released
794 // while waiting for a free buffer. The release and commit callback will try to
795 // acquire buffers if there are any available, but we don't want it to acquire
796 // in the case where a sync transaction wants the buffer.
797 mSyncedFrameNumbers.emplace(item.mFrameNumber);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000798 // If there's no available buffer and we're in a sync transaction, we need to wait
799 // instead of returning since we guarantee a buffer will be acquired for the sync.
800 while (acquireNextBufferLocked(mSyncTransaction) == BufferQueue::NO_BUFFER_AVAILABLE) {
801 BQA_LOGD("waiting for available buffer");
802 mCallbackCV.wait(_lock);
803 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000804
805 // Only need a commit callback when syncing to ensure the buffer that's synced has been
806 // sent to SF
807 incStrong((void*)transactionCommittedCallbackThunk);
808 mSyncTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,
809 static_cast<void*>(this));
Tianhao Yao4861b102022-02-03 20:18:35 +0000810 if (mAcquireSingleBuffer) {
811 prevCallback = mTransactionReadyCallback;
812 prevTransaction = mSyncTransaction;
813 mTransactionReadyCallback = nullptr;
814 mSyncTransaction = nullptr;
815 }
chaviwc1cf4022022-06-03 13:32:33 -0500816 } else if (!waitForTransactionCallback) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000817 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800818 }
819 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000820 if (prevCallback) {
821 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500822 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800823}
824
Vishnu Nairaef1de92020-10-22 12:15:53 -0700825void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
826 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
827 // Do nothing since we are not storing unacquired buffer items locally.
828}
829
Vishnu Nairadf632b2021-01-07 14:05:08 -0800830void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000831 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800832 mDequeueTimestamps[bufferId] = systemTime();
Patrick Williams4b9507d2024-07-25 09:55:52 -0500833};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800834
835void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500836 {
837 std::lock_guard _lock{mTimestampMutex};
838 mDequeueTimestamps.erase(bufferId);
839 }
840
841#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
842 {
843 std::lock_guard lock{mMutex};
844 mNumDequeued--;
845 }
846#endif
847}
Vishnu Nairadf632b2021-01-07 14:05:08 -0800848
Chavi Weingartenc398c012023-04-12 17:26:02 +0000849bool BLASTBufferQueue::syncNextTransaction(
Tianhao Yao4861b102022-02-03 20:18:35 +0000850 std::function<void(SurfaceComposerClient::Transaction*)> callback,
851 bool acquireSingleBuffer) {
Chavi Weingartenc398c012023-04-12 17:26:02 +0000852 LOG_ALWAYS_FATAL_IF(!callback,
853 "BLASTBufferQueue: callback passed in to syncNextTransaction must not be "
854 "NULL");
chaviw3b4bdcf2022-03-17 09:27:03 -0500855
Chavi Weingartenc398c012023-04-12 17:26:02 +0000856 std::lock_guard _lock{mMutex};
857 BBQ_TRACE();
858 if (mTransactionReadyCallback) {
859 ALOGW("Attempting to overwrite transaction callback in syncNextTransaction");
860 return false;
Tianhao Yao4861b102022-02-03 20:18:35 +0000861 }
chaviw3b4bdcf2022-03-17 09:27:03 -0500862
Chavi Weingartenc398c012023-04-12 17:26:02 +0000863 mTransactionReadyCallback = callback;
864 mSyncTransaction = new SurfaceComposerClient::Transaction();
865 mAcquireSingleBuffer = acquireSingleBuffer;
866 return true;
Tianhao Yao4861b102022-02-03 20:18:35 +0000867}
868
869void BLASTBufferQueue::stopContinuousSyncTransaction() {
870 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
871 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
872 {
873 std::lock_guard _lock{mMutex};
Chavi Weingartenc398c012023-04-12 17:26:02 +0000874 if (mAcquireSingleBuffer || !mTransactionReadyCallback) {
875 ALOGW("Attempting to stop continuous sync when none are active");
876 return;
Tianhao Yao4861b102022-02-03 20:18:35 +0000877 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000878
879 prevCallback = mTransactionReadyCallback;
880 prevTransaction = mSyncTransaction;
881
Tianhao Yao4861b102022-02-03 20:18:35 +0000882 mTransactionReadyCallback = nullptr;
883 mSyncTransaction = nullptr;
884 mAcquireSingleBuffer = true;
885 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000886
Tianhao Yao4861b102022-02-03 20:18:35 +0000887 if (prevCallback) {
888 prevCallback(prevTransaction);
889 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700890}
891
Chavi Weingartenc398c012023-04-12 17:26:02 +0000892void BLASTBufferQueue::clearSyncTransaction() {
893 std::lock_guard _lock{mMutex};
894 if (!mAcquireSingleBuffer) {
895 ALOGW("Attempting to clear sync transaction when none are active");
896 return;
897 }
898
899 mTransactionReadyCallback = nullptr;
900 mSyncTransaction = nullptr;
901}
902
Vishnu Nairea0de002020-11-17 17:42:37 -0800903bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700904 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
905 // Only reject buffers if scaling mode is freeze.
906 return false;
907 }
908
Chavi Weingarten70670e62023-02-22 17:36:40 +0000909 ui::Size bufferSize = getBufferSize(item);
Vishnu Nairea0de002020-11-17 17:42:37 -0800910 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800911 return false;
912 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700913
Vishnu Nair670b3f72020-09-29 17:52:18 -0700914 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800915 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700916}
Vishnu Nairbf255772020-10-16 10:54:41 -0700917
Robert Carr05086b22020-10-13 18:22:51 -0700918class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700919private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700920 std::mutex mMutex;
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000921 sp<BLASTBufferQueue> mBbq GUARDED_BY(mMutex);
922 bool mDestroyed GUARDED_BY(mMutex) = false;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700923
Robert Carr05086b22020-10-13 18:22:51 -0700924public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700925 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
926 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
927 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700928
Robert Carr05086b22020-10-13 18:22:51 -0700929 void allocateBuffers() override {
930 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
931 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
932 auto gbp = getIGraphicBufferProducer();
933 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
934 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
935 gbp->allocateBuffers(reqWidth, reqHeight,
936 reqFormat, reqUsage);
937
938 }).detach();
939 }
Robert Carr9c006e02020-10-14 13:41:57 -0700940
Marin Shalamanovc5986772021-03-16 16:09:49 +0100941 status_t setFrameRate(float frameRate, int8_t compatibility,
942 int8_t changeFrameRateStrategy) override {
Ady Abraham6cdd3fd2023-09-07 18:45:58 -0700943 if (flags::bq_setframerate()) {
944 return Surface::setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
945 }
946
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000947 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700948 if (mDestroyed) {
949 return DEAD_OBJECT;
950 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100951 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
952 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700953 return BAD_VALUE;
954 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100955 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700956 }
Robert Carr9b611b72020-10-19 12:00:23 -0700957
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800958 status_t setFrameTimelineInfo(uint64_t frameNumber,
959 const FrameTimelineInfo& frameTimelineInfo) override {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000960 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700961 if (mDestroyed) {
962 return DEAD_OBJECT;
963 }
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800964 return mBbq->setFrameTimelineInfo(frameNumber, frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700965 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700966
967 void destroy() override {
968 Surface::destroy();
969
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000970 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700971 mDestroyed = true;
972 mBbq = nullptr;
973 }
Robert Carr05086b22020-10-13 18:22:51 -0700974};
975
Robert Carr9c006e02020-10-14 13:41:57 -0700976// TODO: Can we coalesce this with frame updates? Need to confirm
977// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200978status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
979 bool shouldBeSeamless) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000980 std::lock_guard _lock{mMutex};
Robert Carr9c006e02020-10-14 13:41:57 -0700981 SurfaceComposerClient::Transaction t;
982
Marin Shalamanov46084422020-10-13 12:33:42 +0200983 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700984}
985
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800986status_t BLASTBufferQueue::setFrameTimelineInfo(uint64_t frameNumber,
987 const FrameTimelineInfo& frameTimelineInfo) {
988 ATRACE_FORMAT("%s(%s) frameNumber: %" PRIu64 " vsyncId: %" PRId64, __func__, mName.c_str(),
989 frameNumber, frameTimelineInfo.vsyncId);
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000990 std::lock_guard _lock{mMutex};
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800991 mPendingFrameTimelines.push({frameNumber, frameTimelineInfo});
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100992 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700993}
994
Hongguang Chen621ec582021-02-16 15:42:35 -0800995void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000996 std::lock_guard _lock{mMutex};
Hongguang Chen621ec582021-02-16 15:42:35 -0800997 SurfaceComposerClient::Transaction t;
998
999 t.setSidebandStream(mSurfaceControl, stream).apply();
1000}
1001
Vishnu Nair992496b2020-10-22 17:27:21 -07001002sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001003 std::lock_guard _lock{mMutex};
Vishnu Nair992496b2020-10-22 17:27:21 -07001004 sp<IBinder> scHandle = nullptr;
1005 if (includeSurfaceControlHandle && mSurfaceControl) {
1006 scHandle = mSurfaceControl->getHandle();
1007 }
1008 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -07001009}
1010
Vishnu Nairc4a40c12020-12-23 09:14:32 -08001011void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
1012 uint64_t frameNumber) {
1013 std::lock_guard _lock{mMutex};
1014 if (mLastAcquiredFrameNumber >= frameNumber) {
1015 // Apply the transaction since we have already acquired the desired frame.
1016 t->apply();
1017 } else {
chaviwaad6cf52021-03-23 17:27:20 -05001018 mPendingTransactions.emplace_back(frameNumber, *t);
1019 // Clear the transaction so it can't be applied elsewhere.
1020 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -08001021 }
1022}
1023
chaviw6a195272021-09-03 16:14:25 -05001024void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
1025 std::lock_guard _lock{mMutex};
1026
1027 SurfaceComposerClient::Transaction t;
1028 mergePendingTransactions(&t, frameNumber);
Robert Carr79dc06a2022-02-22 15:28:59 -08001029 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
1030 t.setApplyToken(mApplyToken).apply(false, true);
chaviw6a195272021-09-03 16:14:25 -05001031}
1032
1033void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
1034 uint64_t frameNumber) {
1035 auto mergeTransaction =
1036 [&t, currentFrameNumber = frameNumber](
1037 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
1038 auto& [targetFrameNumber, transaction] = pendingTransaction;
1039 if (currentFrameNumber < targetFrameNumber) {
1040 return false;
1041 }
1042 t->merge(std::move(transaction));
1043 return true;
1044 };
1045
1046 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
1047 mPendingTransactions.end(), mergeTransaction),
1048 mPendingTransactions.end());
1049}
1050
chaviwd84085a2022-02-08 11:07:04 -06001051SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
1052 uint64_t frameNumber) {
1053 std::lock_guard _lock{mMutex};
1054 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
1055 mergePendingTransactions(t, frameNumber);
1056 return t;
1057}
1058
Vishnu Nair89496122020-12-14 17:14:53 -08001059// Maintains a single worker thread per process that services a list of runnables.
1060class AsyncWorker : public Singleton<AsyncWorker> {
1061private:
1062 std::thread mThread;
1063 bool mDone = false;
1064 std::deque<std::function<void()>> mRunnables;
1065 std::mutex mMutex;
1066 std::condition_variable mCv;
1067 void run() {
1068 std::unique_lock<std::mutex> lock(mMutex);
1069 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -08001070 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001071 std::deque<std::function<void()>> runnables = std::move(mRunnables);
1072 mRunnables.clear();
1073 lock.unlock();
1074 // Run outside the lock since the runnable might trigger another
1075 // post to the async worker.
1076 execute(runnables);
1077 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -08001078 }
Wonsik Kim567533e2021-05-04 19:31:29 -07001079 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -08001080 }
1081 }
1082
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001083 void execute(std::deque<std::function<void()>>& runnables) {
1084 while (!runnables.empty()) {
1085 std::function<void()> runnable = runnables.front();
1086 runnables.pop_front();
1087 runnable();
1088 }
1089 }
1090
Vishnu Nair89496122020-12-14 17:14:53 -08001091public:
1092 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
1093
1094 ~AsyncWorker() {
1095 mDone = true;
1096 mCv.notify_all();
1097 if (mThread.joinable()) {
1098 mThread.join();
1099 }
1100 }
1101
1102 void post(std::function<void()> runnable) {
1103 std::unique_lock<std::mutex> lock(mMutex);
1104 mRunnables.emplace_back(std::move(runnable));
1105 mCv.notify_one();
1106 }
1107};
1108ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
1109
1110// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
1111class AsyncProducerListener : public BnProducerListener {
1112private:
1113 const sp<IProducerListener> mListener;
1114
1115public:
1116 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
1117
1118 void onBufferReleased() override {
1119 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
1120 }
1121
1122 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
1123 AsyncWorker::getInstance().post(
1124 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
1125 }
1126};
1127
1128// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
1129// can be non-blocking when the producer is in the client process.
1130class BBQBufferQueueProducer : public BufferQueueProducer {
1131public:
Patrick Williamsca81c052024-08-15 12:38:34 -05001132 BBQBufferQueueProducer(const sp<BufferQueueCore>& core, const wp<BLASTBufferQueue>& bbq)
Brian Lindahlc794b692023-01-31 15:42:47 -07001133 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/),
Patrick Williamsca81c052024-08-15 12:38:34 -05001134 mBLASTBufferQueue(bbq) {}
Vishnu Nair89496122020-12-14 17:14:53 -08001135
1136 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
1137 QueueBufferOutput* output) override {
1138 if (!listener) {
1139 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
1140 }
1141
1142 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
1143 producerControlledByApp, output);
1144 }
Vishnu Nair17dde612020-12-28 11:39:59 -08001145
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001146#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1147 status_t disconnect(int api, DisconnectMode mode) override {
1148 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1149 if (!bbq) {
1150 return BufferQueueProducer::disconnect(api, mode);
1151 }
1152
1153 std::lock_guard lock{bbq->mMutex};
1154 if (status_t status = BufferQueueProducer::disconnect(api, mode); status != OK) {
1155 return status;
1156 }
1157
Patrick Williamsca81c052024-08-15 12:38:34 -05001158 // We need to reset dequeued and acquired counts because BufferQueueProducer::disconnect
1159 // calls BufferQueueCore::freeAllBuffersLocked which frees all dequeued and acquired
1160 // buffers. We don't reset mNumFrameAvailable because these buffers are still available
1161 // in BufferItemConsumer.
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001162 bbq->mNumDequeued = 0;
1163 bbq->mNumAcquired = 0;
Patrick Williamsca81c052024-08-15 12:38:34 -05001164 // SurfaceFlinger sends release callbacks for buffers that have been acquired after a
1165 // disconnect. We set disconnectedAfterAcquired to true so that we can ignore any stale
1166 // releases that come in after the producer is disconnected. Otherwise, releaseBuffer will
1167 // decrement mNumAcquired for a buffer that was acquired before we reset mNumAcquired to
1168 // zero.
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001169 for (auto& [releaseId, bufferItem] : bbq->mSubmitted) {
Patrick Williamsca81c052024-08-15 12:38:34 -05001170 bufferItem.disconnectedAfterAcquired = true;
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001171 }
1172
1173 return OK;
1174 }
1175
1176 status_t setAsyncMode(bool asyncMode) override {
1177 if (status_t status = BufferQueueProducer::setAsyncMode(asyncMode); status != OK) {
1178 return status;
1179 }
1180
1181 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1182 if (!bbq) {
1183 return OK;
1184 }
1185
1186 {
1187 std::lock_guard lock{bbq->mMutex};
1188 bbq->mAsyncMode = asyncMode;
1189 }
1190
1191 return OK;
1192 }
1193
1194 status_t setSharedBufferMode(bool sharedBufferMode) override {
1195 if (status_t status = BufferQueueProducer::setSharedBufferMode(sharedBufferMode);
1196 status != OK) {
1197 return status;
1198 }
1199
1200 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1201 if (!bbq) {
1202 return OK;
1203 }
1204
1205 {
1206 std::lock_guard lock{bbq->mMutex};
1207 bbq->mSharedBufferMode = sharedBufferMode;
1208 }
1209
1210 return OK;
1211 }
1212
1213 status_t detachBuffer(int slot) override {
1214 if (status_t status = BufferQueueProducer::detachBuffer(slot); status != OK) {
1215 return status;
1216 }
1217
1218 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1219 if (!bbq) {
1220 return OK;
1221 }
1222
1223 {
1224 std::lock_guard lock{bbq->mMutex};
1225 bbq->mNumDequeued--;
1226 }
1227
1228 return OK;
1229 }
1230
1231 status_t dequeueBuffer(int* outSlot, sp<Fence>* outFence, uint32_t width, uint32_t height,
1232 PixelFormat format, uint64_t usage, uint64_t* outBufferAge,
1233 FrameEventHistoryDelta* outTimestamps) override {
1234 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1235 if (!bbq) {
1236 return BufferQueueProducer::dequeueBuffer(outSlot, outFence, width, height, format,
1237 usage, outBufferAge, outTimestamps);
1238 }
1239
1240 {
1241 std::lock_guard lock{bbq->mMutex};
1242 bbq->mNumDequeued++;
1243 }
1244
1245 status_t status =
1246 BufferQueueProducer::dequeueBuffer(outSlot, outFence, width, height, format, usage,
1247 outBufferAge, outTimestamps);
1248 if (status < 0) {
1249 std::lock_guard lock{bbq->mMutex};
1250 bbq->mNumDequeued--;
1251 }
1252 return status;
1253 }
1254#endif
1255
Brian Lindahlc794b692023-01-31 15:42:47 -07001256 // We want to resize the frame history when changing the size of the buffer queue
1257 status_t setMaxDequeuedBufferCount(int maxDequeuedBufferCount) override {
1258 int maxBufferCount;
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001259 if (status_t status = BufferQueueProducer::setMaxDequeuedBufferCount(maxDequeuedBufferCount,
1260 &maxBufferCount);
1261 status != OK) {
1262 return status;
Brian Lindahlc794b692023-01-31 15:42:47 -07001263 }
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001264
1265 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1266 if (!bbq) {
1267 return OK;
1268 }
1269
1270 // if we can't determine the max buffer count, then just skip growing the history size
1271 size_t newFrameHistorySize = maxBufferCount + 2; // +2 because triple buffer rendering
1272 // optimize away resizing the frame history unless it will grow
1273 if (newFrameHistorySize > FrameEventHistory::INITIAL_MAX_FRAME_HISTORY) {
1274 ALOGV("increasing frame history size to %zu", newFrameHistorySize);
1275 bbq->resizeFrameEventHistory(newFrameHistorySize);
1276 }
1277
1278#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1279 {
1280 std::lock_guard lock{bbq->mMutex};
1281 bbq->mMaxDequeuedBuffers = maxDequeuedBufferCount;
1282 }
1283#endif
1284
1285 return OK;
Brian Lindahlc794b692023-01-31 15:42:47 -07001286 }
1287
Vishnu Nair17dde612020-12-28 11:39:59 -08001288 int query(int what, int* value) override {
1289 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
1290 *value = 1;
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001291 return OK;
Vishnu Nair17dde612020-12-28 11:39:59 -08001292 }
1293 return BufferQueueProducer::query(what, value);
1294 }
Brian Lindahlc794b692023-01-31 15:42:47 -07001295
1296private:
1297 const wp<BLASTBufferQueue> mBLASTBufferQueue;
Vishnu Nair89496122020-12-14 17:14:53 -08001298};
1299
1300// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
1301// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
1302// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
1303// we can deadlock.
1304void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
1305 sp<IGraphicBufferConsumer>* outConsumer) {
1306 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
1307 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
1308
1309 sp<BufferQueueCore> core(new BufferQueueCore());
1310 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
1311
Brian Lindahlc794b692023-01-31 15:42:47 -07001312 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core, this));
Vishnu Nair89496122020-12-14 17:14:53 -08001313 LOG_ALWAYS_FATAL_IF(producer == nullptr,
1314 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
1315
Vishnu Nair8b30dd12021-01-25 14:16:54 -08001316 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
1317 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -08001318 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
1319 "BLASTBufferQueue: failed to create BufferQueueConsumer");
1320
1321 *outProducer = producer;
1322 *outConsumer = consumer;
1323}
1324
Brian Lindahlc794b692023-01-31 15:42:47 -07001325void BLASTBufferQueue::resizeFrameEventHistory(size_t newSize) {
1326 // This can be null during creation of the buffer queue, but resizing won't do anything at that
1327 // point in time, so just ignore. This can go away once the class relationships and lifetimes of
1328 // objects are cleaned up with a major refactor of BufferQueue as a whole.
1329 if (mBufferItemConsumer != nullptr) {
1330 std::unique_lock _lock{mMutex};
1331 mBufferItemConsumer->resizeFrameEventHistory(newSize);
1332 }
1333}
1334
chaviw497e81c2021-02-04 17:09:47 -08001335PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
1336 PixelFormat convertedFormat = format;
1337 switch (format) {
1338 case PIXEL_FORMAT_TRANSPARENT:
1339 case PIXEL_FORMAT_TRANSLUCENT:
1340 convertedFormat = PIXEL_FORMAT_RGBA_8888;
1341 break;
1342 case PIXEL_FORMAT_OPAQUE:
1343 convertedFormat = PIXEL_FORMAT_RGBX_8888;
1344 break;
1345 }
1346 return convertedFormat;
1347}
1348
Robert Carr82d07c92021-05-10 11:36:43 -07001349uint32_t BLASTBufferQueue::getLastTransformHint() const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001350 std::lock_guard _lock{mMutex};
Robert Carr82d07c92021-05-10 11:36:43 -07001351 if (mSurfaceControl != nullptr) {
1352 return mSurfaceControl->getTransformHint();
1353 } else {
1354 return 0;
1355 }
1356}
1357
chaviw0b020f82021-08-20 12:00:47 -05001358uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001359 std::lock_guard _lock{mMutex};
chaviw0b020f82021-08-20 12:00:47 -05001360 return mLastAcquiredFrameNumber;
1361}
1362
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001363bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001364 std::lock_guard _lock{mMutex};
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001365 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1366}
1367
Patrick Williamsf1e5df12022-10-17 21:37:42 +00001368void BLASTBufferQueue::setTransactionHangCallback(
1369 std::function<void(const std::string&)> callback) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001370 std::lock_guard _lock{mMutex};
Robert Carr4c1b6462021-12-21 10:30:50 -08001371 mTransactionHangCallback = callback;
1372}
1373
Robert Carr78c25dd2019-08-15 14:10:33 -07001374} // namespace android