blob: f8e3fd0a5c700b0cffc9d11467674ab18f61e532 [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
Patrick Williams5312ec12024-08-23 16:11:10 -0500309TransactionCompletedCallbackTakesContext BLASTBufferQueue::makeTransactionCommittedCallbackThunk() {
310 return [bbq = sp<BLASTBufferQueue>::fromExisting(
311 this)](void* /*context*/, nsecs_t latchTime, const sp<Fence>& presentFence,
312 const std::vector<SurfaceControlStats>& stats) {
313 bbq->transactionCommittedCallback(latchTime, presentFence, stats);
314 };
chaviwd7deef72021-10-06 11:53:40 -0500315}
316
317void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
318 const sp<Fence>& /*presentFence*/,
319 const std::vector<SurfaceControlStats>& stats) {
320 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000321 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600322 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500323 BQA_LOGV("transactionCommittedCallback");
324 if (!mSurfaceControlsWithPendingCallback.empty()) {
325 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
326 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
327 if (stat) {
328 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
329
330 // We need to check if we were waiting for a transaction callback in order to
331 // process any pending buffers and unblock. It's possible to get transaction
chaviwc1cf4022022-06-03 13:32:33 -0500332 // callbacks for previous requests so we need to ensure that there are no pending
333 // frame numbers that were in a sync. We remove the frame from mSyncedFrameNumbers
334 // set and then check if it's empty. If there are no more pending syncs, we can
335 // proceed with flushing the shadow queue.
chaviwc1cf4022022-06-03 13:32:33 -0500336 mSyncedFrameNumbers.erase(currFrameNumber);
Chavi Weingartend48797b2023-08-04 13:11:39 +0000337 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500338 flushShadowQueue();
339 }
340 } else {
chaviw768bfa02021-11-01 09:50:57 -0500341 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviwd7deef72021-10-06 11:53:40 -0500342 }
343 } else {
344 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
345 "empty.");
346 }
chaviwd7deef72021-10-06 11:53:40 -0500347 }
348}
349
Patrick Williams5312ec12024-08-23 16:11:10 -0500350TransactionCompletedCallbackTakesContext BLASTBufferQueue::makeTransactionCallbackThunk() {
351 return [bbq = sp<BLASTBufferQueue>::fromExisting(
352 this)](void* /*context*/, nsecs_t latchTime, const sp<Fence>& presentFence,
353 const std::vector<SurfaceControlStats>& stats) {
354 bbq->transactionCallback(latchTime, presentFence, stats);
355 };
Robert Carr78c25dd2019-08-15 14:10:33 -0700356}
357
358void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
359 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700360 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000361 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600362 BBQ_TRACE();
chaviw71c2cc42020-10-23 16:42:02 -0700363 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700364
chaviw42026162021-04-16 15:46:12 -0500365 if (!mSurfaceControlsWithPendingCallback.empty()) {
366 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
367 mSurfaceControlsWithPendingCallback.pop();
chaviwd7deef72021-10-06 11:53:40 -0500368 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
369 if (statsOptional) {
370 SurfaceControlStats stat = *statsOptional;
Vishnu Nair71fcf912022-10-18 09:14:20 -0700371 if (stat.transformHint) {
372 mTransformHint = *stat.transformHint;
373 mBufferItemConsumer->setTransformHint(mTransformHint);
374 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
375 }
Vishnu Nairde66dc72021-06-17 17:54:41 -0700376 // Update frametime stamps if the frame was latched and presented, indicated by a
377 // valid latch time.
378 if (stat.latchTime > 0) {
379 mBufferItemConsumer
380 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
Alec Mouri21d94322023-10-17 19:51:39 +0000381 stat.frameEventStats.previousFrameNumber,
Vishnu Nairde66dc72021-06-17 17:54:41 -0700382 stat.frameEventStats.refreshStartTime,
383 stat.frameEventStats.gpuCompositionDoneFence,
384 stat.presentFence, stat.previousReleaseFence,
385 stat.frameEventStats.compositorTiming,
386 stat.latchTime,
387 stat.frameEventStats.dequeueReadyTime);
388 }
Robert Carr405e2f62021-12-31 16:59:34 -0800389 auto currFrameNumber = stat.frameEventStats.frameNumber;
390 std::vector<ReleaseCallbackId> staleReleases;
391 for (const auto& [key, value]: mSubmitted) {
392 if (currFrameNumber > key.framenumber) {
393 staleReleases.push_back(key);
394 }
395 }
396 for (const auto& staleRelease : staleReleases) {
Robert Carr405e2f62021-12-31 16:59:34 -0800397 releaseBufferCallbackLocked(staleRelease,
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700398 stat.previousReleaseFence
399 ? stat.previousReleaseFence
400 : Fence::NO_FENCE,
401 stat.currentMaxAcquiredBufferCount,
402 true /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800403 }
chaviwd7deef72021-10-06 11:53:40 -0500404 } else {
chaviw768bfa02021-11-01 09:50:57 -0500405 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500406 }
407 } else {
408 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
409 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800410 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700411 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700412}
413
Vishnu Nair1506b182021-02-22 14:35:15 -0800414// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
415// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
416// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
417// Otherwise, this is a no-op.
Patrick Williams5312ec12024-08-23 16:11:10 -0500418ReleaseBufferCallback BLASTBufferQueue::makeReleaseBufferCallbackThunk() {
419 return [weakBbq = wp<BLASTBufferQueue>::fromExisting(
420 this)](const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
421 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
422 sp<BLASTBufferQueue> bbq = weakBbq.promote();
423 if (!bbq) {
424 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
425 return;
426 }
427 bbq->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
428 };
Vishnu Nair1506b182021-02-22 14:35:15 -0800429}
430
Priyanka Advani (xWF)8af62f22024-08-28 20:50:11 +0000431void BLASTBufferQueue::flushShadowQueue() {
432 BQA_LOGV("flushShadowQueue");
433 int numFramesToFlush = mNumFrameAvailable;
434 while (numFramesToFlush > 0) {
435 acquireNextBufferLocked(std::nullopt);
436 numFramesToFlush--;
437 }
438}
439
chaviw69058fb2021-09-27 09:37:30 -0500440void BLASTBufferQueue::releaseBufferCallback(
441 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
442 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000443 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600444 BBQ_TRACE();
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700445 releaseBufferCallbackLocked(id, releaseFence, currentMaxAcquiredBufferCount,
446 false /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800447}
448
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700449void BLASTBufferQueue::releaseBufferCallbackLocked(
450 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
451 std::optional<uint32_t> currentMaxAcquiredBufferCount, bool fakeRelease) {
Robert Carr405e2f62021-12-31 16:59:34 -0800452 ATRACE_CALL();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700453 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800454
Ady Abraham899dcdb2021-06-15 16:56:21 -0700455 // Calculate how many buffers we need to hold before we release them back
456 // to the buffer queue. This will prevent higher latency when we are running
457 // on a lower refresh rate than the max supported. We only do that for EGL
458 // clients as others don't care about latency
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000459 const auto it = mSubmitted.find(id);
460 const bool isEGL = it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
Ady Abraham899dcdb2021-06-15 16:56:21 -0700461
chaviw69058fb2021-09-27 09:37:30 -0500462 if (currentMaxAcquiredBufferCount) {
463 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
464 }
465
liulijunf90df632022-11-14 14:24:48 +0800466 const uint32_t numPendingBuffersToHold =
467 isEGL ? std::max(0, mMaxAcquiredBuffers - (int32_t)mCurrentMaxAcquiredBufferCount) : 0;
Robert Carr405e2f62021-12-31 16:59:34 -0800468
469 auto rb = ReleasedBuffer{id, releaseFence};
470 if (std::find(mPendingRelease.begin(), mPendingRelease.end(), rb) == mPendingRelease.end()) {
471 mPendingRelease.emplace_back(rb);
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700472 if (fakeRelease) {
473 BQA_LOGE("Faking releaseBufferCallback from transactionCompleteCallback %" PRIu64,
474 id.framenumber);
475 BBQ_TRACE("FakeReleaseCallback");
476 }
Robert Carr405e2f62021-12-31 16:59:34 -0800477 }
Ady Abraham899dcdb2021-06-15 16:56:21 -0700478
479 // Release all buffers that are beyond the ones that we need to hold
480 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500481 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700482 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500483 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwc1cf4022022-06-03 13:32:33 -0500484 // Don't process the transactions here if mSyncedFrameNumbers is not empty. That means
485 // are still transactions that have sync buffers in them that have not been applied or
486 // dropped. Instead, let onFrameAvailable handle processing them since it will merge with
487 // the syncTransaction.
488 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500489 acquireNextBufferLocked(std::nullopt);
490 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800491 }
492
Ady Abraham899dcdb2021-06-15 16:56:21 -0700493 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700494 ATRACE_INT(mQueuedBufferTrace.c_str(),
495 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800496 mCallbackCV.notify_all();
497}
498
chaviw0acd33a2021-11-02 11:55:37 -0500499void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
500 const sp<Fence>& releaseFence) {
501 auto it = mSubmitted.find(callbackId);
502 if (it == mSubmitted.end()) {
Patrick Williams4b9507d2024-07-25 09:55:52 -0500503 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
504 callbackId.to_string().c_str());
chaviw0acd33a2021-11-02 11:55:37 -0500505 return;
506 }
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500507#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
Patrick Williamsca81c052024-08-15 12:38:34 -0500508 if (!it->second.disconnectedAfterAcquired) {
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500509 mNumAcquired--;
510 }
511#else
chaviw0acd33a2021-11-02 11:55:37 -0500512 mNumAcquired--;
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500513#endif
chaviw57ae4b22022-02-03 16:51:39 -0600514 BBQ_TRACE("frame=%" PRIu64, callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500515 BQA_LOGV("released %s", callbackId.to_string().c_str());
516 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
517 mSubmitted.erase(it);
chaviwc1cf4022022-06-03 13:32:33 -0500518 // Remove the frame number from mSyncedFrameNumbers since we can get a release callback
519 // without getting a transaction committed if the buffer was dropped.
520 mSyncedFrameNumbers.erase(callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500521}
522
Chavi Weingarten70670e62023-02-22 17:36:40 +0000523static ui::Size getBufferSize(const BufferItem& item) {
524 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
525 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
526
527 // Take the buffer's orientation into account
528 if (item.mTransform & ui::Transform::ROT_90) {
529 std::swap(bufWidth, bufHeight);
530 }
531 return ui::Size(bufWidth, bufHeight);
532}
533
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000534status_t BLASTBufferQueue::acquireNextBufferLocked(
chaviwd7deef72021-10-06 11:53:40 -0500535 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800536 // Check if we have frames available and we have not acquired the maximum number of buffers.
537 // Even with this check, the consumer can fail to acquire an additional buffer if the consumer
538 // has already acquired (mMaxAcquiredBuffers + 1) and the new buffer is not droppable. In this
539 // case mBufferItemConsumer->acquireBuffer will return with NO_BUFFER_AVAILABLE.
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000540 if (mNumFrameAvailable == 0) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800541 BQA_LOGV("Can't acquire next buffer. No available frames");
542 return BufferQueue::NO_BUFFER_AVAILABLE;
543 }
544
545 if (mNumAcquired >= (mMaxAcquiredBuffers + 2)) {
546 BQA_LOGV("Can't acquire next buffer. Already acquired max frames %d max:%d + 2",
547 mNumAcquired, mMaxAcquiredBuffers);
548 return BufferQueue::NO_BUFFER_AVAILABLE;
Valerie Haud3b90d22019-11-06 09:37:31 -0800549 }
550
Valerie Haua32c5522019-12-09 10:11:08 -0800551 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700552 BQA_LOGE("ERROR : surface control is null");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000553 return NAME_NOT_FOUND;
Valerie Haud3b90d22019-11-06 09:37:31 -0800554 }
555
Robert Carr78c25dd2019-08-15 14:10:33 -0700556 SurfaceComposerClient::Transaction localTransaction;
557 bool applyTransaction = true;
558 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500559 if (transaction) {
560 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700561 applyTransaction = false;
562 }
563
Patrick Williamsca81c052024-08-15 12:38:34 -0500564 BLASTBufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800565
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800566 status_t status =
567 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800568 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
569 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000570 return status;
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800571 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700572 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000573 return status;
Robert Carr78c25dd2019-08-15 14:10:33 -0700574 }
chaviw57ae4b22022-02-03 16:51:39 -0600575
Valerie Haua32c5522019-12-09 10:11:08 -0800576 auto buffer = bufferItem.mGraphicBuffer;
577 mNumFrameAvailable--;
chaviw57ae4b22022-02-03 16:51:39 -0600578 BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800579
580 if (buffer == nullptr) {
581 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700582 BQA_LOGE("Buffer was empty");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000583 return BAD_VALUE;
Valerie Haua32c5522019-12-09 10:11:08 -0800584 }
585
Vishnu Nair670b3f72020-09-29 17:52:18 -0700586 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700587 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800588 "buffer{size=%dx%d transform=%d}",
589 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
590 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
591 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000592 return acquireNextBufferLocked(transaction);
Vishnu Nair670b3f72020-09-29 17:52:18 -0700593 }
594
Valerie Haua32c5522019-12-09 10:11:08 -0800595 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700596 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
597 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
598 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700599
Valerie Hau871d6352020-01-29 08:44:02 -0800600 bool needsDisconnect = false;
601 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
602
603 // if producer disconnected before, notify SurfaceFlinger
604 if (needsDisconnect) {
605 t->notifyProducerDisconnect(mSurfaceControl);
606 }
607
Chavi Weingarten70670e62023-02-22 17:36:40 +0000608 // Only update mSize for destination bounds if the incoming buffer matches the requested size.
609 // Otherwise, it could cause stretching since the destination bounds will update before the
610 // buffer with the new size is acquired.
Vishnu Nair5b5f6932023-04-12 16:28:19 -0700611 if (mRequestedSize == getBufferSize(bufferItem) ||
612 bufferItem.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Chavi Weingarten70670e62023-02-22 17:36:40 +0000613 mSize = mRequestedSize;
614 }
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700615 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000616 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
617 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700618 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800619
Patrick Williams5312ec12024-08-23 16:11:10 -0500620 auto releaseBufferCallback = makeReleaseBufferCallbackThunk();
chaviwba4320c2021-09-15 15:20:53 -0500621 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900622
623 nsecs_t dequeueTime = -1;
624 {
625 std::lock_guard _lock{mTimestampMutex};
626 auto dequeueTimeIt = mDequeueTimestamps.find(buffer->getId());
627 if (dequeueTimeIt != mDequeueTimestamps.end()) {
628 dequeueTime = dequeueTimeIt->second;
629 mDequeueTimestamps.erase(dequeueTimeIt);
630 }
631 }
632
liulijuneb489f62022-10-17 22:02:14 +0800633 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, mProducerId,
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900634 releaseBufferCallback, dequeueTime);
John Reck137069e2020-12-10 22:07:37 -0500635 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
636 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
637 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Patrick Williams5312ec12024-08-23 16:11:10 -0500638 t->addTransactionCompletedCallback(makeTransactionCallbackThunk(), nullptr);
chaviwf2dace72021-11-17 17:36:50 -0600639
chaviw42026162021-04-16 15:46:12 -0500640 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700641
Vishnu Naird2aaab12022-02-10 14:49:09 -0800642 if (mUpdateDestinationFrame) {
643 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
644 } else {
645 const bool ignoreDestinationFrame =
646 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
647 t->setFlags(mSurfaceControl,
648 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
649 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700650 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700651 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800652 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800653 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800654 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800655 if (!bufferItem.mIsAutoTimestamp) {
656 t->setDesiredPresentTime(bufferItem.mTimestamp);
657 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700658
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800659 // Drop stale frame timeline infos
660 while (!mPendingFrameTimelines.empty() &&
661 mPendingFrameTimelines.front().first < bufferItem.mFrameNumber) {
662 ATRACE_FORMAT_INSTANT("dropping stale frameNumber: %" PRIu64 " vsyncId: %" PRId64,
663 mPendingFrameTimelines.front().first,
664 mPendingFrameTimelines.front().second.vsyncId);
665 mPendingFrameTimelines.pop();
666 }
667
668 if (!mPendingFrameTimelines.empty() &&
669 mPendingFrameTimelines.front().first == bufferItem.mFrameNumber) {
670 ATRACE_FORMAT_INSTANT("Transaction::setFrameTimelineInfo frameNumber: %" PRIu64
671 " vsyncId: %" PRId64,
672 bufferItem.mFrameNumber,
673 mPendingFrameTimelines.front().second.vsyncId);
674 t->setFrameTimelineInfo(mPendingFrameTimelines.front().second);
675 mPendingFrameTimelines.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100676 }
677
chaviw6a195272021-09-03 16:14:25 -0500678 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700679 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800680 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
681 t->setApplyToken(mApplyToken).apply(false, true);
682 mAppliedLastTransaction = true;
683 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
684 } else {
685 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
686 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700687 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700688
chaviwd7deef72021-10-06 11:53:40 -0500689 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800690 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700691 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500692 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800693 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700694 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700695 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000696 return OK;
Robert Carr78c25dd2019-08-15 14:10:33 -0700697}
698
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800699Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
700 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800701 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800702 }
703 return item.mCrop;
704}
705
chaviwd7deef72021-10-06 11:53:40 -0500706void BLASTBufferQueue::acquireAndReleaseBuffer() {
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000707 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500708 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500709 status_t status =
710 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
711 if (status != OK) {
712 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
713 statusToString(status).c_str());
714 return;
715 }
chaviwd7deef72021-10-06 11:53:40 -0500716 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500717 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500718}
719
Vishnu Nairaef1de92020-10-22 12:15:53 -0700720void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000721 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
722 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
chaviwc1cf4022022-06-03 13:32:33 -0500723
Tianhao Yao4861b102022-02-03 20:18:35 +0000724 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000725 UNIQUE_LOCK_WITH_ASSERTION(mMutex);
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000726 BBQ_TRACE();
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000727 bool waitForTransactionCallback = !mSyncedFrameNumbers.empty();
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800728
Tianhao Yao4861b102022-02-03 20:18:35 +0000729 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
730 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800731
Tianhao Yao4861b102022-02-03 20:18:35 +0000732 if (syncTransactionSet) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000733 // If we are going to re-use the same mSyncTransaction, release the buffer that may
734 // already be set in the Transaction. This is to allow us a free slot early to continue
735 // processing a new buffer.
736 if (!mAcquireSingleBuffer) {
737 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
738 if (bufferData) {
739 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
740 bufferData->frameNumber);
741 releaseBuffer(bufferData->generateReleaseCallbackId(),
742 bufferData->acquireFence);
Tianhao Yao4861b102022-02-03 20:18:35 +0000743 }
744 }
chaviw0acd33a2021-11-02 11:55:37 -0500745
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000746 if (waitForTransactionCallback) {
747 // We are waiting on a previous sync's transaction callback so allow another sync
748 // transaction to proceed.
749 //
750 // We need to first flush out the transactions that were in between the two syncs.
751 // We do this by merging them into mSyncTransaction so any buffer merging will get
752 // a release callback invoked.
753 while (mNumFrameAvailable > 0) {
754 // flush out the shadow queue
755 acquireAndReleaseBuffer();
756 }
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800757 } else {
758 // Make sure the frame available count is 0 before proceeding with a sync to ensure
759 // the correct frame is used for the sync. The only way mNumFrameAvailable would be
760 // greater than 0 is if we already ran out of buffers previously. This means we
761 // need to flush the buffers before proceeding with the sync.
762 while (mNumFrameAvailable > 0) {
763 BQA_LOGD("waiting until no queued buffers");
764 mCallbackCV.wait(_lock);
765 }
chaviwd7deef72021-10-06 11:53:40 -0500766 }
767 }
768
Tianhao Yao4861b102022-02-03 20:18:35 +0000769 // add to shadow queue
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500770#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
771 mNumDequeued--;
772#endif
Tianhao Yao4861b102022-02-03 20:18:35 +0000773 mNumFrameAvailable++;
chaviwc1cf4022022-06-03 13:32:33 -0500774 if (waitForTransactionCallback && mNumFrameAvailable >= 2) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000775 acquireAndReleaseBuffer();
776 }
777 ATRACE_INT(mQueuedBufferTrace.c_str(),
778 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
779
780 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
781 item.mFrameNumber, boolToString(syncTransactionSet));
782
783 if (syncTransactionSet) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800784 // Add to mSyncedFrameNumbers before waiting in case any buffers are released
785 // while waiting for a free buffer. The release and commit callback will try to
786 // acquire buffers if there are any available, but we don't want it to acquire
787 // in the case where a sync transaction wants the buffer.
788 mSyncedFrameNumbers.emplace(item.mFrameNumber);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000789 // If there's no available buffer and we're in a sync transaction, we need to wait
790 // instead of returning since we guarantee a buffer will be acquired for the sync.
791 while (acquireNextBufferLocked(mSyncTransaction) == BufferQueue::NO_BUFFER_AVAILABLE) {
792 BQA_LOGD("waiting for available buffer");
793 mCallbackCV.wait(_lock);
794 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000795
796 // Only need a commit callback when syncing to ensure the buffer that's synced has been
797 // sent to SF
Patrick Williams5312ec12024-08-23 16:11:10 -0500798 mSyncTransaction
799 ->addTransactionCommittedCallback(makeTransactionCommittedCallbackThunk(),
800 nullptr);
Tianhao Yao4861b102022-02-03 20:18:35 +0000801 if (mAcquireSingleBuffer) {
802 prevCallback = mTransactionReadyCallback;
803 prevTransaction = mSyncTransaction;
804 mTransactionReadyCallback = nullptr;
805 mSyncTransaction = nullptr;
806 }
chaviwc1cf4022022-06-03 13:32:33 -0500807 } else if (!waitForTransactionCallback) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000808 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800809 }
810 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000811 if (prevCallback) {
812 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500813 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800814}
815
Vishnu Nairaef1de92020-10-22 12:15:53 -0700816void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
817 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
818 // Do nothing since we are not storing unacquired buffer items locally.
819}
820
Vishnu Nairadf632b2021-01-07 14:05:08 -0800821void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000822 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800823 mDequeueTimestamps[bufferId] = systemTime();
Patrick Williams4b9507d2024-07-25 09:55:52 -0500824};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800825
826void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500827 {
828 std::lock_guard _lock{mTimestampMutex};
829 mDequeueTimestamps.erase(bufferId);
830 }
831
832#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
833 {
834 std::lock_guard lock{mMutex};
835 mNumDequeued--;
836 }
837#endif
838}
Vishnu Nairadf632b2021-01-07 14:05:08 -0800839
Chavi Weingartenc398c012023-04-12 17:26:02 +0000840bool BLASTBufferQueue::syncNextTransaction(
Tianhao Yao4861b102022-02-03 20:18:35 +0000841 std::function<void(SurfaceComposerClient::Transaction*)> callback,
842 bool acquireSingleBuffer) {
Chavi Weingartenc398c012023-04-12 17:26:02 +0000843 LOG_ALWAYS_FATAL_IF(!callback,
844 "BLASTBufferQueue: callback passed in to syncNextTransaction must not be "
845 "NULL");
chaviw3b4bdcf2022-03-17 09:27:03 -0500846
Chavi Weingartenc398c012023-04-12 17:26:02 +0000847 std::lock_guard _lock{mMutex};
848 BBQ_TRACE();
849 if (mTransactionReadyCallback) {
850 ALOGW("Attempting to overwrite transaction callback in syncNextTransaction");
851 return false;
Tianhao Yao4861b102022-02-03 20:18:35 +0000852 }
chaviw3b4bdcf2022-03-17 09:27:03 -0500853
Chavi Weingartenc398c012023-04-12 17:26:02 +0000854 mTransactionReadyCallback = callback;
855 mSyncTransaction = new SurfaceComposerClient::Transaction();
856 mAcquireSingleBuffer = acquireSingleBuffer;
857 return true;
Tianhao Yao4861b102022-02-03 20:18:35 +0000858}
859
860void BLASTBufferQueue::stopContinuousSyncTransaction() {
861 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
862 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
863 {
864 std::lock_guard _lock{mMutex};
Chavi Weingartenc398c012023-04-12 17:26:02 +0000865 if (mAcquireSingleBuffer || !mTransactionReadyCallback) {
866 ALOGW("Attempting to stop continuous sync when none are active");
867 return;
Tianhao Yao4861b102022-02-03 20:18:35 +0000868 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000869
870 prevCallback = mTransactionReadyCallback;
871 prevTransaction = mSyncTransaction;
872
Tianhao Yao4861b102022-02-03 20:18:35 +0000873 mTransactionReadyCallback = nullptr;
874 mSyncTransaction = nullptr;
875 mAcquireSingleBuffer = true;
876 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000877
Tianhao Yao4861b102022-02-03 20:18:35 +0000878 if (prevCallback) {
879 prevCallback(prevTransaction);
880 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700881}
882
Chavi Weingartenc398c012023-04-12 17:26:02 +0000883void BLASTBufferQueue::clearSyncTransaction() {
884 std::lock_guard _lock{mMutex};
885 if (!mAcquireSingleBuffer) {
886 ALOGW("Attempting to clear sync transaction when none are active");
887 return;
888 }
889
890 mTransactionReadyCallback = nullptr;
891 mSyncTransaction = nullptr;
892}
893
Vishnu Nairea0de002020-11-17 17:42:37 -0800894bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700895 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
896 // Only reject buffers if scaling mode is freeze.
897 return false;
898 }
899
Chavi Weingarten70670e62023-02-22 17:36:40 +0000900 ui::Size bufferSize = getBufferSize(item);
Vishnu Nairea0de002020-11-17 17:42:37 -0800901 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800902 return false;
903 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700904
Vishnu Nair670b3f72020-09-29 17:52:18 -0700905 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800906 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700907}
Vishnu Nairbf255772020-10-16 10:54:41 -0700908
Robert Carr05086b22020-10-13 18:22:51 -0700909class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700910private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700911 std::mutex mMutex;
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000912 sp<BLASTBufferQueue> mBbq GUARDED_BY(mMutex);
913 bool mDestroyed GUARDED_BY(mMutex) = false;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700914
Robert Carr05086b22020-10-13 18:22:51 -0700915public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700916 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
917 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
918 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700919
Robert Carr05086b22020-10-13 18:22:51 -0700920 void allocateBuffers() override {
921 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
922 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
923 auto gbp = getIGraphicBufferProducer();
924 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
925 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
926 gbp->allocateBuffers(reqWidth, reqHeight,
927 reqFormat, reqUsage);
928
929 }).detach();
930 }
Robert Carr9c006e02020-10-14 13:41:57 -0700931
Marin Shalamanovc5986772021-03-16 16:09:49 +0100932 status_t setFrameRate(float frameRate, int8_t compatibility,
933 int8_t changeFrameRateStrategy) override {
Ady Abraham6cdd3fd2023-09-07 18:45:58 -0700934 if (flags::bq_setframerate()) {
935 return Surface::setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
936 }
937
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000938 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700939 if (mDestroyed) {
940 return DEAD_OBJECT;
941 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100942 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
943 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700944 return BAD_VALUE;
945 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100946 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700947 }
Robert Carr9b611b72020-10-19 12:00:23 -0700948
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800949 status_t setFrameTimelineInfo(uint64_t frameNumber,
950 const FrameTimelineInfo& frameTimelineInfo) override {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000951 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700952 if (mDestroyed) {
953 return DEAD_OBJECT;
954 }
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800955 return mBbq->setFrameTimelineInfo(frameNumber, frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700956 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700957
958 void destroy() override {
959 Surface::destroy();
960
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000961 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700962 mDestroyed = true;
963 mBbq = nullptr;
964 }
Robert Carr05086b22020-10-13 18:22:51 -0700965};
966
Robert Carr9c006e02020-10-14 13:41:57 -0700967// TODO: Can we coalesce this with frame updates? Need to confirm
968// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200969status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
970 bool shouldBeSeamless) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000971 std::lock_guard _lock{mMutex};
Robert Carr9c006e02020-10-14 13:41:57 -0700972 SurfaceComposerClient::Transaction t;
973
Marin Shalamanov46084422020-10-13 12:33:42 +0200974 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700975}
976
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800977status_t BLASTBufferQueue::setFrameTimelineInfo(uint64_t frameNumber,
978 const FrameTimelineInfo& frameTimelineInfo) {
979 ATRACE_FORMAT("%s(%s) frameNumber: %" PRIu64 " vsyncId: %" PRId64, __func__, mName.c_str(),
980 frameNumber, frameTimelineInfo.vsyncId);
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000981 std::lock_guard _lock{mMutex};
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800982 mPendingFrameTimelines.push({frameNumber, frameTimelineInfo});
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100983 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700984}
985
Hongguang Chen621ec582021-02-16 15:42:35 -0800986void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000987 std::lock_guard _lock{mMutex};
Hongguang Chen621ec582021-02-16 15:42:35 -0800988 SurfaceComposerClient::Transaction t;
989
990 t.setSidebandStream(mSurfaceControl, stream).apply();
991}
992
Vishnu Nair992496b2020-10-22 17:27:21 -0700993sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000994 std::lock_guard _lock{mMutex};
Vishnu Nair992496b2020-10-22 17:27:21 -0700995 sp<IBinder> scHandle = nullptr;
996 if (includeSurfaceControlHandle && mSurfaceControl) {
997 scHandle = mSurfaceControl->getHandle();
998 }
999 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -07001000}
1001
Vishnu Nairc4a40c12020-12-23 09:14:32 -08001002void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
1003 uint64_t frameNumber) {
1004 std::lock_guard _lock{mMutex};
1005 if (mLastAcquiredFrameNumber >= frameNumber) {
1006 // Apply the transaction since we have already acquired the desired frame.
1007 t->apply();
1008 } else {
chaviwaad6cf52021-03-23 17:27:20 -05001009 mPendingTransactions.emplace_back(frameNumber, *t);
1010 // Clear the transaction so it can't be applied elsewhere.
1011 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -08001012 }
1013}
1014
chaviw6a195272021-09-03 16:14:25 -05001015void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
1016 std::lock_guard _lock{mMutex};
1017
1018 SurfaceComposerClient::Transaction t;
1019 mergePendingTransactions(&t, frameNumber);
Robert Carr79dc06a2022-02-22 15:28:59 -08001020 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
1021 t.setApplyToken(mApplyToken).apply(false, true);
chaviw6a195272021-09-03 16:14:25 -05001022}
1023
1024void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
1025 uint64_t frameNumber) {
1026 auto mergeTransaction =
1027 [&t, currentFrameNumber = frameNumber](
1028 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
1029 auto& [targetFrameNumber, transaction] = pendingTransaction;
1030 if (currentFrameNumber < targetFrameNumber) {
1031 return false;
1032 }
1033 t->merge(std::move(transaction));
1034 return true;
1035 };
1036
1037 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
1038 mPendingTransactions.end(), mergeTransaction),
1039 mPendingTransactions.end());
1040}
1041
chaviwd84085a2022-02-08 11:07:04 -06001042SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
1043 uint64_t frameNumber) {
1044 std::lock_guard _lock{mMutex};
1045 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
1046 mergePendingTransactions(t, frameNumber);
1047 return t;
1048}
1049
Vishnu Nair89496122020-12-14 17:14:53 -08001050// Maintains a single worker thread per process that services a list of runnables.
1051class AsyncWorker : public Singleton<AsyncWorker> {
1052private:
1053 std::thread mThread;
1054 bool mDone = false;
1055 std::deque<std::function<void()>> mRunnables;
1056 std::mutex mMutex;
1057 std::condition_variable mCv;
1058 void run() {
1059 std::unique_lock<std::mutex> lock(mMutex);
1060 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -08001061 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001062 std::deque<std::function<void()>> runnables = std::move(mRunnables);
1063 mRunnables.clear();
1064 lock.unlock();
1065 // Run outside the lock since the runnable might trigger another
1066 // post to the async worker.
1067 execute(runnables);
1068 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -08001069 }
Wonsik Kim567533e2021-05-04 19:31:29 -07001070 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -08001071 }
1072 }
1073
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001074 void execute(std::deque<std::function<void()>>& runnables) {
1075 while (!runnables.empty()) {
1076 std::function<void()> runnable = runnables.front();
1077 runnables.pop_front();
1078 runnable();
1079 }
1080 }
1081
Vishnu Nair89496122020-12-14 17:14:53 -08001082public:
1083 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
1084
1085 ~AsyncWorker() {
1086 mDone = true;
1087 mCv.notify_all();
1088 if (mThread.joinable()) {
1089 mThread.join();
1090 }
1091 }
1092
1093 void post(std::function<void()> runnable) {
1094 std::unique_lock<std::mutex> lock(mMutex);
1095 mRunnables.emplace_back(std::move(runnable));
1096 mCv.notify_one();
1097 }
1098};
1099ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
1100
1101// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
1102class AsyncProducerListener : public BnProducerListener {
1103private:
1104 const sp<IProducerListener> mListener;
1105
1106public:
1107 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
1108
1109 void onBufferReleased() override {
1110 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
1111 }
1112
1113 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
1114 AsyncWorker::getInstance().post(
1115 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
1116 }
1117};
1118
1119// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
1120// can be non-blocking when the producer is in the client process.
1121class BBQBufferQueueProducer : public BufferQueueProducer {
1122public:
Patrick Williamsca81c052024-08-15 12:38:34 -05001123 BBQBufferQueueProducer(const sp<BufferQueueCore>& core, const wp<BLASTBufferQueue>& bbq)
Brian Lindahlc794b692023-01-31 15:42:47 -07001124 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/),
Patrick Williamsca81c052024-08-15 12:38:34 -05001125 mBLASTBufferQueue(bbq) {}
Vishnu Nair89496122020-12-14 17:14:53 -08001126
1127 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
1128 QueueBufferOutput* output) override {
1129 if (!listener) {
1130 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
1131 }
1132
1133 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
1134 producerControlledByApp, output);
1135 }
Vishnu Nair17dde612020-12-28 11:39:59 -08001136
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001137#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1138 status_t disconnect(int api, DisconnectMode mode) override {
1139 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1140 if (!bbq) {
1141 return BufferQueueProducer::disconnect(api, mode);
1142 }
1143
1144 std::lock_guard lock{bbq->mMutex};
1145 if (status_t status = BufferQueueProducer::disconnect(api, mode); status != OK) {
1146 return status;
1147 }
1148
Patrick Williamsca81c052024-08-15 12:38:34 -05001149 // We need to reset dequeued and acquired counts because BufferQueueProducer::disconnect
1150 // calls BufferQueueCore::freeAllBuffersLocked which frees all dequeued and acquired
1151 // buffers. We don't reset mNumFrameAvailable because these buffers are still available
1152 // in BufferItemConsumer.
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001153 bbq->mNumDequeued = 0;
1154 bbq->mNumAcquired = 0;
Patrick Williamsca81c052024-08-15 12:38:34 -05001155 // SurfaceFlinger sends release callbacks for buffers that have been acquired after a
1156 // disconnect. We set disconnectedAfterAcquired to true so that we can ignore any stale
1157 // releases that come in after the producer is disconnected. Otherwise, releaseBuffer will
1158 // decrement mNumAcquired for a buffer that was acquired before we reset mNumAcquired to
1159 // zero.
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001160 for (auto& [releaseId, bufferItem] : bbq->mSubmitted) {
Patrick Williamsca81c052024-08-15 12:38:34 -05001161 bufferItem.disconnectedAfterAcquired = true;
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001162 }
1163
1164 return OK;
1165 }
1166
1167 status_t setAsyncMode(bool asyncMode) override {
1168 if (status_t status = BufferQueueProducer::setAsyncMode(asyncMode); status != OK) {
1169 return status;
1170 }
1171
1172 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1173 if (!bbq) {
1174 return OK;
1175 }
1176
1177 {
1178 std::lock_guard lock{bbq->mMutex};
1179 bbq->mAsyncMode = asyncMode;
1180 }
1181
1182 return OK;
1183 }
1184
1185 status_t setSharedBufferMode(bool sharedBufferMode) override {
1186 if (status_t status = BufferQueueProducer::setSharedBufferMode(sharedBufferMode);
1187 status != OK) {
1188 return status;
1189 }
1190
1191 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1192 if (!bbq) {
1193 return OK;
1194 }
1195
1196 {
1197 std::lock_guard lock{bbq->mMutex};
1198 bbq->mSharedBufferMode = sharedBufferMode;
1199 }
1200
1201 return OK;
1202 }
1203
1204 status_t detachBuffer(int slot) override {
1205 if (status_t status = BufferQueueProducer::detachBuffer(slot); status != OK) {
1206 return status;
1207 }
1208
1209 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1210 if (!bbq) {
1211 return OK;
1212 }
1213
1214 {
1215 std::lock_guard lock{bbq->mMutex};
1216 bbq->mNumDequeued--;
1217 }
1218
1219 return OK;
1220 }
1221
1222 status_t dequeueBuffer(int* outSlot, sp<Fence>* outFence, uint32_t width, uint32_t height,
1223 PixelFormat format, uint64_t usage, uint64_t* outBufferAge,
1224 FrameEventHistoryDelta* outTimestamps) override {
1225 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1226 if (!bbq) {
1227 return BufferQueueProducer::dequeueBuffer(outSlot, outFence, width, height, format,
1228 usage, outBufferAge, outTimestamps);
1229 }
1230
1231 {
1232 std::lock_guard lock{bbq->mMutex};
1233 bbq->mNumDequeued++;
1234 }
1235
1236 status_t status =
1237 BufferQueueProducer::dequeueBuffer(outSlot, outFence, width, height, format, usage,
1238 outBufferAge, outTimestamps);
1239 if (status < 0) {
1240 std::lock_guard lock{bbq->mMutex};
1241 bbq->mNumDequeued--;
1242 }
1243 return status;
1244 }
1245#endif
1246
Brian Lindahlc794b692023-01-31 15:42:47 -07001247 // We want to resize the frame history when changing the size of the buffer queue
1248 status_t setMaxDequeuedBufferCount(int maxDequeuedBufferCount) override {
1249 int maxBufferCount;
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001250 if (status_t status = BufferQueueProducer::setMaxDequeuedBufferCount(maxDequeuedBufferCount,
1251 &maxBufferCount);
1252 status != OK) {
1253 return status;
Brian Lindahlc794b692023-01-31 15:42:47 -07001254 }
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001255
1256 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1257 if (!bbq) {
1258 return OK;
1259 }
1260
1261 // if we can't determine the max buffer count, then just skip growing the history size
1262 size_t newFrameHistorySize = maxBufferCount + 2; // +2 because triple buffer rendering
1263 // optimize away resizing the frame history unless it will grow
1264 if (newFrameHistorySize > FrameEventHistory::INITIAL_MAX_FRAME_HISTORY) {
1265 ALOGV("increasing frame history size to %zu", newFrameHistorySize);
1266 bbq->resizeFrameEventHistory(newFrameHistorySize);
1267 }
1268
1269#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1270 {
1271 std::lock_guard lock{bbq->mMutex};
1272 bbq->mMaxDequeuedBuffers = maxDequeuedBufferCount;
1273 }
1274#endif
1275
1276 return OK;
Brian Lindahlc794b692023-01-31 15:42:47 -07001277 }
1278
Vishnu Nair17dde612020-12-28 11:39:59 -08001279 int query(int what, int* value) override {
1280 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
1281 *value = 1;
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001282 return OK;
Vishnu Nair17dde612020-12-28 11:39:59 -08001283 }
1284 return BufferQueueProducer::query(what, value);
1285 }
Brian Lindahlc794b692023-01-31 15:42:47 -07001286
1287private:
1288 const wp<BLASTBufferQueue> mBLASTBufferQueue;
Vishnu Nair89496122020-12-14 17:14:53 -08001289};
1290
1291// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
1292// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
1293// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
1294// we can deadlock.
1295void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
1296 sp<IGraphicBufferConsumer>* outConsumer) {
1297 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
1298 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
1299
1300 sp<BufferQueueCore> core(new BufferQueueCore());
1301 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
1302
Brian Lindahlc794b692023-01-31 15:42:47 -07001303 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core, this));
Vishnu Nair89496122020-12-14 17:14:53 -08001304 LOG_ALWAYS_FATAL_IF(producer == nullptr,
1305 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
1306
Vishnu Nair8b30dd12021-01-25 14:16:54 -08001307 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
1308 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -08001309 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
1310 "BLASTBufferQueue: failed to create BufferQueueConsumer");
1311
1312 *outProducer = producer;
1313 *outConsumer = consumer;
1314}
1315
Brian Lindahlc794b692023-01-31 15:42:47 -07001316void BLASTBufferQueue::resizeFrameEventHistory(size_t newSize) {
1317 // This can be null during creation of the buffer queue, but resizing won't do anything at that
1318 // point in time, so just ignore. This can go away once the class relationships and lifetimes of
1319 // objects are cleaned up with a major refactor of BufferQueue as a whole.
1320 if (mBufferItemConsumer != nullptr) {
1321 std::unique_lock _lock{mMutex};
1322 mBufferItemConsumer->resizeFrameEventHistory(newSize);
1323 }
1324}
1325
chaviw497e81c2021-02-04 17:09:47 -08001326PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
1327 PixelFormat convertedFormat = format;
1328 switch (format) {
1329 case PIXEL_FORMAT_TRANSPARENT:
1330 case PIXEL_FORMAT_TRANSLUCENT:
1331 convertedFormat = PIXEL_FORMAT_RGBA_8888;
1332 break;
1333 case PIXEL_FORMAT_OPAQUE:
1334 convertedFormat = PIXEL_FORMAT_RGBX_8888;
1335 break;
1336 }
1337 return convertedFormat;
1338}
1339
Robert Carr82d07c92021-05-10 11:36:43 -07001340uint32_t BLASTBufferQueue::getLastTransformHint() const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001341 std::lock_guard _lock{mMutex};
Robert Carr82d07c92021-05-10 11:36:43 -07001342 if (mSurfaceControl != nullptr) {
1343 return mSurfaceControl->getTransformHint();
1344 } else {
1345 return 0;
1346 }
1347}
1348
chaviw0b020f82021-08-20 12:00:47 -05001349uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001350 std::lock_guard _lock{mMutex};
chaviw0b020f82021-08-20 12:00:47 -05001351 return mLastAcquiredFrameNumber;
1352}
1353
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001354bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001355 std::lock_guard _lock{mMutex};
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001356 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1357}
1358
Patrick Williamsf1e5df12022-10-17 21:37:42 +00001359void BLASTBufferQueue::setTransactionHangCallback(
1360 std::function<void(const std::string&)> callback) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001361 std::lock_guard _lock{mMutex};
Priyanka Advani (xWF)8af62f22024-08-28 20:50:11 +00001362 mTransactionHangCallback = callback;
Robert Carr4c1b6462021-12-21 10:30:50 -08001363}
1364
Robert Carr78c25dd2019-08-15 14:10:33 -07001365} // namespace android