blob: b8d2b5ffbff9db41dda4b8ee7e5f5e158536fd17 [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
Satish Yalla4aface12024-08-30 09:25:35 +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 }
507 mNumAcquired--;
chaviw57ae4b22022-02-03 16:51:39 -0600508 BBQ_TRACE("frame=%" PRIu64, callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500509 BQA_LOGV("released %s", callbackId.to_string().c_str());
510 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
511 mSubmitted.erase(it);
chaviwc1cf4022022-06-03 13:32:33 -0500512 // Remove the frame number from mSyncedFrameNumbers since we can get a release callback
513 // without getting a transaction committed if the buffer was dropped.
514 mSyncedFrameNumbers.erase(callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500515}
516
Chavi Weingarten70670e62023-02-22 17:36:40 +0000517static ui::Size getBufferSize(const BufferItem& item) {
518 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
519 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
520
521 // Take the buffer's orientation into account
522 if (item.mTransform & ui::Transform::ROT_90) {
523 std::swap(bufWidth, bufHeight);
524 }
525 return ui::Size(bufWidth, bufHeight);
526}
527
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000528status_t BLASTBufferQueue::acquireNextBufferLocked(
chaviwd7deef72021-10-06 11:53:40 -0500529 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800530 // Check if we have frames available and we have not acquired the maximum number of buffers.
531 // Even with this check, the consumer can fail to acquire an additional buffer if the consumer
532 // has already acquired (mMaxAcquiredBuffers + 1) and the new buffer is not droppable. In this
533 // case mBufferItemConsumer->acquireBuffer will return with NO_BUFFER_AVAILABLE.
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000534 if (mNumFrameAvailable == 0) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800535 BQA_LOGV("Can't acquire next buffer. No available frames");
536 return BufferQueue::NO_BUFFER_AVAILABLE;
537 }
538
539 if (mNumAcquired >= (mMaxAcquiredBuffers + 2)) {
540 BQA_LOGV("Can't acquire next buffer. Already acquired max frames %d max:%d + 2",
541 mNumAcquired, mMaxAcquiredBuffers);
542 return BufferQueue::NO_BUFFER_AVAILABLE;
Valerie Haud3b90d22019-11-06 09:37:31 -0800543 }
544
Valerie Haua32c5522019-12-09 10:11:08 -0800545 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700546 BQA_LOGE("ERROR : surface control is null");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000547 return NAME_NOT_FOUND;
Valerie Haud3b90d22019-11-06 09:37:31 -0800548 }
549
Robert Carr78c25dd2019-08-15 14:10:33 -0700550 SurfaceComposerClient::Transaction localTransaction;
551 bool applyTransaction = true;
552 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500553 if (transaction) {
554 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700555 applyTransaction = false;
556 }
557
Patrick Williams3ced5382024-08-21 15:39:32 -0500558 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800559
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800560 status_t status =
561 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800562 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
563 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000564 return status;
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800565 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700566 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000567 return status;
Robert Carr78c25dd2019-08-15 14:10:33 -0700568 }
chaviw57ae4b22022-02-03 16:51:39 -0600569
Valerie Haua32c5522019-12-09 10:11:08 -0800570 auto buffer = bufferItem.mGraphicBuffer;
571 mNumFrameAvailable--;
chaviw57ae4b22022-02-03 16:51:39 -0600572 BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800573
574 if (buffer == nullptr) {
575 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700576 BQA_LOGE("Buffer was empty");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000577 return BAD_VALUE;
Valerie Haua32c5522019-12-09 10:11:08 -0800578 }
579
Vishnu Nair670b3f72020-09-29 17:52:18 -0700580 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700581 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800582 "buffer{size=%dx%d transform=%d}",
583 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
584 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
585 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000586 return acquireNextBufferLocked(transaction);
Vishnu Nair670b3f72020-09-29 17:52:18 -0700587 }
588
Valerie Haua32c5522019-12-09 10:11:08 -0800589 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700590 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
591 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
592 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700593
Valerie Hau871d6352020-01-29 08:44:02 -0800594 bool needsDisconnect = false;
595 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
596
597 // if producer disconnected before, notify SurfaceFlinger
598 if (needsDisconnect) {
599 t->notifyProducerDisconnect(mSurfaceControl);
600 }
601
Chavi Weingarten70670e62023-02-22 17:36:40 +0000602 // Only update mSize for destination bounds if the incoming buffer matches the requested size.
603 // Otherwise, it could cause stretching since the destination bounds will update before the
604 // buffer with the new size is acquired.
Vishnu Nair5b5f6932023-04-12 16:28:19 -0700605 if (mRequestedSize == getBufferSize(bufferItem) ||
606 bufferItem.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Chavi Weingarten70670e62023-02-22 17:36:40 +0000607 mSize = mRequestedSize;
608 }
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700609 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000610 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
611 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700612 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800613
Patrick Williams5312ec12024-08-23 16:11:10 -0500614 auto releaseBufferCallback = makeReleaseBufferCallbackThunk();
chaviwba4320c2021-09-15 15:20:53 -0500615 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900616
617 nsecs_t dequeueTime = -1;
618 {
619 std::lock_guard _lock{mTimestampMutex};
620 auto dequeueTimeIt = mDequeueTimestamps.find(buffer->getId());
621 if (dequeueTimeIt != mDequeueTimestamps.end()) {
622 dequeueTime = dequeueTimeIt->second;
623 mDequeueTimestamps.erase(dequeueTimeIt);
624 }
625 }
626
liulijuneb489f62022-10-17 22:02:14 +0800627 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, mProducerId,
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900628 releaseBufferCallback, dequeueTime);
John Reck137069e2020-12-10 22:07:37 -0500629 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
630 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
631 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Patrick Williams5312ec12024-08-23 16:11:10 -0500632 t->addTransactionCompletedCallback(makeTransactionCallbackThunk(), nullptr);
chaviwf2dace72021-11-17 17:36:50 -0600633
chaviw42026162021-04-16 15:46:12 -0500634 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700635
Vishnu Naird2aaab12022-02-10 14:49:09 -0800636 if (mUpdateDestinationFrame) {
637 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
638 } else {
639 const bool ignoreDestinationFrame =
640 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
641 t->setFlags(mSurfaceControl,
642 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
643 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700644 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700645 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800646 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800647 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800648 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800649 if (!bufferItem.mIsAutoTimestamp) {
650 t->setDesiredPresentTime(bufferItem.mTimestamp);
651 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700652
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800653 // Drop stale frame timeline infos
654 while (!mPendingFrameTimelines.empty() &&
655 mPendingFrameTimelines.front().first < bufferItem.mFrameNumber) {
656 ATRACE_FORMAT_INSTANT("dropping stale frameNumber: %" PRIu64 " vsyncId: %" PRId64,
657 mPendingFrameTimelines.front().first,
658 mPendingFrameTimelines.front().second.vsyncId);
659 mPendingFrameTimelines.pop();
660 }
661
662 if (!mPendingFrameTimelines.empty() &&
663 mPendingFrameTimelines.front().first == bufferItem.mFrameNumber) {
664 ATRACE_FORMAT_INSTANT("Transaction::setFrameTimelineInfo frameNumber: %" PRIu64
665 " vsyncId: %" PRId64,
666 bufferItem.mFrameNumber,
667 mPendingFrameTimelines.front().second.vsyncId);
668 t->setFrameTimelineInfo(mPendingFrameTimelines.front().second);
669 mPendingFrameTimelines.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100670 }
671
chaviw6a195272021-09-03 16:14:25 -0500672 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700673 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800674 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
675 t->setApplyToken(mApplyToken).apply(false, true);
676 mAppliedLastTransaction = true;
677 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
678 } else {
679 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
680 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700681 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700682
chaviwd7deef72021-10-06 11:53:40 -0500683 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800684 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700685 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500686 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800687 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700688 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700689 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000690 return OK;
Robert Carr78c25dd2019-08-15 14:10:33 -0700691}
692
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800693Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
694 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800695 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800696 }
697 return item.mCrop;
698}
699
chaviwd7deef72021-10-06 11:53:40 -0500700void BLASTBufferQueue::acquireAndReleaseBuffer() {
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000701 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500702 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500703 status_t status =
704 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
705 if (status != OK) {
706 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
707 statusToString(status).c_str());
708 return;
709 }
chaviwd7deef72021-10-06 11:53:40 -0500710 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500711 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500712}
713
Vishnu Nairaef1de92020-10-22 12:15:53 -0700714void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000715 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
716 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
chaviwc1cf4022022-06-03 13:32:33 -0500717
Tianhao Yao4861b102022-02-03 20:18:35 +0000718 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000719 UNIQUE_LOCK_WITH_ASSERTION(mMutex);
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000720 BBQ_TRACE();
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000721 bool waitForTransactionCallback = !mSyncedFrameNumbers.empty();
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800722
Tianhao Yao4861b102022-02-03 20:18:35 +0000723 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
724 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800725
Tianhao Yao4861b102022-02-03 20:18:35 +0000726 if (syncTransactionSet) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000727 // If we are going to re-use the same mSyncTransaction, release the buffer that may
728 // already be set in the Transaction. This is to allow us a free slot early to continue
729 // processing a new buffer.
730 if (!mAcquireSingleBuffer) {
731 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
732 if (bufferData) {
733 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
734 bufferData->frameNumber);
735 releaseBuffer(bufferData->generateReleaseCallbackId(),
736 bufferData->acquireFence);
Tianhao Yao4861b102022-02-03 20:18:35 +0000737 }
738 }
chaviw0acd33a2021-11-02 11:55:37 -0500739
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000740 if (waitForTransactionCallback) {
741 // We are waiting on a previous sync's transaction callback so allow another sync
742 // transaction to proceed.
743 //
744 // We need to first flush out the transactions that were in between the two syncs.
745 // We do this by merging them into mSyncTransaction so any buffer merging will get
746 // a release callback invoked.
747 while (mNumFrameAvailable > 0) {
748 // flush out the shadow queue
749 acquireAndReleaseBuffer();
750 }
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800751 } else {
752 // Make sure the frame available count is 0 before proceeding with a sync to ensure
753 // the correct frame is used for the sync. The only way mNumFrameAvailable would be
754 // greater than 0 is if we already ran out of buffers previously. This means we
755 // need to flush the buffers before proceeding with the sync.
756 while (mNumFrameAvailable > 0) {
757 BQA_LOGD("waiting until no queued buffers");
758 mCallbackCV.wait(_lock);
759 }
chaviwd7deef72021-10-06 11:53:40 -0500760 }
761 }
762
Tianhao Yao4861b102022-02-03 20:18:35 +0000763 // add to shadow queue
764 mNumFrameAvailable++;
chaviwc1cf4022022-06-03 13:32:33 -0500765 if (waitForTransactionCallback && mNumFrameAvailable >= 2) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000766 acquireAndReleaseBuffer();
767 }
768 ATRACE_INT(mQueuedBufferTrace.c_str(),
769 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
770
771 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
772 item.mFrameNumber, boolToString(syncTransactionSet));
773
774 if (syncTransactionSet) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800775 // Add to mSyncedFrameNumbers before waiting in case any buffers are released
776 // while waiting for a free buffer. The release and commit callback will try to
777 // acquire buffers if there are any available, but we don't want it to acquire
778 // in the case where a sync transaction wants the buffer.
779 mSyncedFrameNumbers.emplace(item.mFrameNumber);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000780 // If there's no available buffer and we're in a sync transaction, we need to wait
781 // instead of returning since we guarantee a buffer will be acquired for the sync.
782 while (acquireNextBufferLocked(mSyncTransaction) == BufferQueue::NO_BUFFER_AVAILABLE) {
783 BQA_LOGD("waiting for available buffer");
784 mCallbackCV.wait(_lock);
785 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000786
787 // Only need a commit callback when syncing to ensure the buffer that's synced has been
788 // sent to SF
Patrick Williams5312ec12024-08-23 16:11:10 -0500789 mSyncTransaction
790 ->addTransactionCommittedCallback(makeTransactionCommittedCallbackThunk(),
791 nullptr);
Tianhao Yao4861b102022-02-03 20:18:35 +0000792 if (mAcquireSingleBuffer) {
793 prevCallback = mTransactionReadyCallback;
794 prevTransaction = mSyncTransaction;
795 mTransactionReadyCallback = nullptr;
796 mSyncTransaction = nullptr;
797 }
chaviwc1cf4022022-06-03 13:32:33 -0500798 } else if (!waitForTransactionCallback) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000799 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800800 }
801 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000802 if (prevCallback) {
803 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500804 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800805}
806
Vishnu Nairaef1de92020-10-22 12:15:53 -0700807void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
808 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
809 // Do nothing since we are not storing unacquired buffer items locally.
810}
811
Vishnu Nairadf632b2021-01-07 14:05:08 -0800812void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000813 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800814 mDequeueTimestamps[bufferId] = systemTime();
Patrick Williams4b9507d2024-07-25 09:55:52 -0500815};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800816
817void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
Patrick Williams3ced5382024-08-21 15:39:32 -0500818 std::lock_guard _lock{mTimestampMutex};
819 mDequeueTimestamps.erase(bufferId);
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500820}
Vishnu Nairadf632b2021-01-07 14:05:08 -0800821
Chavi Weingartenc398c012023-04-12 17:26:02 +0000822bool BLASTBufferQueue::syncNextTransaction(
Tianhao Yao4861b102022-02-03 20:18:35 +0000823 std::function<void(SurfaceComposerClient::Transaction*)> callback,
824 bool acquireSingleBuffer) {
Chavi Weingartenc398c012023-04-12 17:26:02 +0000825 LOG_ALWAYS_FATAL_IF(!callback,
826 "BLASTBufferQueue: callback passed in to syncNextTransaction must not be "
827 "NULL");
chaviw3b4bdcf2022-03-17 09:27:03 -0500828
Chavi Weingartenc398c012023-04-12 17:26:02 +0000829 std::lock_guard _lock{mMutex};
830 BBQ_TRACE();
831 if (mTransactionReadyCallback) {
832 ALOGW("Attempting to overwrite transaction callback in syncNextTransaction");
833 return false;
Tianhao Yao4861b102022-02-03 20:18:35 +0000834 }
chaviw3b4bdcf2022-03-17 09:27:03 -0500835
Chavi Weingartenc398c012023-04-12 17:26:02 +0000836 mTransactionReadyCallback = callback;
837 mSyncTransaction = new SurfaceComposerClient::Transaction();
838 mAcquireSingleBuffer = acquireSingleBuffer;
839 return true;
Tianhao Yao4861b102022-02-03 20:18:35 +0000840}
841
842void BLASTBufferQueue::stopContinuousSyncTransaction() {
843 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
844 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
845 {
846 std::lock_guard _lock{mMutex};
Chavi Weingartenc398c012023-04-12 17:26:02 +0000847 if (mAcquireSingleBuffer || !mTransactionReadyCallback) {
848 ALOGW("Attempting to stop continuous sync when none are active");
849 return;
Tianhao Yao4861b102022-02-03 20:18:35 +0000850 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000851
852 prevCallback = mTransactionReadyCallback;
853 prevTransaction = mSyncTransaction;
854
Tianhao Yao4861b102022-02-03 20:18:35 +0000855 mTransactionReadyCallback = nullptr;
856 mSyncTransaction = nullptr;
857 mAcquireSingleBuffer = true;
858 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000859
Tianhao Yao4861b102022-02-03 20:18:35 +0000860 if (prevCallback) {
861 prevCallback(prevTransaction);
862 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700863}
864
Chavi Weingartenc398c012023-04-12 17:26:02 +0000865void BLASTBufferQueue::clearSyncTransaction() {
866 std::lock_guard _lock{mMutex};
867 if (!mAcquireSingleBuffer) {
868 ALOGW("Attempting to clear sync transaction when none are active");
869 return;
870 }
871
872 mTransactionReadyCallback = nullptr;
873 mSyncTransaction = nullptr;
874}
875
Vishnu Nairea0de002020-11-17 17:42:37 -0800876bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700877 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
878 // Only reject buffers if scaling mode is freeze.
879 return false;
880 }
881
Chavi Weingarten70670e62023-02-22 17:36:40 +0000882 ui::Size bufferSize = getBufferSize(item);
Vishnu Nairea0de002020-11-17 17:42:37 -0800883 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800884 return false;
885 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700886
Vishnu Nair670b3f72020-09-29 17:52:18 -0700887 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800888 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700889}
Vishnu Nairbf255772020-10-16 10:54:41 -0700890
Robert Carr05086b22020-10-13 18:22:51 -0700891class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700892private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700893 std::mutex mMutex;
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000894 sp<BLASTBufferQueue> mBbq GUARDED_BY(mMutex);
895 bool mDestroyed GUARDED_BY(mMutex) = false;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700896
Robert Carr05086b22020-10-13 18:22:51 -0700897public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700898 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
899 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
900 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700901
Robert Carr05086b22020-10-13 18:22:51 -0700902 void allocateBuffers() override {
903 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
904 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
905 auto gbp = getIGraphicBufferProducer();
906 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
907 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
908 gbp->allocateBuffers(reqWidth, reqHeight,
909 reqFormat, reqUsage);
910
911 }).detach();
912 }
Robert Carr9c006e02020-10-14 13:41:57 -0700913
Marin Shalamanovc5986772021-03-16 16:09:49 +0100914 status_t setFrameRate(float frameRate, int8_t compatibility,
915 int8_t changeFrameRateStrategy) override {
Ady Abraham6cdd3fd2023-09-07 18:45:58 -0700916 if (flags::bq_setframerate()) {
917 return Surface::setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
918 }
919
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000920 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700921 if (mDestroyed) {
922 return DEAD_OBJECT;
923 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100924 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
925 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700926 return BAD_VALUE;
927 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100928 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700929 }
Robert Carr9b611b72020-10-19 12:00:23 -0700930
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800931 status_t setFrameTimelineInfo(uint64_t frameNumber,
932 const FrameTimelineInfo& frameTimelineInfo) override {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000933 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700934 if (mDestroyed) {
935 return DEAD_OBJECT;
936 }
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800937 return mBbq->setFrameTimelineInfo(frameNumber, frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700938 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700939
940 void destroy() override {
941 Surface::destroy();
942
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000943 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700944 mDestroyed = true;
945 mBbq = nullptr;
946 }
Robert Carr05086b22020-10-13 18:22:51 -0700947};
948
Robert Carr9c006e02020-10-14 13:41:57 -0700949// TODO: Can we coalesce this with frame updates? Need to confirm
950// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200951status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
952 bool shouldBeSeamless) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000953 std::lock_guard _lock{mMutex};
Robert Carr9c006e02020-10-14 13:41:57 -0700954 SurfaceComposerClient::Transaction t;
955
Marin Shalamanov46084422020-10-13 12:33:42 +0200956 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700957}
958
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800959status_t BLASTBufferQueue::setFrameTimelineInfo(uint64_t frameNumber,
960 const FrameTimelineInfo& frameTimelineInfo) {
961 ATRACE_FORMAT("%s(%s) frameNumber: %" PRIu64 " vsyncId: %" PRId64, __func__, mName.c_str(),
962 frameNumber, frameTimelineInfo.vsyncId);
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000963 std::lock_guard _lock{mMutex};
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800964 mPendingFrameTimelines.push({frameNumber, frameTimelineInfo});
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100965 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700966}
967
Hongguang Chen621ec582021-02-16 15:42:35 -0800968void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000969 std::lock_guard _lock{mMutex};
Hongguang Chen621ec582021-02-16 15:42:35 -0800970 SurfaceComposerClient::Transaction t;
971
972 t.setSidebandStream(mSurfaceControl, stream).apply();
973}
974
Vishnu Nair992496b2020-10-22 17:27:21 -0700975sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000976 std::lock_guard _lock{mMutex};
Vishnu Nair992496b2020-10-22 17:27:21 -0700977 sp<IBinder> scHandle = nullptr;
978 if (includeSurfaceControlHandle && mSurfaceControl) {
979 scHandle = mSurfaceControl->getHandle();
980 }
981 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700982}
983
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800984void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
985 uint64_t frameNumber) {
986 std::lock_guard _lock{mMutex};
987 if (mLastAcquiredFrameNumber >= frameNumber) {
988 // Apply the transaction since we have already acquired the desired frame.
989 t->apply();
990 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500991 mPendingTransactions.emplace_back(frameNumber, *t);
992 // Clear the transaction so it can't be applied elsewhere.
993 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800994 }
995}
996
chaviw6a195272021-09-03 16:14:25 -0500997void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
998 std::lock_guard _lock{mMutex};
999
1000 SurfaceComposerClient::Transaction t;
1001 mergePendingTransactions(&t, frameNumber);
Robert Carr79dc06a2022-02-22 15:28:59 -08001002 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
1003 t.setApplyToken(mApplyToken).apply(false, true);
chaviw6a195272021-09-03 16:14:25 -05001004}
1005
1006void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
1007 uint64_t frameNumber) {
1008 auto mergeTransaction =
1009 [&t, currentFrameNumber = frameNumber](
1010 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
1011 auto& [targetFrameNumber, transaction] = pendingTransaction;
1012 if (currentFrameNumber < targetFrameNumber) {
1013 return false;
1014 }
1015 t->merge(std::move(transaction));
1016 return true;
1017 };
1018
1019 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
1020 mPendingTransactions.end(), mergeTransaction),
1021 mPendingTransactions.end());
1022}
1023
chaviwd84085a2022-02-08 11:07:04 -06001024SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
1025 uint64_t frameNumber) {
1026 std::lock_guard _lock{mMutex};
1027 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
1028 mergePendingTransactions(t, frameNumber);
1029 return t;
1030}
1031
Vishnu Nair89496122020-12-14 17:14:53 -08001032// Maintains a single worker thread per process that services a list of runnables.
1033class AsyncWorker : public Singleton<AsyncWorker> {
1034private:
1035 std::thread mThread;
1036 bool mDone = false;
1037 std::deque<std::function<void()>> mRunnables;
1038 std::mutex mMutex;
1039 std::condition_variable mCv;
1040 void run() {
1041 std::unique_lock<std::mutex> lock(mMutex);
1042 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -08001043 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001044 std::deque<std::function<void()>> runnables = std::move(mRunnables);
1045 mRunnables.clear();
1046 lock.unlock();
1047 // Run outside the lock since the runnable might trigger another
1048 // post to the async worker.
1049 execute(runnables);
1050 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -08001051 }
Wonsik Kim567533e2021-05-04 19:31:29 -07001052 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -08001053 }
1054 }
1055
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001056 void execute(std::deque<std::function<void()>>& runnables) {
1057 while (!runnables.empty()) {
1058 std::function<void()> runnable = runnables.front();
1059 runnables.pop_front();
1060 runnable();
1061 }
1062 }
1063
Vishnu Nair89496122020-12-14 17:14:53 -08001064public:
1065 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
1066
1067 ~AsyncWorker() {
1068 mDone = true;
1069 mCv.notify_all();
1070 if (mThread.joinable()) {
1071 mThread.join();
1072 }
1073 }
1074
1075 void post(std::function<void()> runnable) {
1076 std::unique_lock<std::mutex> lock(mMutex);
1077 mRunnables.emplace_back(std::move(runnable));
1078 mCv.notify_one();
1079 }
1080};
1081ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
1082
1083// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
1084class AsyncProducerListener : public BnProducerListener {
1085private:
1086 const sp<IProducerListener> mListener;
1087
1088public:
1089 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
1090
1091 void onBufferReleased() override {
1092 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
1093 }
1094
1095 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
1096 AsyncWorker::getInstance().post(
1097 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
1098 }
1099};
1100
1101// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
1102// can be non-blocking when the producer is in the client process.
1103class BBQBufferQueueProducer : public BufferQueueProducer {
1104public:
Patrick Williamsca81c052024-08-15 12:38:34 -05001105 BBQBufferQueueProducer(const sp<BufferQueueCore>& core, const wp<BLASTBufferQueue>& bbq)
Brian Lindahlc794b692023-01-31 15:42:47 -07001106 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/),
Patrick Williamsca81c052024-08-15 12:38:34 -05001107 mBLASTBufferQueue(bbq) {}
Vishnu Nair89496122020-12-14 17:14:53 -08001108
1109 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
1110 QueueBufferOutput* output) override {
1111 if (!listener) {
1112 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
1113 }
1114
1115 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
1116 producerControlledByApp, output);
1117 }
Vishnu Nair17dde612020-12-28 11:39:59 -08001118
Brian Lindahlc794b692023-01-31 15:42:47 -07001119 // We want to resize the frame history when changing the size of the buffer queue
1120 status_t setMaxDequeuedBufferCount(int maxDequeuedBufferCount) override {
1121 int maxBufferCount;
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001122 if (status_t status = BufferQueueProducer::setMaxDequeuedBufferCount(maxDequeuedBufferCount,
1123 &maxBufferCount);
1124 status != OK) {
1125 return status;
Brian Lindahlc794b692023-01-31 15:42:47 -07001126 }
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001127
1128 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1129 if (!bbq) {
1130 return OK;
1131 }
1132
1133 // if we can't determine the max buffer count, then just skip growing the history size
1134 size_t newFrameHistorySize = maxBufferCount + 2; // +2 because triple buffer rendering
1135 // optimize away resizing the frame history unless it will grow
1136 if (newFrameHistorySize > FrameEventHistory::INITIAL_MAX_FRAME_HISTORY) {
1137 ALOGV("increasing frame history size to %zu", newFrameHistorySize);
1138 bbq->resizeFrameEventHistory(newFrameHistorySize);
1139 }
1140
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001141 return OK;
Brian Lindahlc794b692023-01-31 15:42:47 -07001142 }
1143
Vishnu Nair17dde612020-12-28 11:39:59 -08001144 int query(int what, int* value) override {
1145 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
1146 *value = 1;
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001147 return OK;
Vishnu Nair17dde612020-12-28 11:39:59 -08001148 }
1149 return BufferQueueProducer::query(what, value);
1150 }
Brian Lindahlc794b692023-01-31 15:42:47 -07001151
1152private:
1153 const wp<BLASTBufferQueue> mBLASTBufferQueue;
Vishnu Nair89496122020-12-14 17:14:53 -08001154};
1155
1156// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
1157// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
1158// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
1159// we can deadlock.
1160void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
1161 sp<IGraphicBufferConsumer>* outConsumer) {
1162 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
1163 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
1164
1165 sp<BufferQueueCore> core(new BufferQueueCore());
1166 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
1167
Brian Lindahlc794b692023-01-31 15:42:47 -07001168 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core, this));
Vishnu Nair89496122020-12-14 17:14:53 -08001169 LOG_ALWAYS_FATAL_IF(producer == nullptr,
1170 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
1171
Vishnu Nair8b30dd12021-01-25 14:16:54 -08001172 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
1173 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -08001174 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
1175 "BLASTBufferQueue: failed to create BufferQueueConsumer");
1176
1177 *outProducer = producer;
1178 *outConsumer = consumer;
1179}
1180
Brian Lindahlc794b692023-01-31 15:42:47 -07001181void BLASTBufferQueue::resizeFrameEventHistory(size_t newSize) {
1182 // This can be null during creation of the buffer queue, but resizing won't do anything at that
1183 // point in time, so just ignore. This can go away once the class relationships and lifetimes of
1184 // objects are cleaned up with a major refactor of BufferQueue as a whole.
1185 if (mBufferItemConsumer != nullptr) {
1186 std::unique_lock _lock{mMutex};
1187 mBufferItemConsumer->resizeFrameEventHistory(newSize);
1188 }
1189}
1190
chaviw497e81c2021-02-04 17:09:47 -08001191PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
1192 PixelFormat convertedFormat = format;
1193 switch (format) {
1194 case PIXEL_FORMAT_TRANSPARENT:
1195 case PIXEL_FORMAT_TRANSLUCENT:
1196 convertedFormat = PIXEL_FORMAT_RGBA_8888;
1197 break;
1198 case PIXEL_FORMAT_OPAQUE:
1199 convertedFormat = PIXEL_FORMAT_RGBX_8888;
1200 break;
1201 }
1202 return convertedFormat;
1203}
1204
Robert Carr82d07c92021-05-10 11:36:43 -07001205uint32_t BLASTBufferQueue::getLastTransformHint() const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001206 std::lock_guard _lock{mMutex};
Robert Carr82d07c92021-05-10 11:36:43 -07001207 if (mSurfaceControl != nullptr) {
1208 return mSurfaceControl->getTransformHint();
1209 } else {
1210 return 0;
1211 }
1212}
1213
chaviw0b020f82021-08-20 12:00:47 -05001214uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001215 std::lock_guard _lock{mMutex};
chaviw0b020f82021-08-20 12:00:47 -05001216 return mLastAcquiredFrameNumber;
1217}
1218
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001219bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001220 std::lock_guard _lock{mMutex};
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001221 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1222}
1223
Patrick Williamsf1e5df12022-10-17 21:37:42 +00001224void BLASTBufferQueue::setTransactionHangCallback(
1225 std::function<void(const std::string&)> callback) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001226 std::lock_guard _lock{mMutex};
Satish Yalla4aface12024-08-30 09:25:35 +00001227 mTransactionHangCallback = callback;
Robert Carr4c1b6462021-12-21 10:30:50 -08001228}
1229
Robert Carr78c25dd2019-08-15 14:10:33 -07001230} // namespace android