blob: 49f4cba284430d70c8d4c4ced41819c70b3c528f [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>
Patrick Williams7c9fa272024-08-30 12:38:43 +000025#include <ftl/fake_guard.h>
Robert Carr78c25dd2019-08-15 14:10:33 -070026#include <gui/BLASTBufferQueue.h>
27#include <gui/BufferItemConsumer.h>
Vishnu Nair89496122020-12-14 17:14:53 -080028#include <gui/BufferQueueConsumer.h>
29#include <gui/BufferQueueCore.h>
30#include <gui/BufferQueueProducer.h>
Patrick Williams7c9fa272024-08-30 12:38:43 +000031#include <sys/epoll.h>
32#include <sys/eventfd.h>
Ady Abraham107788e2023-10-17 12:31:08 -070033
Ady Abraham6cdd3fd2023-09-07 18:45:58 -070034#include <gui/FrameRateUtils.h>
Valerie Hau45e4b3b2019-12-03 10:49:17 -080035#include <gui/GLConsumer.h>
Vishnu Nair89496122020-12-14 17:14:53 -080036#include <gui/IProducerListener.h>
Robert Carr05086b22020-10-13 18:22:51 -070037#include <gui/Surface.h>
chaviw57ae4b22022-02-03 16:51:39 -060038#include <gui/TraceUtils.h>
Vishnu Nair89496122020-12-14 17:14:53 -080039#include <utils/Singleton.h>
Valerie Haua32c5522019-12-09 10:11:08 -080040#include <utils/Trace.h>
41
Ady Abraham0bde6b52021-05-18 13:57:02 -070042#include <private/gui/ComposerService.h>
Huihong Luo02186fb2022-02-23 14:21:54 -080043#include <private/gui/ComposerServiceAIDL.h>
Ady Abraham0bde6b52021-05-18 13:57:02 -070044
Chavi Weingartene0237bb2023-02-06 21:48:32 +000045#include <android-base/thread_annotations.h>
Robert Carr78c25dd2019-08-15 14:10:33 -070046
Alec Mouri21d94322023-10-17 19:51:39 +000047#include <com_android_graphics_libgui_flags.h>
48
Ady Abraham6cdd3fd2023-09-07 18:45:58 -070049using namespace com::android::graphics::libgui;
Robert Carr78c25dd2019-08-15 14:10:33 -070050using namespace std::chrono_literals;
51
Vishnu Nairdab94092020-09-29 16:09:04 -070052namespace {
Patrick Williams078d7362024-08-27 10:20:39 -050053
54#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
55// RAII wrapper to defer arbitrary work until the Deferred instance is deleted.
56template <class F>
57class Deferred {
58public:
59 explicit Deferred(F f) : mF{std::move(f)} {}
60
61 ~Deferred() { mF(); }
62
63 Deferred(const Deferred&) = delete;
64 Deferred& operator=(const Deferred&) = delete;
65
66private:
67 F mF;
68};
69#endif
70
chaviw3277faf2021-05-19 16:45:23 -050071inline const char* boolToString(bool b) {
Vishnu Nairdab94092020-09-29 16:09:04 -070072 return b ? "true" : "false";
73}
Patrick Williams078d7362024-08-27 10:20:39 -050074
Vishnu Nairdab94092020-09-29 16:09:04 -070075} // namespace
76
Robert Carr78c25dd2019-08-15 14:10:33 -070077namespace android {
78
Vishnu Nairdab94092020-09-29 16:09:04 -070079// Macros to include adapter info in log messages
chaviwd7deef72021-10-06 11:53:40 -050080#define BQA_LOGD(x, ...) \
81 ALOGD("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070082#define BQA_LOGV(x, ...) \
83 ALOGV("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairc6f89ee2020-12-11 14:27:32 -080084// enable logs for a single layer
85//#define BQA_LOGV(x, ...) \
86// ALOGV_IF((strstr(mName.c_str(), "SurfaceView") != nullptr), "[%s](f:%u,a:%u) " x, \
87// mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070088#define BQA_LOGE(x, ...) \
89 ALOGE("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
90
chaviw57ae4b22022-02-03 16:51:39 -060091#define BBQ_TRACE(x, ...) \
92 ATRACE_FORMAT("%s - %s(f:%u,a:%u)" x, __FUNCTION__, mName.c_str(), mNumFrameAvailable, \
93 mNumAcquired, ##__VA_ARGS__)
94
Chavi Weingartene0237bb2023-02-06 21:48:32 +000095#define UNIQUE_LOCK_WITH_ASSERTION(mutex) \
96 std::unique_lock _lock{mutex}; \
97 base::ScopedLockAssertion assumeLocked(mutex);
98
Valerie Hau871d6352020-01-29 08:44:02 -080099void BLASTBufferItemConsumer::onDisconnect() {
Jiakai Zhangc33c63a2021-11-09 11:24:04 +0000100 Mutex::Autolock lock(mMutex);
101 mPreviouslyConnected = mCurrentlyConnected;
102 mCurrentlyConnected = false;
103 if (mPreviouslyConnected) {
104 mDisconnectEvents.push(mCurrentFrameNumber);
Valerie Hau871d6352020-01-29 08:44:02 -0800105 }
Jiakai Zhangc33c63a2021-11-09 11:24:04 +0000106 mFrameEventHistory.onDisconnect();
Valerie Hau871d6352020-01-29 08:44:02 -0800107}
108
109void BLASTBufferItemConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
110 FrameEventHistoryDelta* outDelta) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800111 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800112 if (newTimestamps) {
113 // BufferQueueProducer only adds a new timestamp on
114 // queueBuffer
115 mCurrentFrameNumber = newTimestamps->frameNumber;
116 mFrameEventHistory.addQueue(*newTimestamps);
117 }
118 if (outDelta) {
119 // frame event histories will be processed
120 // only after the producer connects and requests
121 // deltas for the first time. Forward this intent
122 // to SF-side to turn event processing back on
123 mPreviouslyConnected = mCurrentlyConnected;
124 mCurrentlyConnected = true;
125 mFrameEventHistory.getAndResetDelta(outDelta);
126 }
127}
128
Alec Mouri21d94322023-10-17 19:51:39 +0000129void BLASTBufferItemConsumer::updateFrameTimestamps(
130 uint64_t frameNumber, uint64_t previousFrameNumber, nsecs_t refreshStartTime,
131 const sp<Fence>& glDoneFence, const sp<Fence>& presentFence,
132 const sp<Fence>& prevReleaseFence, CompositorTiming compositorTiming, nsecs_t latchTime,
133 nsecs_t dequeueReadyTime) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800134 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800135
136 // if the producer is not connected, don't bother updating,
137 // the next producer that connects won't access this frame event
138 if (!mCurrentlyConnected) return;
139 std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
140 std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
141 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
142
143 mFrameEventHistory.addLatch(frameNumber, latchTime);
Alec Mouri21d94322023-10-17 19:51:39 +0000144 if (flags::frametimestamps_previousrelease()) {
145 if (previousFrameNumber > 0) {
146 mFrameEventHistory.addRelease(previousFrameNumber, dequeueReadyTime,
147 std::move(releaseFenceTime));
148 }
149 } else {
150 mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
151 }
152
Valerie Hau871d6352020-01-29 08:44:02 -0800153 mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
154 mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
155 compositorTiming);
156}
157
158void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
159 bool disconnect = false;
Hongguang Chen621ec582021-02-16 15:42:35 -0800160 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800161 while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
162 disconnect = true;
163 mDisconnectEvents.pop();
164 }
165 if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
166}
167
Hongguang Chen621ec582021-02-16 15:42:35 -0800168void BLASTBufferItemConsumer::onSidebandStreamChanged() {
Ady Abrahamdbca1352021-12-15 11:58:56 -0800169 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
170 if (bbq != nullptr) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800171 sp<NativeHandle> stream = getSidebandStream();
Ady Abrahamdbca1352021-12-15 11:58:56 -0800172 bbq->setSidebandStream(stream);
Hongguang Chen621ec582021-02-16 15:42:35 -0800173 }
174}
175
Ady Abraham107788e2023-10-17 12:31:08 -0700176#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_SETFRAMERATE)
Ady Abraham6cdd3fd2023-09-07 18:45:58 -0700177void BLASTBufferItemConsumer::onSetFrameRate(float frameRate, int8_t compatibility,
178 int8_t changeFrameRateStrategy) {
179 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
180 if (bbq != nullptr) {
181 bbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
182 }
183}
184#endif
185
Brian Lindahlc794b692023-01-31 15:42:47 -0700186void BLASTBufferItemConsumer::resizeFrameEventHistory(size_t newSize) {
187 Mutex::Autolock lock(mMutex);
188 mFrameEventHistory.resize(newSize);
189}
190
Vishnu Naird2aaab12022-02-10 14:49:09 -0800191BLASTBufferQueue::BLASTBufferQueue(const std::string& name, bool updateDestinationFrame)
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800192 : mSurfaceControl(nullptr),
193 mSize(1, 1),
Vishnu Nairea0de002020-11-17 17:42:37 -0800194 mRequestedSize(mSize),
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800195 mFormat(PIXEL_FORMAT_RGBA_8888),
Tianhao Yao4861b102022-02-03 20:18:35 +0000196 mTransactionReadyCallback(nullptr),
Vishnu Naird2aaab12022-02-10 14:49:09 -0800197 mSyncTransaction(nullptr),
198 mUpdateDestinationFrame(updateDestinationFrame) {
Vishnu Nair89496122020-12-14 17:14:53 -0800199 createBufferQueue(&mProducer, &mConsumer);
Jim Shargod30823a2024-07-27 02:49:39 +0000200#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_CONSUMER_BASE_OWNS_BQ)
201 mBufferItemConsumer = new BLASTBufferItemConsumer(mProducer, mConsumer,
202 GraphicBuffer::USAGE_HW_COMPOSER |
203 GraphicBuffer::USAGE_HW_TEXTURE,
204 1, false, this);
205#else
Vishnu Nair1618c672021-02-05 13:08:26 -0800206 mBufferItemConsumer = new BLASTBufferItemConsumer(mConsumer,
207 GraphicBuffer::USAGE_HW_COMPOSER |
208 GraphicBuffer::USAGE_HW_TEXTURE,
Ady Abrahamdbca1352021-12-15 11:58:56 -0800209 1, false, this);
Jim Shargod30823a2024-07-27 02:49:39 +0000210#endif // COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_CONSUMER_BASE_OWNS_BQ)
211 // since the adapter is in the client process, set dequeue timeout
212 // explicitly so that dequeueBuffer will block
213 mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
214
liulijuneb489f62022-10-17 22:02:14 +0800215 static std::atomic<uint32_t> nextId = 0;
216 mProducerId = nextId++;
217 mName = name + "#" + std::to_string(mProducerId);
218 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(mProducerId);
219 mQueuedBufferTrace = "QueuedBuffer - " + mName + "BLAST#" + std::to_string(mProducerId);
Vishnu Nairdab94092020-09-29 16:09:04 -0700220 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700221 mBufferItemConsumer->setFrameAvailableListener(this);
Robert Carr9f133d72020-04-01 15:51:46 -0700222
Huihong Luo02186fb2022-02-23 14:21:54 -0800223 ComposerServiceAIDL::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);
Ady Abraham0bde6b52021-05-18 13:57:02 -0700224 mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
chaviw69058fb2021-09-27 09:37:30 -0500225 mCurrentMaxAcquiredBufferCount = mMaxAcquiredBuffers;
Valerie Haua32c5522019-12-09 10:11:08 -0800226 mNumAcquired = 0;
227 mNumFrameAvailable = 0;
Robert Carr4c1b6462021-12-21 10:30:50 -0800228
229 TransactionCompletedListener::getInstance()->addQueueStallListener(
Patrick Williamsf1e5df12022-10-17 21:37:42 +0000230 [&](const std::string& reason) {
231 std::function<void(const std::string&)> callbackCopy;
232 {
233 std::unique_lock _lock{mMutex};
234 callbackCopy = mTransactionHangCallback;
235 }
236 if (callbackCopy) callbackCopy(reason);
237 },
238 this);
Robert Carr4c1b6462021-12-21 10:30:50 -0800239
Patrick Williams7c9fa272024-08-30 12:38:43 +0000240#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
Patrick Williams078d7362024-08-27 10:20:39 -0500241 gui::BufferReleaseChannel::open(mName, mBufferReleaseConsumer, mBufferReleaseProducer);
242 mBufferReleaseReader.emplace(*this);
Patrick Williams7c9fa272024-08-30 12:38:43 +0000243#endif
244
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800245 BQA_LOGV("BLASTBufferQueue created");
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800246}
247
248BLASTBufferQueue::BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface,
249 int width, int height, int32_t format)
250 : BLASTBufferQueue(name) {
251 update(surface, width, height, format);
Robert Carr78c25dd2019-08-15 14:10:33 -0700252}
253
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800254BLASTBufferQueue::~BLASTBufferQueue() {
Robert Carr4c1b6462021-12-21 10:30:50 -0800255 TransactionCompletedListener::getInstance()->removeQueueStallListener(this);
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800256 if (mPendingTransactions.empty()) {
257 return;
258 }
259 BQA_LOGE("Applying pending transactions on dtor %d",
260 static_cast<uint32_t>(mPendingTransactions.size()));
261 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800262 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
Robert Carr79dc06a2022-02-22 15:28:59 -0800263 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
264 t.setApplyToken(mApplyToken).apply(false, true);
chaviw3b4bdcf2022-03-17 09:27:03 -0500265
266 if (mTransactionReadyCallback) {
267 mTransactionReadyCallback(mSyncTransaction);
268 }
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800269}
270
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500271void BLASTBufferQueue::onFirstRef() {
272 // safe default, most producers are expected to override this
273 mProducer->setMaxDequeuedBufferCount(2);
Patrick Williams7c9fa272024-08-30 12:38:43 +0000274#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
Patrick Williams078d7362024-08-27 10:20:39 -0500275 mBufferReleaseThread.emplace(sp<BLASTBufferQueue>::fromExisting(this));
Patrick Williams7c9fa272024-08-30 12:38:43 +0000276#endif
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500277}
278
chaviw565ee542021-01-14 10:21:23 -0800279void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Naird2aaab12022-02-10 14:49:09 -0800280 int32_t format) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800281 LOG_ALWAYS_FATAL_IF(surface == nullptr, "BLASTBufferQueue: mSurfaceControl must not be NULL");
282
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000283 std::lock_guard _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800284 if (mFormat != format) {
285 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800286 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800287 }
288
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800289 const bool surfaceControlChanged = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairab066512022-01-04 22:28:00 +0000290 if (surfaceControlChanged && mSurfaceControl != nullptr) {
291 BQA_LOGD("Updating SurfaceControl without recreating BBQ");
292 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800293 bool applyTransaction = false;
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800294
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700295 // Always update the native object even though they might have the same layer handle, so we can
296 // get the updated transform hint from WM.
297 mSurfaceControl = surface;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800298 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800299 if (surfaceControlChanged) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800300 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
301 layer_state_t::eEnableBackpressure);
Patrick Williams7c9fa272024-08-30 12:38:43 +0000302#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
303 t.setBufferReleaseChannel(mSurfaceControl, mBufferReleaseProducer);
304#endif
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800305 applyTransaction = true;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800306 }
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800307 mTransformHint = mSurfaceControl->getTransformHint();
308 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700309 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
310 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800311
Vishnu Nairea0de002020-11-17 17:42:37 -0800312 ui::Size newSize(width, height);
313 if (mRequestedSize != newSize) {
314 mRequestedSize.set(newSize);
315 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000316 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800317 // If the buffer supports scaling, update the frame immediately since the client may
318 // want to scale the existing buffer to the new size.
319 mSize = mRequestedSize;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800320 if (mUpdateDestinationFrame) {
321 t.setDestinationFrame(mSurfaceControl, Rect(newSize));
322 applyTransaction = true;
323 }
Vishnu Nair53c936c2020-12-03 11:46:37 -0800324 }
Robert Carrfc416512020-04-02 12:32:44 -0700325 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800326 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800327 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
328 t.setApplyToken(mApplyToken).apply(false, true);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800329 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700330}
331
chaviwd7deef72021-10-06 11:53:40 -0500332static std::optional<SurfaceControlStats> findMatchingStat(
333 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
334 for (auto stat : stats) {
335 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
336 return stat;
337 }
338 }
339 return std::nullopt;
340}
341
Patrick Williams5312ec12024-08-23 16:11:10 -0500342TransactionCompletedCallbackTakesContext BLASTBufferQueue::makeTransactionCommittedCallbackThunk() {
343 return [bbq = sp<BLASTBufferQueue>::fromExisting(
344 this)](void* /*context*/, nsecs_t latchTime, const sp<Fence>& presentFence,
345 const std::vector<SurfaceControlStats>& stats) {
346 bbq->transactionCommittedCallback(latchTime, presentFence, stats);
347 };
chaviwd7deef72021-10-06 11:53:40 -0500348}
349
350void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
351 const sp<Fence>& /*presentFence*/,
352 const std::vector<SurfaceControlStats>& stats) {
353 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000354 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600355 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500356 BQA_LOGV("transactionCommittedCallback");
357 if (!mSurfaceControlsWithPendingCallback.empty()) {
358 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
359 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
360 if (stat) {
361 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
362
363 // We need to check if we were waiting for a transaction callback in order to
364 // process any pending buffers and unblock. It's possible to get transaction
chaviwc1cf4022022-06-03 13:32:33 -0500365 // callbacks for previous requests so we need to ensure that there are no pending
366 // frame numbers that were in a sync. We remove the frame from mSyncedFrameNumbers
367 // set and then check if it's empty. If there are no more pending syncs, we can
368 // proceed with flushing the shadow queue.
chaviwc1cf4022022-06-03 13:32:33 -0500369 mSyncedFrameNumbers.erase(currFrameNumber);
Chavi Weingartend48797b2023-08-04 13:11:39 +0000370 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500371 flushShadowQueue();
372 }
373 } else {
chaviw768bfa02021-11-01 09:50:57 -0500374 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviwd7deef72021-10-06 11:53:40 -0500375 }
376 } else {
377 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
378 "empty.");
379 }
chaviwd7deef72021-10-06 11:53:40 -0500380 }
381}
382
Patrick Williams5312ec12024-08-23 16:11:10 -0500383TransactionCompletedCallbackTakesContext BLASTBufferQueue::makeTransactionCallbackThunk() {
384 return [bbq = sp<BLASTBufferQueue>::fromExisting(
385 this)](void* /*context*/, nsecs_t latchTime, const sp<Fence>& presentFence,
386 const std::vector<SurfaceControlStats>& stats) {
387 bbq->transactionCallback(latchTime, presentFence, stats);
388 };
Robert Carr78c25dd2019-08-15 14:10:33 -0700389}
390
391void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
392 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700393 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000394 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600395 BBQ_TRACE();
chaviw71c2cc42020-10-23 16:42:02 -0700396 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700397
chaviw42026162021-04-16 15:46:12 -0500398 if (!mSurfaceControlsWithPendingCallback.empty()) {
399 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
400 mSurfaceControlsWithPendingCallback.pop();
chaviwd7deef72021-10-06 11:53:40 -0500401 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
402 if (statsOptional) {
403 SurfaceControlStats stat = *statsOptional;
Vishnu Nair71fcf912022-10-18 09:14:20 -0700404 if (stat.transformHint) {
405 mTransformHint = *stat.transformHint;
406 mBufferItemConsumer->setTransformHint(mTransformHint);
407 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
408 }
Vishnu Nairde66dc72021-06-17 17:54:41 -0700409 // Update frametime stamps if the frame was latched and presented, indicated by a
410 // valid latch time.
411 if (stat.latchTime > 0) {
412 mBufferItemConsumer
413 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
Alec Mouri21d94322023-10-17 19:51:39 +0000414 stat.frameEventStats.previousFrameNumber,
Vishnu Nairde66dc72021-06-17 17:54:41 -0700415 stat.frameEventStats.refreshStartTime,
416 stat.frameEventStats.gpuCompositionDoneFence,
417 stat.presentFence, stat.previousReleaseFence,
418 stat.frameEventStats.compositorTiming,
419 stat.latchTime,
420 stat.frameEventStats.dequeueReadyTime);
421 }
Patrick Williams7c9fa272024-08-30 12:38:43 +0000422#if !COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
Robert Carr405e2f62021-12-31 16:59:34 -0800423 auto currFrameNumber = stat.frameEventStats.frameNumber;
424 std::vector<ReleaseCallbackId> staleReleases;
425 for (const auto& [key, value]: mSubmitted) {
426 if (currFrameNumber > key.framenumber) {
427 staleReleases.push_back(key);
428 }
429 }
430 for (const auto& staleRelease : staleReleases) {
Robert Carr405e2f62021-12-31 16:59:34 -0800431 releaseBufferCallbackLocked(staleRelease,
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700432 stat.previousReleaseFence
433 ? stat.previousReleaseFence
434 : Fence::NO_FENCE,
435 stat.currentMaxAcquiredBufferCount,
436 true /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800437 }
Patrick Williams7c9fa272024-08-30 12:38:43 +0000438#endif
chaviwd7deef72021-10-06 11:53:40 -0500439 } else {
chaviw768bfa02021-11-01 09:50:57 -0500440 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500441 }
442 } else {
443 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
444 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800445 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700446 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700447}
448
Patrick Williams7c9fa272024-08-30 12:38:43 +0000449void BLASTBufferQueue::flushShadowQueue() {
450 BQA_LOGV("flushShadowQueue");
451 int numFramesToFlush = mNumFrameAvailable;
452 while (numFramesToFlush > 0) {
453 acquireNextBufferLocked(std::nullopt);
454 numFramesToFlush--;
455 }
456}
457
Vishnu Nair1506b182021-02-22 14:35:15 -0800458// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
459// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
460// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
461// Otherwise, this is a no-op.
Patrick Williams5312ec12024-08-23 16:11:10 -0500462ReleaseBufferCallback BLASTBufferQueue::makeReleaseBufferCallbackThunk() {
463 return [weakBbq = wp<BLASTBufferQueue>::fromExisting(
464 this)](const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
465 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
466 sp<BLASTBufferQueue> bbq = weakBbq.promote();
467 if (!bbq) {
468 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
469 return;
470 }
471 bbq->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
472 };
Vishnu Nair1506b182021-02-22 14:35:15 -0800473}
474
chaviw69058fb2021-09-27 09:37:30 -0500475void BLASTBufferQueue::releaseBufferCallback(
476 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
477 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000478 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600479 BBQ_TRACE();
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700480 releaseBufferCallbackLocked(id, releaseFence, currentMaxAcquiredBufferCount,
481 false /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800482}
483
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700484void BLASTBufferQueue::releaseBufferCallbackLocked(
485 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
486 std::optional<uint32_t> currentMaxAcquiredBufferCount, bool fakeRelease) {
Robert Carr405e2f62021-12-31 16:59:34 -0800487 ATRACE_CALL();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700488 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800489
Ady Abraham899dcdb2021-06-15 16:56:21 -0700490 // Calculate how many buffers we need to hold before we release them back
491 // to the buffer queue. This will prevent higher latency when we are running
492 // on a lower refresh rate than the max supported. We only do that for EGL
493 // clients as others don't care about latency
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000494 const auto it = mSubmitted.find(id);
495 const bool isEGL = it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
Ady Abraham899dcdb2021-06-15 16:56:21 -0700496
chaviw69058fb2021-09-27 09:37:30 -0500497 if (currentMaxAcquiredBufferCount) {
498 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
499 }
500
liulijunf90df632022-11-14 14:24:48 +0800501 const uint32_t numPendingBuffersToHold =
502 isEGL ? std::max(0, mMaxAcquiredBuffers - (int32_t)mCurrentMaxAcquiredBufferCount) : 0;
Robert Carr405e2f62021-12-31 16:59:34 -0800503
504 auto rb = ReleasedBuffer{id, releaseFence};
505 if (std::find(mPendingRelease.begin(), mPendingRelease.end(), rb) == mPendingRelease.end()) {
506 mPendingRelease.emplace_back(rb);
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700507 if (fakeRelease) {
508 BQA_LOGE("Faking releaseBufferCallback from transactionCompleteCallback %" PRIu64,
509 id.framenumber);
510 BBQ_TRACE("FakeReleaseCallback");
511 }
Robert Carr405e2f62021-12-31 16:59:34 -0800512 }
Ady Abraham899dcdb2021-06-15 16:56:21 -0700513
514 // Release all buffers that are beyond the ones that we need to hold
515 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500516 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700517 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500518 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwc1cf4022022-06-03 13:32:33 -0500519 // Don't process the transactions here if mSyncedFrameNumbers is not empty. That means
520 // are still transactions that have sync buffers in them that have not been applied or
521 // dropped. Instead, let onFrameAvailable handle processing them since it will merge with
522 // the syncTransaction.
523 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500524 acquireNextBufferLocked(std::nullopt);
525 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800526 }
527
Ady Abraham899dcdb2021-06-15 16:56:21 -0700528 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700529 ATRACE_INT(mQueuedBufferTrace.c_str(),
530 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800531 mCallbackCV.notify_all();
532}
533
chaviw0acd33a2021-11-02 11:55:37 -0500534void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
535 const sp<Fence>& releaseFence) {
536 auto it = mSubmitted.find(callbackId);
537 if (it == mSubmitted.end()) {
Patrick Williams4b9507d2024-07-25 09:55:52 -0500538 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
539 callbackId.to_string().c_str());
chaviw0acd33a2021-11-02 11:55:37 -0500540 return;
541 }
542 mNumAcquired--;
chaviw57ae4b22022-02-03 16:51:39 -0600543 BBQ_TRACE("frame=%" PRIu64, callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500544 BQA_LOGV("released %s", callbackId.to_string().c_str());
545 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
546 mSubmitted.erase(it);
chaviwc1cf4022022-06-03 13:32:33 -0500547 // Remove the frame number from mSyncedFrameNumbers since we can get a release callback
548 // without getting a transaction committed if the buffer was dropped.
549 mSyncedFrameNumbers.erase(callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500550}
551
Chavi Weingarten70670e62023-02-22 17:36:40 +0000552static ui::Size getBufferSize(const BufferItem& item) {
553 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
554 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
555
556 // Take the buffer's orientation into account
557 if (item.mTransform & ui::Transform::ROT_90) {
558 std::swap(bufWidth, bufHeight);
559 }
560 return ui::Size(bufWidth, bufHeight);
561}
562
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000563status_t BLASTBufferQueue::acquireNextBufferLocked(
chaviwd7deef72021-10-06 11:53:40 -0500564 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800565 // Check if we have frames available and we have not acquired the maximum number of buffers.
566 // Even with this check, the consumer can fail to acquire an additional buffer if the consumer
567 // has already acquired (mMaxAcquiredBuffers + 1) and the new buffer is not droppable. In this
568 // case mBufferItemConsumer->acquireBuffer will return with NO_BUFFER_AVAILABLE.
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000569 if (mNumFrameAvailable == 0) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800570 BQA_LOGV("Can't acquire next buffer. No available frames");
571 return BufferQueue::NO_BUFFER_AVAILABLE;
572 }
573
574 if (mNumAcquired >= (mMaxAcquiredBuffers + 2)) {
575 BQA_LOGV("Can't acquire next buffer. Already acquired max frames %d max:%d + 2",
576 mNumAcquired, mMaxAcquiredBuffers);
577 return BufferQueue::NO_BUFFER_AVAILABLE;
Valerie Haud3b90d22019-11-06 09:37:31 -0800578 }
579
Valerie Haua32c5522019-12-09 10:11:08 -0800580 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700581 BQA_LOGE("ERROR : surface control is null");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000582 return NAME_NOT_FOUND;
Valerie Haud3b90d22019-11-06 09:37:31 -0800583 }
584
Robert Carr78c25dd2019-08-15 14:10:33 -0700585 SurfaceComposerClient::Transaction localTransaction;
586 bool applyTransaction = true;
587 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500588 if (transaction) {
589 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700590 applyTransaction = false;
591 }
592
Patrick Williams3ced5382024-08-21 15:39:32 -0500593 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800594
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800595 status_t status =
596 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800597 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
598 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000599 return status;
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800600 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700601 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000602 return status;
Robert Carr78c25dd2019-08-15 14:10:33 -0700603 }
chaviw57ae4b22022-02-03 16:51:39 -0600604
Valerie Haua32c5522019-12-09 10:11:08 -0800605 auto buffer = bufferItem.mGraphicBuffer;
606 mNumFrameAvailable--;
chaviw57ae4b22022-02-03 16:51:39 -0600607 BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800608
609 if (buffer == nullptr) {
610 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700611 BQA_LOGE("Buffer was empty");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000612 return BAD_VALUE;
Valerie Haua32c5522019-12-09 10:11:08 -0800613 }
614
Vishnu Nair670b3f72020-09-29 17:52:18 -0700615 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700616 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800617 "buffer{size=%dx%d transform=%d}",
618 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
619 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
620 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000621 return acquireNextBufferLocked(transaction);
Vishnu Nair670b3f72020-09-29 17:52:18 -0700622 }
623
Valerie Haua32c5522019-12-09 10:11:08 -0800624 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700625 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
626 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
627 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700628
Valerie Hau871d6352020-01-29 08:44:02 -0800629 bool needsDisconnect = false;
630 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
631
632 // if producer disconnected before, notify SurfaceFlinger
633 if (needsDisconnect) {
634 t->notifyProducerDisconnect(mSurfaceControl);
635 }
636
Chavi Weingarten70670e62023-02-22 17:36:40 +0000637 // Only update mSize for destination bounds if the incoming buffer matches the requested size.
638 // Otherwise, it could cause stretching since the destination bounds will update before the
639 // buffer with the new size is acquired.
Vishnu Nair5b5f6932023-04-12 16:28:19 -0700640 if (mRequestedSize == getBufferSize(bufferItem) ||
641 bufferItem.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Chavi Weingarten70670e62023-02-22 17:36:40 +0000642 mSize = mRequestedSize;
643 }
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700644 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000645 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
646 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700647 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800648
Patrick Williams7c9fa272024-08-30 12:38:43 +0000649#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
650 ReleaseBufferCallback releaseBufferCallback =
Patrick Williams078d7362024-08-27 10:20:39 -0500651 applyTransaction ? nullptr : makeReleaseBufferCallbackThunk();
Patrick Williams7c9fa272024-08-30 12:38:43 +0000652#else
Patrick Williams5312ec12024-08-23 16:11:10 -0500653 auto releaseBufferCallback = makeReleaseBufferCallbackThunk();
Patrick Williams7c9fa272024-08-30 12:38:43 +0000654#endif
chaviwba4320c2021-09-15 15:20:53 -0500655 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900656
657 nsecs_t dequeueTime = -1;
658 {
659 std::lock_guard _lock{mTimestampMutex};
660 auto dequeueTimeIt = mDequeueTimestamps.find(buffer->getId());
661 if (dequeueTimeIt != mDequeueTimestamps.end()) {
662 dequeueTime = dequeueTimeIt->second;
663 mDequeueTimestamps.erase(dequeueTimeIt);
664 }
665 }
666
liulijuneb489f62022-10-17 22:02:14 +0800667 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, mProducerId,
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900668 releaseBufferCallback, dequeueTime);
John Reck137069e2020-12-10 22:07:37 -0500669 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
670 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
671 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Patrick Williams5312ec12024-08-23 16:11:10 -0500672 t->addTransactionCompletedCallback(makeTransactionCallbackThunk(), nullptr);
chaviwf2dace72021-11-17 17:36:50 -0600673
chaviw42026162021-04-16 15:46:12 -0500674 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700675
Vishnu Naird2aaab12022-02-10 14:49:09 -0800676 if (mUpdateDestinationFrame) {
677 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
678 } else {
679 const bool ignoreDestinationFrame =
680 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
681 t->setFlags(mSurfaceControl,
682 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
683 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700684 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700685 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800686 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800687 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800688 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800689 if (!bufferItem.mIsAutoTimestamp) {
690 t->setDesiredPresentTime(bufferItem.mTimestamp);
691 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700692
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800693 // Drop stale frame timeline infos
694 while (!mPendingFrameTimelines.empty() &&
695 mPendingFrameTimelines.front().first < bufferItem.mFrameNumber) {
696 ATRACE_FORMAT_INSTANT("dropping stale frameNumber: %" PRIu64 " vsyncId: %" PRId64,
697 mPendingFrameTimelines.front().first,
698 mPendingFrameTimelines.front().second.vsyncId);
699 mPendingFrameTimelines.pop();
700 }
701
702 if (!mPendingFrameTimelines.empty() &&
703 mPendingFrameTimelines.front().first == bufferItem.mFrameNumber) {
704 ATRACE_FORMAT_INSTANT("Transaction::setFrameTimelineInfo frameNumber: %" PRIu64
705 " vsyncId: %" PRId64,
706 bufferItem.mFrameNumber,
707 mPendingFrameTimelines.front().second.vsyncId);
708 t->setFrameTimelineInfo(mPendingFrameTimelines.front().second);
709 mPendingFrameTimelines.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100710 }
711
chaviw6a195272021-09-03 16:14:25 -0500712 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700713 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800714 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
715 t->setApplyToken(mApplyToken).apply(false, true);
716 mAppliedLastTransaction = true;
717 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
718 } else {
719 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
720 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700721 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700722
chaviwd7deef72021-10-06 11:53:40 -0500723 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800724 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700725 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500726 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800727 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700728 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700729 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000730 return OK;
Robert Carr78c25dd2019-08-15 14:10:33 -0700731}
732
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800733Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
734 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800735 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800736 }
737 return item.mCrop;
738}
739
chaviwd7deef72021-10-06 11:53:40 -0500740void BLASTBufferQueue::acquireAndReleaseBuffer() {
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000741 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500742 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500743 status_t status =
744 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
745 if (status != OK) {
746 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
747 statusToString(status).c_str());
748 return;
749 }
chaviwd7deef72021-10-06 11:53:40 -0500750 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500751 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500752}
753
Vishnu Nairaef1de92020-10-22 12:15:53 -0700754void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000755 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
756 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
chaviwc1cf4022022-06-03 13:32:33 -0500757
Tianhao Yao4861b102022-02-03 20:18:35 +0000758 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000759 UNIQUE_LOCK_WITH_ASSERTION(mMutex);
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000760 BBQ_TRACE();
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000761 bool waitForTransactionCallback = !mSyncedFrameNumbers.empty();
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800762
Tianhao Yao4861b102022-02-03 20:18:35 +0000763 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
764 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800765
Tianhao Yao4861b102022-02-03 20:18:35 +0000766 if (syncTransactionSet) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000767 // If we are going to re-use the same mSyncTransaction, release the buffer that may
768 // already be set in the Transaction. This is to allow us a free slot early to continue
769 // processing a new buffer.
770 if (!mAcquireSingleBuffer) {
771 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
772 if (bufferData) {
773 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
774 bufferData->frameNumber);
775 releaseBuffer(bufferData->generateReleaseCallbackId(),
776 bufferData->acquireFence);
Tianhao Yao4861b102022-02-03 20:18:35 +0000777 }
778 }
chaviw0acd33a2021-11-02 11:55:37 -0500779
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000780 if (waitForTransactionCallback) {
781 // We are waiting on a previous sync's transaction callback so allow another sync
782 // transaction to proceed.
783 //
784 // We need to first flush out the transactions that were in between the two syncs.
785 // We do this by merging them into mSyncTransaction so any buffer merging will get
786 // a release callback invoked.
787 while (mNumFrameAvailable > 0) {
788 // flush out the shadow queue
789 acquireAndReleaseBuffer();
790 }
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800791 } else {
792 // Make sure the frame available count is 0 before proceeding with a sync to ensure
793 // the correct frame is used for the sync. The only way mNumFrameAvailable would be
794 // greater than 0 is if we already ran out of buffers previously. This means we
795 // need to flush the buffers before proceeding with the sync.
796 while (mNumFrameAvailable > 0) {
797 BQA_LOGD("waiting until no queued buffers");
798 mCallbackCV.wait(_lock);
799 }
chaviwd7deef72021-10-06 11:53:40 -0500800 }
801 }
802
Tianhao Yao4861b102022-02-03 20:18:35 +0000803 // add to shadow queue
804 mNumFrameAvailable++;
chaviwc1cf4022022-06-03 13:32:33 -0500805 if (waitForTransactionCallback && mNumFrameAvailable >= 2) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000806 acquireAndReleaseBuffer();
807 }
808 ATRACE_INT(mQueuedBufferTrace.c_str(),
809 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
810
811 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
812 item.mFrameNumber, boolToString(syncTransactionSet));
813
814 if (syncTransactionSet) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800815 // Add to mSyncedFrameNumbers before waiting in case any buffers are released
816 // while waiting for a free buffer. The release and commit callback will try to
817 // acquire buffers if there are any available, but we don't want it to acquire
818 // in the case where a sync transaction wants the buffer.
819 mSyncedFrameNumbers.emplace(item.mFrameNumber);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000820 // If there's no available buffer and we're in a sync transaction, we need to wait
821 // instead of returning since we guarantee a buffer will be acquired for the sync.
822 while (acquireNextBufferLocked(mSyncTransaction) == BufferQueue::NO_BUFFER_AVAILABLE) {
823 BQA_LOGD("waiting for available buffer");
824 mCallbackCV.wait(_lock);
825 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000826
827 // Only need a commit callback when syncing to ensure the buffer that's synced has been
828 // sent to SF
Patrick Williams5312ec12024-08-23 16:11:10 -0500829 mSyncTransaction
830 ->addTransactionCommittedCallback(makeTransactionCommittedCallbackThunk(),
831 nullptr);
Tianhao Yao4861b102022-02-03 20:18:35 +0000832 if (mAcquireSingleBuffer) {
833 prevCallback = mTransactionReadyCallback;
834 prevTransaction = mSyncTransaction;
835 mTransactionReadyCallback = nullptr;
836 mSyncTransaction = nullptr;
837 }
chaviwc1cf4022022-06-03 13:32:33 -0500838 } else if (!waitForTransactionCallback) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000839 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800840 }
841 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000842 if (prevCallback) {
843 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500844 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800845}
846
Vishnu Nairaef1de92020-10-22 12:15:53 -0700847void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
848 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
849 // Do nothing since we are not storing unacquired buffer items locally.
850}
851
Vishnu Nairadf632b2021-01-07 14:05:08 -0800852void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000853 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800854 mDequeueTimestamps[bufferId] = systemTime();
Patrick Williams4b9507d2024-07-25 09:55:52 -0500855};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800856
857void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
Patrick Williams3ced5382024-08-21 15:39:32 -0500858 std::lock_guard _lock{mTimestampMutex};
859 mDequeueTimestamps.erase(bufferId);
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500860}
Vishnu Nairadf632b2021-01-07 14:05:08 -0800861
Chavi Weingartenc398c012023-04-12 17:26:02 +0000862bool BLASTBufferQueue::syncNextTransaction(
Tianhao Yao4861b102022-02-03 20:18:35 +0000863 std::function<void(SurfaceComposerClient::Transaction*)> callback,
864 bool acquireSingleBuffer) {
Chavi Weingartenc398c012023-04-12 17:26:02 +0000865 LOG_ALWAYS_FATAL_IF(!callback,
866 "BLASTBufferQueue: callback passed in to syncNextTransaction must not be "
867 "NULL");
chaviw3b4bdcf2022-03-17 09:27:03 -0500868
Chavi Weingartenc398c012023-04-12 17:26:02 +0000869 std::lock_guard _lock{mMutex};
870 BBQ_TRACE();
871 if (mTransactionReadyCallback) {
872 ALOGW("Attempting to overwrite transaction callback in syncNextTransaction");
873 return false;
Tianhao Yao4861b102022-02-03 20:18:35 +0000874 }
chaviw3b4bdcf2022-03-17 09:27:03 -0500875
Chavi Weingartenc398c012023-04-12 17:26:02 +0000876 mTransactionReadyCallback = callback;
877 mSyncTransaction = new SurfaceComposerClient::Transaction();
878 mAcquireSingleBuffer = acquireSingleBuffer;
879 return true;
Tianhao Yao4861b102022-02-03 20:18:35 +0000880}
881
882void BLASTBufferQueue::stopContinuousSyncTransaction() {
883 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
884 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
885 {
886 std::lock_guard _lock{mMutex};
Chavi Weingartenc398c012023-04-12 17:26:02 +0000887 if (mAcquireSingleBuffer || !mTransactionReadyCallback) {
888 ALOGW("Attempting to stop continuous sync when none are active");
889 return;
Tianhao Yao4861b102022-02-03 20:18:35 +0000890 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000891
892 prevCallback = mTransactionReadyCallback;
893 prevTransaction = mSyncTransaction;
894
Tianhao Yao4861b102022-02-03 20:18:35 +0000895 mTransactionReadyCallback = nullptr;
896 mSyncTransaction = nullptr;
897 mAcquireSingleBuffer = true;
898 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000899
Tianhao Yao4861b102022-02-03 20:18:35 +0000900 if (prevCallback) {
901 prevCallback(prevTransaction);
902 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700903}
904
Chavi Weingartenc398c012023-04-12 17:26:02 +0000905void BLASTBufferQueue::clearSyncTransaction() {
906 std::lock_guard _lock{mMutex};
907 if (!mAcquireSingleBuffer) {
908 ALOGW("Attempting to clear sync transaction when none are active");
909 return;
910 }
911
912 mTransactionReadyCallback = nullptr;
913 mSyncTransaction = nullptr;
914}
915
Vishnu Nairea0de002020-11-17 17:42:37 -0800916bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700917 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
918 // Only reject buffers if scaling mode is freeze.
919 return false;
920 }
921
Chavi Weingarten70670e62023-02-22 17:36:40 +0000922 ui::Size bufferSize = getBufferSize(item);
Vishnu Nairea0de002020-11-17 17:42:37 -0800923 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800924 return false;
925 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700926
Vishnu Nair670b3f72020-09-29 17:52:18 -0700927 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800928 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700929}
Vishnu Nairbf255772020-10-16 10:54:41 -0700930
Robert Carr05086b22020-10-13 18:22:51 -0700931class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700932private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700933 std::mutex mMutex;
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000934 sp<BLASTBufferQueue> mBbq GUARDED_BY(mMutex);
935 bool mDestroyed GUARDED_BY(mMutex) = false;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700936
Robert Carr05086b22020-10-13 18:22:51 -0700937public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700938 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
939 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
940 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700941
Robert Carr05086b22020-10-13 18:22:51 -0700942 void allocateBuffers() override {
943 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
944 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
945 auto gbp = getIGraphicBufferProducer();
946 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
947 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
948 gbp->allocateBuffers(reqWidth, reqHeight,
949 reqFormat, reqUsage);
950
951 }).detach();
952 }
Robert Carr9c006e02020-10-14 13:41:57 -0700953
Marin Shalamanovc5986772021-03-16 16:09:49 +0100954 status_t setFrameRate(float frameRate, int8_t compatibility,
955 int8_t changeFrameRateStrategy) override {
Ady Abraham6cdd3fd2023-09-07 18:45:58 -0700956 if (flags::bq_setframerate()) {
957 return Surface::setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
958 }
959
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000960 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700961 if (mDestroyed) {
962 return DEAD_OBJECT;
963 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100964 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
965 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700966 return BAD_VALUE;
967 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100968 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700969 }
Robert Carr9b611b72020-10-19 12:00:23 -0700970
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800971 status_t setFrameTimelineInfo(uint64_t frameNumber,
972 const FrameTimelineInfo& frameTimelineInfo) override {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000973 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700974 if (mDestroyed) {
975 return DEAD_OBJECT;
976 }
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800977 return mBbq->setFrameTimelineInfo(frameNumber, frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700978 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700979
980 void destroy() override {
981 Surface::destroy();
982
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000983 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700984 mDestroyed = true;
985 mBbq = nullptr;
986 }
Robert Carr05086b22020-10-13 18:22:51 -0700987};
988
Robert Carr9c006e02020-10-14 13:41:57 -0700989// TODO: Can we coalesce this with frame updates? Need to confirm
990// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200991status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
992 bool shouldBeSeamless) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000993 std::lock_guard _lock{mMutex};
Robert Carr9c006e02020-10-14 13:41:57 -0700994 SurfaceComposerClient::Transaction t;
995
Marin Shalamanov46084422020-10-13 12:33:42 +0200996 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700997}
998
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800999status_t BLASTBufferQueue::setFrameTimelineInfo(uint64_t frameNumber,
1000 const FrameTimelineInfo& frameTimelineInfo) {
1001 ATRACE_FORMAT("%s(%s) frameNumber: %" PRIu64 " vsyncId: %" PRId64, __func__, mName.c_str(),
1002 frameNumber, frameTimelineInfo.vsyncId);
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001003 std::lock_guard _lock{mMutex};
Ady Abrahamd6e409e2023-01-19 16:07:31 -08001004 mPendingFrameTimelines.push({frameNumber, frameTimelineInfo});
Jorim Jaggia3fe67b2020-12-01 00:24:33 +01001005 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -07001006}
1007
Hongguang Chen621ec582021-02-16 15:42:35 -08001008void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001009 std::lock_guard _lock{mMutex};
Hongguang Chen621ec582021-02-16 15:42:35 -08001010 SurfaceComposerClient::Transaction t;
1011
1012 t.setSidebandStream(mSurfaceControl, stream).apply();
1013}
1014
Vishnu Nair992496b2020-10-22 17:27:21 -07001015sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001016 std::lock_guard _lock{mMutex};
Vishnu Nair992496b2020-10-22 17:27:21 -07001017 sp<IBinder> scHandle = nullptr;
1018 if (includeSurfaceControlHandle && mSurfaceControl) {
1019 scHandle = mSurfaceControl->getHandle();
1020 }
1021 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -07001022}
1023
Vishnu Nairc4a40c12020-12-23 09:14:32 -08001024void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
1025 uint64_t frameNumber) {
1026 std::lock_guard _lock{mMutex};
1027 if (mLastAcquiredFrameNumber >= frameNumber) {
1028 // Apply the transaction since we have already acquired the desired frame.
1029 t->apply();
1030 } else {
chaviwaad6cf52021-03-23 17:27:20 -05001031 mPendingTransactions.emplace_back(frameNumber, *t);
1032 // Clear the transaction so it can't be applied elsewhere.
1033 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -08001034 }
1035}
1036
chaviw6a195272021-09-03 16:14:25 -05001037void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
1038 std::lock_guard _lock{mMutex};
1039
1040 SurfaceComposerClient::Transaction t;
1041 mergePendingTransactions(&t, frameNumber);
Robert Carr79dc06a2022-02-22 15:28:59 -08001042 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
1043 t.setApplyToken(mApplyToken).apply(false, true);
chaviw6a195272021-09-03 16:14:25 -05001044}
1045
1046void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
1047 uint64_t frameNumber) {
1048 auto mergeTransaction =
1049 [&t, currentFrameNumber = frameNumber](
1050 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
1051 auto& [targetFrameNumber, transaction] = pendingTransaction;
1052 if (currentFrameNumber < targetFrameNumber) {
1053 return false;
1054 }
1055 t->merge(std::move(transaction));
1056 return true;
1057 };
1058
1059 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
1060 mPendingTransactions.end(), mergeTransaction),
1061 mPendingTransactions.end());
1062}
1063
chaviwd84085a2022-02-08 11:07:04 -06001064SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
1065 uint64_t frameNumber) {
1066 std::lock_guard _lock{mMutex};
1067 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
1068 mergePendingTransactions(t, frameNumber);
1069 return t;
1070}
1071
Vishnu Nair89496122020-12-14 17:14:53 -08001072// Maintains a single worker thread per process that services a list of runnables.
1073class AsyncWorker : public Singleton<AsyncWorker> {
1074private:
1075 std::thread mThread;
1076 bool mDone = false;
1077 std::deque<std::function<void()>> mRunnables;
1078 std::mutex mMutex;
1079 std::condition_variable mCv;
1080 void run() {
1081 std::unique_lock<std::mutex> lock(mMutex);
1082 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -08001083 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001084 std::deque<std::function<void()>> runnables = std::move(mRunnables);
1085 mRunnables.clear();
1086 lock.unlock();
1087 // Run outside the lock since the runnable might trigger another
1088 // post to the async worker.
1089 execute(runnables);
1090 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -08001091 }
Wonsik Kim567533e2021-05-04 19:31:29 -07001092 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -08001093 }
1094 }
1095
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001096 void execute(std::deque<std::function<void()>>& runnables) {
1097 while (!runnables.empty()) {
1098 std::function<void()> runnable = runnables.front();
1099 runnables.pop_front();
1100 runnable();
1101 }
1102 }
1103
Vishnu Nair89496122020-12-14 17:14:53 -08001104public:
1105 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
1106
1107 ~AsyncWorker() {
1108 mDone = true;
1109 mCv.notify_all();
1110 if (mThread.joinable()) {
1111 mThread.join();
1112 }
1113 }
1114
1115 void post(std::function<void()> runnable) {
1116 std::unique_lock<std::mutex> lock(mMutex);
1117 mRunnables.emplace_back(std::move(runnable));
1118 mCv.notify_one();
1119 }
1120};
1121ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
1122
1123// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
1124class AsyncProducerListener : public BnProducerListener {
1125private:
1126 const sp<IProducerListener> mListener;
1127
1128public:
1129 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
1130
1131 void onBufferReleased() override {
1132 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
1133 }
1134
1135 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
1136 AsyncWorker::getInstance().post(
1137 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
1138 }
Sungtak Lee7c935092024-09-16 16:55:04 +00001139
1140 void onBufferDetached(int slot) override {
1141 AsyncWorker::getInstance().post(
1142 [listener = mListener, slot = slot]() { listener->onBufferDetached(slot); });
1143 }
1144
1145#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_CONSUMER_ATTACH_CALLBACK)
1146 void onBufferAttached() override {
1147 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferAttached(); });
1148 }
1149#endif
Vishnu Nair89496122020-12-14 17:14:53 -08001150};
1151
Patrick Williams078d7362024-08-27 10:20:39 -05001152#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1153class BBQBufferQueueCore : public BufferQueueCore {
1154public:
1155 explicit BBQBufferQueueCore(const wp<BLASTBufferQueue>& bbq) : mBLASTBufferQueue{bbq} {}
1156
1157 void notifyBufferReleased() const override {
1158 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1159 if (!bbq) {
1160 return;
1161 }
1162 bbq->mBufferReleaseReader->interruptBlockingRead();
1163 }
1164
1165private:
1166 wp<BLASTBufferQueue> mBLASTBufferQueue;
1167};
1168#endif
1169
Vishnu Nair89496122020-12-14 17:14:53 -08001170// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
1171// can be non-blocking when the producer is in the client process.
1172class BBQBufferQueueProducer : public BufferQueueProducer {
1173public:
Patrick Williamsca81c052024-08-15 12:38:34 -05001174 BBQBufferQueueProducer(const sp<BufferQueueCore>& core, const wp<BLASTBufferQueue>& bbq)
Brian Lindahlc794b692023-01-31 15:42:47 -07001175 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/),
Patrick Williamsca81c052024-08-15 12:38:34 -05001176 mBLASTBufferQueue(bbq) {}
Vishnu Nair89496122020-12-14 17:14:53 -08001177
1178 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
1179 QueueBufferOutput* output) override {
1180 if (!listener) {
1181 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
1182 }
1183
1184 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
1185 producerControlledByApp, output);
1186 }
Vishnu Nair17dde612020-12-28 11:39:59 -08001187
Brian Lindahlc794b692023-01-31 15:42:47 -07001188 // We want to resize the frame history when changing the size of the buffer queue
1189 status_t setMaxDequeuedBufferCount(int maxDequeuedBufferCount) override {
1190 int maxBufferCount;
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001191 if (status_t status = BufferQueueProducer::setMaxDequeuedBufferCount(maxDequeuedBufferCount,
1192 &maxBufferCount);
1193 status != OK) {
1194 return status;
Brian Lindahlc794b692023-01-31 15:42:47 -07001195 }
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001196
1197 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1198 if (!bbq) {
1199 return OK;
1200 }
1201
1202 // if we can't determine the max buffer count, then just skip growing the history size
1203 size_t newFrameHistorySize = maxBufferCount + 2; // +2 because triple buffer rendering
1204 // optimize away resizing the frame history unless it will grow
1205 if (newFrameHistorySize > FrameEventHistory::INITIAL_MAX_FRAME_HISTORY) {
1206 ALOGV("increasing frame history size to %zu", newFrameHistorySize);
1207 bbq->resizeFrameEventHistory(newFrameHistorySize);
1208 }
1209
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001210 return OK;
Brian Lindahlc794b692023-01-31 15:42:47 -07001211 }
1212
Vishnu Nair17dde612020-12-28 11:39:59 -08001213 int query(int what, int* value) override {
1214 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
1215 *value = 1;
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001216 return OK;
Vishnu Nair17dde612020-12-28 11:39:59 -08001217 }
1218 return BufferQueueProducer::query(what, value);
1219 }
Brian Lindahlc794b692023-01-31 15:42:47 -07001220
Patrick Williams078d7362024-08-27 10:20:39 -05001221#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1222 status_t waitForBufferRelease(std::unique_lock<std::mutex>& bufferQueueLock,
1223 nsecs_t timeout) const override {
1224 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1225 if (!bbq) {
1226 return OK;
1227 }
1228
1229 // BufferQueue has already checked if we have a free buffer. If there's an unread interrupt,
1230 // we want to ignore it. This must be done before unlocking the BufferQueue lock to ensure
1231 // we don't miss an interrupt.
1232 bbq->mBufferReleaseReader->clearInterrupts();
1233 bbq->mThreadsBlockingOnDequeue++;
1234 bufferQueueLock.unlock();
1235 Deferred cleanup{[&]() {
1236 bufferQueueLock.lock();
1237 bbq->mThreadsBlockingOnDequeue--;
1238 }};
1239
1240 ATRACE_FORMAT("waiting for free buffer");
1241 ReleaseCallbackId id;
1242 sp<Fence> fence;
1243 uint32_t maxAcquiredBufferCount;
1244 status_t status =
1245 bbq->mBufferReleaseReader->readBlocking(id, fence, maxAcquiredBufferCount, timeout);
1246 if (status == TIMED_OUT) {
1247 return TIMED_OUT;
1248 } else if (status != OK) {
1249 // Waiting was interrupted or an error occurred. BufferQueueProducer will check if we
1250 // have a free buffer and call this method again if not.
1251 return OK;
1252 }
1253
1254 bbq->releaseBufferCallback(id, fence, maxAcquiredBufferCount);
1255 return OK;
1256 }
1257#endif
1258
Brian Lindahlc794b692023-01-31 15:42:47 -07001259private:
1260 const wp<BLASTBufferQueue> mBLASTBufferQueue;
Vishnu Nair89496122020-12-14 17:14:53 -08001261};
1262
1263// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
1264// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
1265// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
1266// we can deadlock.
1267void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
1268 sp<IGraphicBufferConsumer>* outConsumer) {
1269 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
1270 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
1271
Patrick Williams078d7362024-08-27 10:20:39 -05001272#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1273 auto core = sp<BBQBufferQueueCore>::make(this);
1274#else
1275 auto core = sp<BufferQueueCore>::make();
1276#endif
Vishnu Nair89496122020-12-14 17:14:53 -08001277 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
1278
Patrick Williams078d7362024-08-27 10:20:39 -05001279 auto producer = sp<BBQBufferQueueProducer>::make(core, this);
Vishnu Nair89496122020-12-14 17:14:53 -08001280 LOG_ALWAYS_FATAL_IF(producer == nullptr,
1281 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
1282
Patrick Williams078d7362024-08-27 10:20:39 -05001283 auto consumer = sp<BufferQueueConsumer>::make(core);
Vishnu Nair8b30dd12021-01-25 14:16:54 -08001284 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -08001285 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
1286 "BLASTBufferQueue: failed to create BufferQueueConsumer");
1287
1288 *outProducer = producer;
1289 *outConsumer = consumer;
1290}
1291
Brian Lindahlc794b692023-01-31 15:42:47 -07001292void BLASTBufferQueue::resizeFrameEventHistory(size_t newSize) {
1293 // This can be null during creation of the buffer queue, but resizing won't do anything at that
1294 // point in time, so just ignore. This can go away once the class relationships and lifetimes of
1295 // objects are cleaned up with a major refactor of BufferQueue as a whole.
1296 if (mBufferItemConsumer != nullptr) {
1297 std::unique_lock _lock{mMutex};
1298 mBufferItemConsumer->resizeFrameEventHistory(newSize);
1299 }
1300}
1301
chaviw497e81c2021-02-04 17:09:47 -08001302PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
1303 PixelFormat convertedFormat = format;
1304 switch (format) {
1305 case PIXEL_FORMAT_TRANSPARENT:
1306 case PIXEL_FORMAT_TRANSLUCENT:
1307 convertedFormat = PIXEL_FORMAT_RGBA_8888;
1308 break;
1309 case PIXEL_FORMAT_OPAQUE:
1310 convertedFormat = PIXEL_FORMAT_RGBX_8888;
1311 break;
1312 }
1313 return convertedFormat;
1314}
1315
Robert Carr82d07c92021-05-10 11:36:43 -07001316uint32_t BLASTBufferQueue::getLastTransformHint() const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001317 std::lock_guard _lock{mMutex};
Robert Carr82d07c92021-05-10 11:36:43 -07001318 if (mSurfaceControl != nullptr) {
1319 return mSurfaceControl->getTransformHint();
1320 } else {
1321 return 0;
1322 }
1323}
1324
chaviw0b020f82021-08-20 12:00:47 -05001325uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001326 std::lock_guard _lock{mMutex};
chaviw0b020f82021-08-20 12:00:47 -05001327 return mLastAcquiredFrameNumber;
1328}
1329
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001330bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001331 std::lock_guard _lock{mMutex};
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001332 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1333}
1334
Patrick Williamsf1e5df12022-10-17 21:37:42 +00001335void BLASTBufferQueue::setTransactionHangCallback(
1336 std::function<void(const std::string&)> callback) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001337 std::lock_guard _lock{mMutex};
Patrick Williams7c9fa272024-08-30 12:38:43 +00001338 mTransactionHangCallback = std::move(callback);
Robert Carr4c1b6462021-12-21 10:30:50 -08001339}
1340
Vishnu Nairaf15fab2024-07-30 08:59:26 -07001341void BLASTBufferQueue::setApplyToken(sp<IBinder> applyToken) {
1342 std::lock_guard _lock{mMutex};
1343 mApplyToken = std::move(applyToken);
1344}
1345
Patrick Williams7c9fa272024-08-30 12:38:43 +00001346#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1347
Patrick Williams078d7362024-08-27 10:20:39 -05001348BLASTBufferQueue::BufferReleaseReader::BufferReleaseReader(BLASTBufferQueue& bbq) : mBbq{bbq} {
1349 mEpollFd = android::base::unique_fd{epoll_create1(EPOLL_CLOEXEC)};
Patrick Williams7c9fa272024-08-30 12:38:43 +00001350 LOG_ALWAYS_FATAL_IF(!mEpollFd.ok(),
1351 "Failed to create buffer release epoll file descriptor. errno=%d "
1352 "message='%s'",
1353 errno, strerror(errno));
1354
1355 epoll_event registerEndpointFd{};
1356 registerEndpointFd.events = EPOLLIN;
Patrick Williams078d7362024-08-27 10:20:39 -05001357 registerEndpointFd.data.fd = mBbq.mBufferReleaseConsumer->getFd();
1358 status_t status = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mBbq.mBufferReleaseConsumer->getFd(),
1359 &registerEndpointFd);
Patrick Williams7c9fa272024-08-30 12:38:43 +00001360 LOG_ALWAYS_FATAL_IF(status == -1,
1361 "Failed to register buffer release consumer file descriptor with epoll. "
1362 "errno=%d message='%s'",
1363 errno, strerror(errno));
1364
1365 mEventFd = android::base::unique_fd(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK));
1366 LOG_ALWAYS_FATAL_IF(!mEventFd.ok(),
1367 "Failed to create buffer release event file descriptor. errno=%d "
1368 "message='%s'",
1369 errno, strerror(errno));
1370
1371 epoll_event registerEventFd{};
1372 registerEventFd.events = EPOLLIN;
1373 registerEventFd.data.fd = mEventFd.get();
1374 status = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mEventFd.get(), &registerEventFd);
1375 LOG_ALWAYS_FATAL_IF(status == -1,
1376 "Failed to register buffer release event file descriptor with epoll. "
1377 "errno=%d message='%s'",
1378 errno, strerror(errno));
1379}
1380
Patrick Williams7c9fa272024-08-30 12:38:43 +00001381status_t BLASTBufferQueue::BufferReleaseReader::readBlocking(ReleaseCallbackId& outId,
1382 sp<Fence>& outFence,
Patrick Williams078d7362024-08-27 10:20:39 -05001383 uint32_t& outMaxAcquiredBufferCount,
1384 nsecs_t timeout) {
1385 // TODO(b/363290953) epoll_wait only has millisecond timeout precision. If timeout is less than
1386 // 1ms, then we round timeout up to 1ms. Otherwise, we round timeout to the nearest
1387 // millisecond. Once epoll_pwait2 can be used in libgui, we can specify timeout with nanosecond
1388 // precision.
1389 int timeoutMs = -1;
1390 if (timeout == 0) {
1391 timeoutMs = 0;
1392 } else if (timeout > 0) {
1393 const int nsPerMs = 1000000;
1394 if (timeout < nsPerMs) {
1395 timeoutMs = 1;
1396 } else {
1397 timeoutMs = static_cast<int>(
1398 std::chrono::round<std::chrono::milliseconds>(std::chrono::nanoseconds{timeout})
1399 .count());
1400 }
1401 }
1402
Patrick Williams7c9fa272024-08-30 12:38:43 +00001403 epoll_event event{};
Patrick Williams078d7362024-08-27 10:20:39 -05001404 int eventCount;
1405 do {
1406 eventCount = epoll_wait(mEpollFd.get(), &event, 1 /*maxevents*/, timeoutMs);
1407 } while (eventCount == -1 && errno != EINTR);
1408
1409 if (eventCount == -1) {
1410 ALOGE("epoll_wait error while waiting for buffer release. errno=%d message='%s'", errno,
1411 strerror(errno));
1412 return UNKNOWN_ERROR;
1413 }
1414
1415 if (eventCount == 0) {
1416 return TIMED_OUT;
Patrick Williams7c9fa272024-08-30 12:38:43 +00001417 }
1418
1419 if (event.data.fd == mEventFd.get()) {
Patrick Williams078d7362024-08-27 10:20:39 -05001420 clearInterrupts();
Patrick Williams7c9fa272024-08-30 12:38:43 +00001421 return WOULD_BLOCK;
1422 }
1423
Patrick Williams078d7362024-08-27 10:20:39 -05001424 return mBbq.mBufferReleaseConsumer->readReleaseFence(outId, outFence,
1425 outMaxAcquiredBufferCount);
Patrick Williams7c9fa272024-08-30 12:38:43 +00001426}
1427
1428void BLASTBufferQueue::BufferReleaseReader::interruptBlockingRead() {
Patrick Williams078d7362024-08-27 10:20:39 -05001429 if (eventfd_write(mEventFd.get(), 1) == -1) {
Patrick Williams7c9fa272024-08-30 12:38:43 +00001430 ALOGE("failed to notify dequeue event. errno=%d message='%s'", errno, strerror(errno));
1431 }
1432}
1433
Patrick Williams078d7362024-08-27 10:20:39 -05001434void BLASTBufferQueue::BufferReleaseReader::clearInterrupts() {
1435 eventfd_t value;
1436 if (eventfd_read(mEventFd.get(), &value) == -1 && errno != EWOULDBLOCK) {
1437 ALOGE("error while reading from eventfd. errno=%d message='%s'", errno, strerror(errno));
1438 }
1439}
1440
1441BLASTBufferQueue::BufferReleaseThread::BufferReleaseThread(const sp<BLASTBufferQueue>& bbq) {
1442 android::base::unique_fd epollFd{epoll_create1(EPOLL_CLOEXEC)};
1443 LOG_ALWAYS_FATAL_IF(!epollFd.ok(),
1444 "Failed to create buffer release background thread epoll file descriptor. "
1445 "errno=%d message='%s'",
1446 errno, strerror(errno));
1447
1448 epoll_event registerEndpointFd{};
1449 registerEndpointFd.events = EPOLLIN;
1450 registerEndpointFd.data.fd = bbq->mBufferReleaseConsumer->getFd();
1451 status_t status = epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, bbq->mBufferReleaseConsumer->getFd(),
1452 &registerEndpointFd);
1453 LOG_ALWAYS_FATAL_IF(status == -1,
1454 "Failed to register background thread buffer release consumer file "
1455 "descriptor with epoll. errno=%d message='%s'",
1456 errno, strerror(errno));
1457
1458 // EventFd is used to break the background thread's loop.
1459 android::base::unique_fd eventFd{eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK)};
1460 LOG_ALWAYS_FATAL_IF(!eventFd.ok(),
1461 "Failed to create background thread buffer release event file descriptor. "
1462 "errno=%d message='%s'",
1463 errno, strerror(errno));
1464
1465 epoll_event registerEventFd{};
1466 registerEventFd.events = EPOLLIN;
1467 registerEventFd.data.fd = eventFd.get();
1468 status = epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, eventFd.get(), &registerEventFd);
1469 LOG_ALWAYS_FATAL_IF(status == -1,
1470 "Failed to register background thread event file descriptor with epoll. "
1471 "errno=%d message='%s'",
1472 errno, strerror(errno));
1473
1474 mEventFd = eventFd.get();
1475
1476 std::thread([epollFd = std::move(epollFd), eventFd = std::move(eventFd),
1477 weakBbq = wp<BLASTBufferQueue>(bbq)]() {
Patrick Williams7c9fa272024-08-30 12:38:43 +00001478 pthread_setname_np(pthread_self(), "BufferReleaseThread");
Patrick Williams078d7362024-08-27 10:20:39 -05001479 while (true) {
1480 epoll_event event{};
1481 int eventCount;
1482 do {
1483 eventCount = epoll_wait(epollFd.get(), &event, 1 /*maxevents*/, -1 /*timeout*/);
1484 } while (eventCount == -1 && errno != EINTR);
1485
1486 if (eventCount == -1) {
1487 ALOGE("epoll_wait error while waiting for buffer release in background thread. "
1488 "errno=%d message='%s'",
1489 errno, strerror(errno));
Patrick Williams7c9fa272024-08-30 12:38:43 +00001490 continue;
1491 }
Patrick Williams078d7362024-08-27 10:20:39 -05001492
1493 // EventFd is used to join this thread.
1494 if (event.data.fd == eventFd.get()) {
1495 return;
1496 }
1497
Patrick Williams7c9fa272024-08-30 12:38:43 +00001498 sp<BLASTBufferQueue> bbq = weakBbq.promote();
1499 if (!bbq) {
1500 return;
1501 }
Patrick Williams078d7362024-08-27 10:20:39 -05001502
1503 // If there are threads blocking on dequeue, give those threads priority for handling
1504 // the release.
1505 if (bbq->mThreadsBlockingOnDequeue > 0) {
1506 std::this_thread::sleep_for(0ms);
1507 continue;
1508 }
1509
1510 ReleaseCallbackId id;
1511 sp<Fence> fence;
1512 uint32_t maxAcquiredBufferCount;
1513 status_t status = bbq->mBufferReleaseConsumer->readReleaseFence(id, fence,
1514 maxAcquiredBufferCount);
1515 if (status != OK) {
1516 ALOGE("failed to read from buffer release consumer in background thread. errno=%d "
1517 "message='%s'",
1518 errno, strerror(errno));
1519 continue;
1520 }
Patrick Williams7c9fa272024-08-30 12:38:43 +00001521 bbq->releaseBufferCallback(id, fence, maxAcquiredBufferCount);
1522 }
1523 }).detach();
1524}
1525
1526BLASTBufferQueue::BufferReleaseThread::~BufferReleaseThread() {
Patrick Williams078d7362024-08-27 10:20:39 -05001527 eventfd_write(mEventFd, 1);
Patrick Williams7c9fa272024-08-30 12:38:43 +00001528}
1529
1530#endif
1531
Robert Carr78c25dd2019-08-15 14:10:33 -07001532} // namespace android