blob: 7aee90393b0460d7822dd4414d3ad2d25cf3a778 [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)
Patrick Williamsc16a4a52024-10-26 01:48:01 -050055template <class Mutex>
56class UnlockGuard {
Patrick Williams078d7362024-08-27 10:20:39 -050057public:
Patrick Williamsc16a4a52024-10-26 01:48:01 -050058 explicit UnlockGuard(Mutex& lock) : mLock{lock} { mLock.unlock(); }
Patrick Williams078d7362024-08-27 10:20:39 -050059
Patrick Williamsc16a4a52024-10-26 01:48:01 -050060 ~UnlockGuard() { mLock.lock(); }
Patrick Williams078d7362024-08-27 10:20:39 -050061
Patrick Williamsc16a4a52024-10-26 01:48:01 -050062 UnlockGuard(const UnlockGuard&) = delete;
63 UnlockGuard& operator=(const UnlockGuard&) = delete;
Patrick Williams078d7362024-08-27 10:20:39 -050064
65private:
Patrick Williamsc16a4a52024-10-26 01:48:01 -050066 Mutex& mLock;
Patrick Williams078d7362024-08-27 10:20:39 -050067};
68#endif
69
chaviw3277faf2021-05-19 16:45:23 -050070inline const char* boolToString(bool b) {
Vishnu Nairdab94092020-09-29 16:09:04 -070071 return b ? "true" : "false";
72}
Patrick Williams078d7362024-08-27 10:20:39 -050073
Vishnu Nairdab94092020-09-29 16:09:04 -070074} // namespace
75
Robert Carr78c25dd2019-08-15 14:10:33 -070076namespace android {
77
Vishnu Nairdab94092020-09-29 16:09:04 -070078// Macros to include adapter info in log messages
chaviwd7deef72021-10-06 11:53:40 -050079#define BQA_LOGD(x, ...) \
80 ALOGD("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070081#define BQA_LOGV(x, ...) \
82 ALOGV("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairc6f89ee2020-12-11 14:27:32 -080083// enable logs for a single layer
84//#define BQA_LOGV(x, ...) \
85// ALOGV_IF((strstr(mName.c_str(), "SurfaceView") != nullptr), "[%s](f:%u,a:%u) " x, \
86// mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070087#define BQA_LOGE(x, ...) \
88 ALOGE("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
89
chaviw57ae4b22022-02-03 16:51:39 -060090#define BBQ_TRACE(x, ...) \
91 ATRACE_FORMAT("%s - %s(f:%u,a:%u)" x, __FUNCTION__, mName.c_str(), mNumFrameAvailable, \
92 mNumAcquired, ##__VA_ARGS__)
93
Chavi Weingartene0237bb2023-02-06 21:48:32 +000094#define UNIQUE_LOCK_WITH_ASSERTION(mutex) \
95 std::unique_lock _lock{mutex}; \
96 base::ScopedLockAssertion assumeLocked(mutex);
97
Valerie Hau871d6352020-01-29 08:44:02 -080098void BLASTBufferItemConsumer::onDisconnect() {
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000099 Mutex::Autolock lock(mMutex);
100 mPreviouslyConnected = mCurrentlyConnected;
101 mCurrentlyConnected = false;
102 if (mPreviouslyConnected) {
103 mDisconnectEvents.push(mCurrentFrameNumber);
Valerie Hau871d6352020-01-29 08:44:02 -0800104 }
Jiakai Zhangc33c63a2021-11-09 11:24:04 +0000105 mFrameEventHistory.onDisconnect();
Valerie Hau871d6352020-01-29 08:44:02 -0800106}
107
108void BLASTBufferItemConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
109 FrameEventHistoryDelta* outDelta) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800110 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800111 if (newTimestamps) {
112 // BufferQueueProducer only adds a new timestamp on
113 // queueBuffer
114 mCurrentFrameNumber = newTimestamps->frameNumber;
115 mFrameEventHistory.addQueue(*newTimestamps);
116 }
117 if (outDelta) {
118 // frame event histories will be processed
119 // only after the producer connects and requests
120 // deltas for the first time. Forward this intent
121 // to SF-side to turn event processing back on
122 mPreviouslyConnected = mCurrentlyConnected;
123 mCurrentlyConnected = true;
124 mFrameEventHistory.getAndResetDelta(outDelta);
125 }
126}
127
Alec Mouri21d94322023-10-17 19:51:39 +0000128void BLASTBufferItemConsumer::updateFrameTimestamps(
129 uint64_t frameNumber, uint64_t previousFrameNumber, nsecs_t refreshStartTime,
130 const sp<Fence>& glDoneFence, const sp<Fence>& presentFence,
131 const sp<Fence>& prevReleaseFence, CompositorTiming compositorTiming, nsecs_t latchTime,
132 nsecs_t dequeueReadyTime) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800133 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800134
135 // if the producer is not connected, don't bother updating,
136 // the next producer that connects won't access this frame event
137 if (!mCurrentlyConnected) return;
138 std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
139 std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
140 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
141
142 mFrameEventHistory.addLatch(frameNumber, latchTime);
Alec Mouri21d94322023-10-17 19:51:39 +0000143 if (flags::frametimestamps_previousrelease()) {
144 if (previousFrameNumber > 0) {
145 mFrameEventHistory.addRelease(previousFrameNumber, dequeueReadyTime,
146 std::move(releaseFenceTime));
147 }
148 } else {
149 mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
150 }
151
Valerie Hau871d6352020-01-29 08:44:02 -0800152 mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
153 mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
154 compositorTiming);
155}
156
157void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
158 bool disconnect = false;
Hongguang Chen621ec582021-02-16 15:42:35 -0800159 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800160 while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
161 disconnect = true;
162 mDisconnectEvents.pop();
163 }
164 if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
165}
166
Hongguang Chen621ec582021-02-16 15:42:35 -0800167void BLASTBufferItemConsumer::onSidebandStreamChanged() {
Ady Abrahamdbca1352021-12-15 11:58:56 -0800168 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
169 if (bbq != nullptr) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800170 sp<NativeHandle> stream = getSidebandStream();
Ady Abrahamdbca1352021-12-15 11:58:56 -0800171 bbq->setSidebandStream(stream);
Hongguang Chen621ec582021-02-16 15:42:35 -0800172 }
173}
174
Ady Abraham107788e2023-10-17 12:31:08 -0700175#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_SETFRAMERATE)
Ady Abraham6cdd3fd2023-09-07 18:45:58 -0700176void BLASTBufferItemConsumer::onSetFrameRate(float frameRate, int8_t compatibility,
177 int8_t changeFrameRateStrategy) {
178 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
179 if (bbq != nullptr) {
180 bbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
181 }
182}
183#endif
184
Brian Lindahlc794b692023-01-31 15:42:47 -0700185void BLASTBufferItemConsumer::resizeFrameEventHistory(size_t newSize) {
186 Mutex::Autolock lock(mMutex);
187 mFrameEventHistory.resize(newSize);
188}
189
Vishnu Naird2aaab12022-02-10 14:49:09 -0800190BLASTBufferQueue::BLASTBufferQueue(const std::string& name, bool updateDestinationFrame)
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800191 : mSurfaceControl(nullptr),
192 mSize(1, 1),
Vishnu Nairea0de002020-11-17 17:42:37 -0800193 mRequestedSize(mSize),
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800194 mFormat(PIXEL_FORMAT_RGBA_8888),
Tianhao Yao4861b102022-02-03 20:18:35 +0000195 mTransactionReadyCallback(nullptr),
Vishnu Naird2aaab12022-02-10 14:49:09 -0800196 mSyncTransaction(nullptr),
197 mUpdateDestinationFrame(updateDestinationFrame) {
Vishnu Nair89496122020-12-14 17:14:53 -0800198 createBufferQueue(&mProducer, &mConsumer);
Jim Shargod30823a2024-07-27 02:49:39 +0000199#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_CONSUMER_BASE_OWNS_BQ)
200 mBufferItemConsumer = new BLASTBufferItemConsumer(mProducer, mConsumer,
201 GraphicBuffer::USAGE_HW_COMPOSER |
202 GraphicBuffer::USAGE_HW_TEXTURE,
203 1, false, this);
204#else
Vishnu Nair1618c672021-02-05 13:08:26 -0800205 mBufferItemConsumer = new BLASTBufferItemConsumer(mConsumer,
206 GraphicBuffer::USAGE_HW_COMPOSER |
207 GraphicBuffer::USAGE_HW_TEXTURE,
Ady Abrahamdbca1352021-12-15 11:58:56 -0800208 1, false, this);
Jim Shargod30823a2024-07-27 02:49:39 +0000209#endif // COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_CONSUMER_BASE_OWNS_BQ)
210 // since the adapter is in the client process, set dequeue timeout
211 // explicitly so that dequeueBuffer will block
212 mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
213
liulijuneb489f62022-10-17 22:02:14 +0800214 static std::atomic<uint32_t> nextId = 0;
215 mProducerId = nextId++;
216 mName = name + "#" + std::to_string(mProducerId);
217 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(mProducerId);
218 mQueuedBufferTrace = "QueuedBuffer - " + mName + "BLAST#" + std::to_string(mProducerId);
Vishnu Nairdab94092020-09-29 16:09:04 -0700219 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700220 mBufferItemConsumer->setFrameAvailableListener(this);
Robert Carr9f133d72020-04-01 15:51:46 -0700221
Huihong Luo02186fb2022-02-23 14:21:54 -0800222 ComposerServiceAIDL::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);
Ady Abraham0bde6b52021-05-18 13:57:02 -0700223 mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
chaviw69058fb2021-09-27 09:37:30 -0500224 mCurrentMaxAcquiredBufferCount = mMaxAcquiredBuffers;
Valerie Haua32c5522019-12-09 10:11:08 -0800225 mNumAcquired = 0;
226 mNumFrameAvailable = 0;
Robert Carr4c1b6462021-12-21 10:30:50 -0800227
228 TransactionCompletedListener::getInstance()->addQueueStallListener(
Patrick Williamsf1e5df12022-10-17 21:37:42 +0000229 [&](const std::string& reason) {
230 std::function<void(const std::string&)> callbackCopy;
231 {
232 std::unique_lock _lock{mMutex};
233 callbackCopy = mTransactionHangCallback;
234 }
235 if (callbackCopy) callbackCopy(reason);
236 },
237 this);
Robert Carr4c1b6462021-12-21 10:30:50 -0800238
Patrick Williams7c9fa272024-08-30 12:38:43 +0000239#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
Patrick Williams078d7362024-08-27 10:20:39 -0500240 gui::BufferReleaseChannel::open(mName, mBufferReleaseConsumer, mBufferReleaseProducer);
241 mBufferReleaseReader.emplace(*this);
Patrick Williams7c9fa272024-08-30 12:38:43 +0000242#endif
243
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800244 BQA_LOGV("BLASTBufferQueue created");
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800245}
246
247BLASTBufferQueue::BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface,
248 int width, int height, int32_t format)
249 : BLASTBufferQueue(name) {
250 update(surface, width, height, format);
Robert Carr78c25dd2019-08-15 14:10:33 -0700251}
252
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800253BLASTBufferQueue::~BLASTBufferQueue() {
Robert Carr4c1b6462021-12-21 10:30:50 -0800254 TransactionCompletedListener::getInstance()->removeQueueStallListener(this);
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800255 if (mPendingTransactions.empty()) {
256 return;
257 }
258 BQA_LOGE("Applying pending transactions on dtor %d",
259 static_cast<uint32_t>(mPendingTransactions.size()));
260 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800261 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
Robert Carr79dc06a2022-02-22 15:28:59 -0800262 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
263 t.setApplyToken(mApplyToken).apply(false, true);
chaviw3b4bdcf2022-03-17 09:27:03 -0500264
265 if (mTransactionReadyCallback) {
266 mTransactionReadyCallback(mSyncTransaction);
267 }
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800268}
269
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500270void BLASTBufferQueue::onFirstRef() {
271 // safe default, most producers are expected to override this
272 mProducer->setMaxDequeuedBufferCount(2);
273}
274
chaviw565ee542021-01-14 10:21:23 -0800275void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Naird2aaab12022-02-10 14:49:09 -0800276 int32_t format) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800277 LOG_ALWAYS_FATAL_IF(surface == nullptr, "BLASTBufferQueue: mSurfaceControl must not be NULL");
278
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000279 std::lock_guard _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800280 if (mFormat != format) {
281 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800282 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800283 }
284
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800285 const bool surfaceControlChanged = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairab066512022-01-04 22:28:00 +0000286 if (surfaceControlChanged && mSurfaceControl != nullptr) {
287 BQA_LOGD("Updating SurfaceControl without recreating BBQ");
288 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800289
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700290 // Always update the native object even though they might have the same layer handle, so we can
291 // get the updated transform hint from WM.
292 mSurfaceControl = surface;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800293 SurfaceComposerClient::Transaction t;
Brian Lindahl628cff42024-10-30 11:50:28 -0600294 bool applyTransaction = false;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800295 if (surfaceControlChanged) {
Patrick Williamsc16a4a52024-10-26 01:48:01 -0500296#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
Patrick Williamsa419faa2024-10-29 16:50:27 -0500297 updateBufferReleaseProducer();
Patrick Williamsc16a4a52024-10-26 01:48:01 -0500298#endif
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800299 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
300 layer_state_t::eEnableBackpressure);
Brian Lindahl628cff42024-10-30 11:50:28 -0600301 // Migrate the picture profile handle to the new surface control.
302 if (com_android_graphics_libgui_flags_apply_picture_profiles() &&
303 mPictureProfileHandle.has_value()) {
304 t.setPictureProfileHandle(mSurfaceControl, *mPictureProfileHandle);
305 }
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800306 applyTransaction = true;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800307 }
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800308 mTransformHint = mSurfaceControl->getTransformHint();
309 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700310 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
311 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800312
Vishnu Nairea0de002020-11-17 17:42:37 -0800313 ui::Size newSize(width, height);
314 if (mRequestedSize != newSize) {
315 mRequestedSize.set(newSize);
316 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000317 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800318 // If the buffer supports scaling, update the frame immediately since the client may
319 // want to scale the existing buffer to the new size.
320 mSize = mRequestedSize;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800321 if (mUpdateDestinationFrame) {
322 t.setDestinationFrame(mSurfaceControl, Rect(newSize));
323 applyTransaction = true;
324 }
Vishnu Nair53c936c2020-12-03 11:46:37 -0800325 }
Robert Carrfc416512020-04-02 12:32:44 -0700326 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800327 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800328 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
Patrick Williamsc16a4a52024-10-26 01:48:01 -0500329 t.setApplyToken(mApplyToken).apply(false /* synchronous */, true /* oneWay */);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800330 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700331}
332
chaviwd7deef72021-10-06 11:53:40 -0500333static std::optional<SurfaceControlStats> findMatchingStat(
334 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
335 for (auto stat : stats) {
336 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
337 return stat;
338 }
339 }
340 return std::nullopt;
341}
342
Patrick Williams5312ec12024-08-23 16:11:10 -0500343TransactionCompletedCallbackTakesContext BLASTBufferQueue::makeTransactionCommittedCallbackThunk() {
344 return [bbq = sp<BLASTBufferQueue>::fromExisting(
345 this)](void* /*context*/, nsecs_t latchTime, const sp<Fence>& presentFence,
346 const std::vector<SurfaceControlStats>& stats) {
347 bbq->transactionCommittedCallback(latchTime, presentFence, stats);
348 };
chaviwd7deef72021-10-06 11:53:40 -0500349}
350
351void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
352 const sp<Fence>& /*presentFence*/,
353 const std::vector<SurfaceControlStats>& stats) {
354 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000355 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600356 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500357 BQA_LOGV("transactionCommittedCallback");
358 if (!mSurfaceControlsWithPendingCallback.empty()) {
359 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
360 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
361 if (stat) {
362 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
363
364 // We need to check if we were waiting for a transaction callback in order to
365 // process any pending buffers and unblock. It's possible to get transaction
chaviwc1cf4022022-06-03 13:32:33 -0500366 // callbacks for previous requests so we need to ensure that there are no pending
367 // frame numbers that were in a sync. We remove the frame from mSyncedFrameNumbers
368 // set and then check if it's empty. If there are no more pending syncs, we can
369 // proceed with flushing the shadow queue.
chaviwc1cf4022022-06-03 13:32:33 -0500370 mSyncedFrameNumbers.erase(currFrameNumber);
Chavi Weingartend48797b2023-08-04 13:11:39 +0000371 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500372 flushShadowQueue();
373 }
374 } else {
chaviw768bfa02021-11-01 09:50:57 -0500375 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviwd7deef72021-10-06 11:53:40 -0500376 }
377 } else {
378 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
379 "empty.");
380 }
chaviwd7deef72021-10-06 11:53:40 -0500381 }
382}
383
Patrick Williams5312ec12024-08-23 16:11:10 -0500384TransactionCompletedCallbackTakesContext BLASTBufferQueue::makeTransactionCallbackThunk() {
385 return [bbq = sp<BLASTBufferQueue>::fromExisting(
386 this)](void* /*context*/, nsecs_t latchTime, const sp<Fence>& presentFence,
387 const std::vector<SurfaceControlStats>& stats) {
388 bbq->transactionCallback(latchTime, presentFence, stats);
389 };
Robert Carr78c25dd2019-08-15 14:10:33 -0700390}
391
392void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
393 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700394 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000395 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600396 BBQ_TRACE();
chaviw71c2cc42020-10-23 16:42:02 -0700397 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700398
chaviw42026162021-04-16 15:46:12 -0500399 if (!mSurfaceControlsWithPendingCallback.empty()) {
400 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
401 mSurfaceControlsWithPendingCallback.pop();
chaviwd7deef72021-10-06 11:53:40 -0500402 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
403 if (statsOptional) {
404 SurfaceControlStats stat = *statsOptional;
Vishnu Nair71fcf912022-10-18 09:14:20 -0700405 if (stat.transformHint) {
406 mTransformHint = *stat.transformHint;
407 mBufferItemConsumer->setTransformHint(mTransformHint);
408 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
409 }
Vishnu Nairde66dc72021-06-17 17:54:41 -0700410 // Update frametime stamps if the frame was latched and presented, indicated by a
411 // valid latch time.
412 if (stat.latchTime > 0) {
413 mBufferItemConsumer
414 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
Alec Mouri21d94322023-10-17 19:51:39 +0000415 stat.frameEventStats.previousFrameNumber,
Vishnu Nairde66dc72021-06-17 17:54:41 -0700416 stat.frameEventStats.refreshStartTime,
417 stat.frameEventStats.gpuCompositionDoneFence,
418 stat.presentFence, stat.previousReleaseFence,
419 stat.frameEventStats.compositorTiming,
420 stat.latchTime,
421 stat.frameEventStats.dequeueReadyTime);
422 }
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 }
chaviwd7deef72021-10-06 11:53:40 -0500438 } else {
chaviw768bfa02021-11-01 09:50:57 -0500439 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500440 }
441 } else {
442 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
443 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800444 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700445 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700446}
447
Patrick Williams7c9fa272024-08-30 12:38:43 +0000448void BLASTBufferQueue::flushShadowQueue() {
449 BQA_LOGV("flushShadowQueue");
450 int numFramesToFlush = mNumFrameAvailable;
451 while (numFramesToFlush > 0) {
452 acquireNextBufferLocked(std::nullopt);
453 numFramesToFlush--;
454 }
455}
456
Vishnu Nair1506b182021-02-22 14:35:15 -0800457// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
458// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
459// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
460// Otherwise, this is a no-op.
Patrick Williams5312ec12024-08-23 16:11:10 -0500461ReleaseBufferCallback BLASTBufferQueue::makeReleaseBufferCallbackThunk() {
462 return [weakBbq = wp<BLASTBufferQueue>::fromExisting(
463 this)](const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
464 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
465 sp<BLASTBufferQueue> bbq = weakBbq.promote();
466 if (!bbq) {
467 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
468 return;
469 }
470 bbq->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
Patrick Williamsc16a4a52024-10-26 01:48:01 -0500471#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
472 bbq->drainBufferReleaseConsumer();
473#endif
Patrick Williams5312ec12024-08-23 16:11:10 -0500474 };
Vishnu Nair1506b182021-02-22 14:35:15 -0800475}
476
chaviw69058fb2021-09-27 09:37:30 -0500477void BLASTBufferQueue::releaseBufferCallback(
478 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
479 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000480 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600481 BBQ_TRACE();
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700482 releaseBufferCallbackLocked(id, releaseFence, currentMaxAcquiredBufferCount,
483 false /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800484}
485
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700486void BLASTBufferQueue::releaseBufferCallbackLocked(
487 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
488 std::optional<uint32_t> currentMaxAcquiredBufferCount, bool fakeRelease) {
Robert Carr405e2f62021-12-31 16:59:34 -0800489 ATRACE_CALL();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700490 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800491
Ady Abraham899dcdb2021-06-15 16:56:21 -0700492 // Calculate how many buffers we need to hold before we release them back
493 // to the buffer queue. This will prevent higher latency when we are running
494 // on a lower refresh rate than the max supported. We only do that for EGL
495 // clients as others don't care about latency
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000496 const auto it = mSubmitted.find(id);
497 const bool isEGL = it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
Ady Abraham899dcdb2021-06-15 16:56:21 -0700498
chaviw69058fb2021-09-27 09:37:30 -0500499 if (currentMaxAcquiredBufferCount) {
500 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
501 }
502
liulijunf90df632022-11-14 14:24:48 +0800503 const uint32_t numPendingBuffersToHold =
504 isEGL ? std::max(0, mMaxAcquiredBuffers - (int32_t)mCurrentMaxAcquiredBufferCount) : 0;
Robert Carr405e2f62021-12-31 16:59:34 -0800505
506 auto rb = ReleasedBuffer{id, releaseFence};
507 if (std::find(mPendingRelease.begin(), mPendingRelease.end(), rb) == mPendingRelease.end()) {
508 mPendingRelease.emplace_back(rb);
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700509 if (fakeRelease) {
510 BQA_LOGE("Faking releaseBufferCallback from transactionCompleteCallback %" PRIu64,
511 id.framenumber);
512 BBQ_TRACE("FakeReleaseCallback");
513 }
Robert Carr405e2f62021-12-31 16:59:34 -0800514 }
Ady Abraham899dcdb2021-06-15 16:56:21 -0700515
516 // Release all buffers that are beyond the ones that we need to hold
517 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500518 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700519 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500520 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwc1cf4022022-06-03 13:32:33 -0500521 // Don't process the transactions here if mSyncedFrameNumbers is not empty. That means
522 // are still transactions that have sync buffers in them that have not been applied or
523 // dropped. Instead, let onFrameAvailable handle processing them since it will merge with
524 // the syncTransaction.
525 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500526 acquireNextBufferLocked(std::nullopt);
527 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800528 }
529
Ady Abraham899dcdb2021-06-15 16:56:21 -0700530 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700531 ATRACE_INT(mQueuedBufferTrace.c_str(),
532 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800533 mCallbackCV.notify_all();
534}
535
chaviw0acd33a2021-11-02 11:55:37 -0500536void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
537 const sp<Fence>& releaseFence) {
538 auto it = mSubmitted.find(callbackId);
539 if (it == mSubmitted.end()) {
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 Williams5312ec12024-08-23 16:11:10 -0500649 auto releaseBufferCallback = makeReleaseBufferCallbackThunk();
chaviwba4320c2021-09-15 15:20:53 -0500650 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900651
652 nsecs_t dequeueTime = -1;
653 {
654 std::lock_guard _lock{mTimestampMutex};
655 auto dequeueTimeIt = mDequeueTimestamps.find(buffer->getId());
656 if (dequeueTimeIt != mDequeueTimestamps.end()) {
657 dequeueTime = dequeueTimeIt->second;
658 mDequeueTimestamps.erase(dequeueTimeIt);
659 }
660 }
661
liulijuneb489f62022-10-17 22:02:14 +0800662 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, mProducerId,
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900663 releaseBufferCallback, dequeueTime);
John Reck137069e2020-12-10 22:07:37 -0500664 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
665 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
666 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Patrick Williams5312ec12024-08-23 16:11:10 -0500667 t->addTransactionCompletedCallback(makeTransactionCallbackThunk(), nullptr);
chaviwf2dace72021-11-17 17:36:50 -0600668
chaviw42026162021-04-16 15:46:12 -0500669 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700670
Vishnu Naird2aaab12022-02-10 14:49:09 -0800671 if (mUpdateDestinationFrame) {
672 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
673 } else {
674 const bool ignoreDestinationFrame =
675 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
676 t->setFlags(mSurfaceControl,
677 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
678 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700679 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700680 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800681 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800682 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800683 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800684 if (!bufferItem.mIsAutoTimestamp) {
685 t->setDesiredPresentTime(bufferItem.mTimestamp);
686 }
Brian Lindahl628cff42024-10-30 11:50:28 -0600687 if (com_android_graphics_libgui_flags_apply_picture_profiles() &&
688 bufferItem.mPictureProfileHandle.has_value()) {
689 t->setPictureProfileHandle(mSurfaceControl, *bufferItem.mPictureProfileHandle);
690 // The current picture profile must be maintained in case the BBQ gets its
691 // SurfaceControl switched out.
692 mPictureProfileHandle = bufferItem.mPictureProfileHandle;
693 // Clear out the picture profile if the requestor has asked for it to be cleared
694 if (mPictureProfileHandle == PictureProfileHandle::NONE) {
695 mPictureProfileHandle = std::nullopt;
696 }
697 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700698
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800699 // Drop stale frame timeline infos
700 while (!mPendingFrameTimelines.empty() &&
701 mPendingFrameTimelines.front().first < bufferItem.mFrameNumber) {
702 ATRACE_FORMAT_INSTANT("dropping stale frameNumber: %" PRIu64 " vsyncId: %" PRId64,
703 mPendingFrameTimelines.front().first,
704 mPendingFrameTimelines.front().second.vsyncId);
705 mPendingFrameTimelines.pop();
706 }
707
708 if (!mPendingFrameTimelines.empty() &&
709 mPendingFrameTimelines.front().first == bufferItem.mFrameNumber) {
710 ATRACE_FORMAT_INSTANT("Transaction::setFrameTimelineInfo frameNumber: %" PRIu64
711 " vsyncId: %" PRId64,
712 bufferItem.mFrameNumber,
713 mPendingFrameTimelines.front().second.vsyncId);
714 t->setFrameTimelineInfo(mPendingFrameTimelines.front().second);
715 mPendingFrameTimelines.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100716 }
717
chaviw6a195272021-09-03 16:14:25 -0500718 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700719 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800720 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
721 t->setApplyToken(mApplyToken).apply(false, true);
722 mAppliedLastTransaction = true;
723 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
724 } else {
725 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
726 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700727 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700728
chaviwd7deef72021-10-06 11:53:40 -0500729 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800730 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700731 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500732 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800733 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700734 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700735 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000736 return OK;
Robert Carr78c25dd2019-08-15 14:10:33 -0700737}
738
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800739Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
740 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800741 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800742 }
743 return item.mCrop;
744}
745
chaviwd7deef72021-10-06 11:53:40 -0500746void BLASTBufferQueue::acquireAndReleaseBuffer() {
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000747 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500748 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500749 status_t status =
750 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
751 if (status != OK) {
752 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
753 statusToString(status).c_str());
754 return;
755 }
chaviwd7deef72021-10-06 11:53:40 -0500756 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500757 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500758}
759
Vishnu Nairaef1de92020-10-22 12:15:53 -0700760void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000761 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
762 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
chaviwc1cf4022022-06-03 13:32:33 -0500763
Tianhao Yao4861b102022-02-03 20:18:35 +0000764 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000765 UNIQUE_LOCK_WITH_ASSERTION(mMutex);
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000766 BBQ_TRACE();
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000767 bool waitForTransactionCallback = !mSyncedFrameNumbers.empty();
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800768
Tianhao Yao4861b102022-02-03 20:18:35 +0000769 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
770 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800771
Tianhao Yao4861b102022-02-03 20:18:35 +0000772 if (syncTransactionSet) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000773 // If we are going to re-use the same mSyncTransaction, release the buffer that may
774 // already be set in the Transaction. This is to allow us a free slot early to continue
775 // processing a new buffer.
776 if (!mAcquireSingleBuffer) {
777 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
778 if (bufferData) {
779 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
780 bufferData->frameNumber);
781 releaseBuffer(bufferData->generateReleaseCallbackId(),
782 bufferData->acquireFence);
Tianhao Yao4861b102022-02-03 20:18:35 +0000783 }
784 }
chaviw0acd33a2021-11-02 11:55:37 -0500785
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000786 if (waitForTransactionCallback) {
787 // We are waiting on a previous sync's transaction callback so allow another sync
788 // transaction to proceed.
789 //
790 // We need to first flush out the transactions that were in between the two syncs.
791 // We do this by merging them into mSyncTransaction so any buffer merging will get
792 // a release callback invoked.
793 while (mNumFrameAvailable > 0) {
794 // flush out the shadow queue
795 acquireAndReleaseBuffer();
796 }
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800797 } else {
798 // Make sure the frame available count is 0 before proceeding with a sync to ensure
799 // the correct frame is used for the sync. The only way mNumFrameAvailable would be
800 // greater than 0 is if we already ran out of buffers previously. This means we
801 // need to flush the buffers before proceeding with the sync.
802 while (mNumFrameAvailable > 0) {
803 BQA_LOGD("waiting until no queued buffers");
804 mCallbackCV.wait(_lock);
805 }
chaviwd7deef72021-10-06 11:53:40 -0500806 }
807 }
808
Tianhao Yao4861b102022-02-03 20:18:35 +0000809 // add to shadow queue
810 mNumFrameAvailable++;
chaviwc1cf4022022-06-03 13:32:33 -0500811 if (waitForTransactionCallback && mNumFrameAvailable >= 2) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000812 acquireAndReleaseBuffer();
813 }
814 ATRACE_INT(mQueuedBufferTrace.c_str(),
815 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
816
817 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
818 item.mFrameNumber, boolToString(syncTransactionSet));
819
820 if (syncTransactionSet) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800821 // Add to mSyncedFrameNumbers before waiting in case any buffers are released
822 // while waiting for a free buffer. The release and commit callback will try to
823 // acquire buffers if there are any available, but we don't want it to acquire
824 // in the case where a sync transaction wants the buffer.
825 mSyncedFrameNumbers.emplace(item.mFrameNumber);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000826 // If there's no available buffer and we're in a sync transaction, we need to wait
827 // instead of returning since we guarantee a buffer will be acquired for the sync.
828 while (acquireNextBufferLocked(mSyncTransaction) == BufferQueue::NO_BUFFER_AVAILABLE) {
829 BQA_LOGD("waiting for available buffer");
830 mCallbackCV.wait(_lock);
831 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000832
833 // Only need a commit callback when syncing to ensure the buffer that's synced has been
834 // sent to SF
Patrick Williams5312ec12024-08-23 16:11:10 -0500835 mSyncTransaction
836 ->addTransactionCommittedCallback(makeTransactionCommittedCallbackThunk(),
837 nullptr);
Tianhao Yao4861b102022-02-03 20:18:35 +0000838 if (mAcquireSingleBuffer) {
839 prevCallback = mTransactionReadyCallback;
840 prevTransaction = mSyncTransaction;
841 mTransactionReadyCallback = nullptr;
842 mSyncTransaction = nullptr;
843 }
chaviwc1cf4022022-06-03 13:32:33 -0500844 } else if (!waitForTransactionCallback) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000845 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800846 }
847 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000848 if (prevCallback) {
849 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500850 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800851}
852
Vishnu Nairaef1de92020-10-22 12:15:53 -0700853void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
854 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
855 // Do nothing since we are not storing unacquired buffer items locally.
856}
857
Vishnu Nairadf632b2021-01-07 14:05:08 -0800858void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000859 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800860 mDequeueTimestamps[bufferId] = systemTime();
Patrick Williams4b9507d2024-07-25 09:55:52 -0500861};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800862
863void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
Patrick Williams3ced5382024-08-21 15:39:32 -0500864 std::lock_guard _lock{mTimestampMutex};
865 mDequeueTimestamps.erase(bufferId);
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500866}
Vishnu Nairadf632b2021-01-07 14:05:08 -0800867
Chavi Weingartenc398c012023-04-12 17:26:02 +0000868bool BLASTBufferQueue::syncNextTransaction(
Tianhao Yao4861b102022-02-03 20:18:35 +0000869 std::function<void(SurfaceComposerClient::Transaction*)> callback,
870 bool acquireSingleBuffer) {
Chavi Weingartenc398c012023-04-12 17:26:02 +0000871 LOG_ALWAYS_FATAL_IF(!callback,
872 "BLASTBufferQueue: callback passed in to syncNextTransaction must not be "
873 "NULL");
chaviw3b4bdcf2022-03-17 09:27:03 -0500874
Chavi Weingartenc398c012023-04-12 17:26:02 +0000875 std::lock_guard _lock{mMutex};
876 BBQ_TRACE();
877 if (mTransactionReadyCallback) {
878 ALOGW("Attempting to overwrite transaction callback in syncNextTransaction");
879 return false;
Tianhao Yao4861b102022-02-03 20:18:35 +0000880 }
chaviw3b4bdcf2022-03-17 09:27:03 -0500881
Chavi Weingartenc398c012023-04-12 17:26:02 +0000882 mTransactionReadyCallback = callback;
883 mSyncTransaction = new SurfaceComposerClient::Transaction();
884 mAcquireSingleBuffer = acquireSingleBuffer;
885 return true;
Tianhao Yao4861b102022-02-03 20:18:35 +0000886}
887
888void BLASTBufferQueue::stopContinuousSyncTransaction() {
889 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
890 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
891 {
892 std::lock_guard _lock{mMutex};
Chavi Weingartenc398c012023-04-12 17:26:02 +0000893 if (mAcquireSingleBuffer || !mTransactionReadyCallback) {
894 ALOGW("Attempting to stop continuous sync when none are active");
895 return;
Tianhao Yao4861b102022-02-03 20:18:35 +0000896 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000897
898 prevCallback = mTransactionReadyCallback;
899 prevTransaction = mSyncTransaction;
900
Tianhao Yao4861b102022-02-03 20:18:35 +0000901 mTransactionReadyCallback = nullptr;
902 mSyncTransaction = nullptr;
903 mAcquireSingleBuffer = true;
904 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000905
Tianhao Yao4861b102022-02-03 20:18:35 +0000906 if (prevCallback) {
907 prevCallback(prevTransaction);
908 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700909}
910
Chavi Weingartenc398c012023-04-12 17:26:02 +0000911void BLASTBufferQueue::clearSyncTransaction() {
912 std::lock_guard _lock{mMutex};
913 if (!mAcquireSingleBuffer) {
914 ALOGW("Attempting to clear sync transaction when none are active");
915 return;
916 }
917
918 mTransactionReadyCallback = nullptr;
919 mSyncTransaction = nullptr;
920}
921
Vishnu Nairea0de002020-11-17 17:42:37 -0800922bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700923 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
924 // Only reject buffers if scaling mode is freeze.
925 return false;
926 }
927
Chavi Weingarten70670e62023-02-22 17:36:40 +0000928 ui::Size bufferSize = getBufferSize(item);
Vishnu Nairea0de002020-11-17 17:42:37 -0800929 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800930 return false;
931 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700932
Vishnu Nair670b3f72020-09-29 17:52:18 -0700933 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800934 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700935}
Vishnu Nairbf255772020-10-16 10:54:41 -0700936
Robert Carr05086b22020-10-13 18:22:51 -0700937class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700938private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700939 std::mutex mMutex;
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000940 sp<BLASTBufferQueue> mBbq GUARDED_BY(mMutex);
941 bool mDestroyed GUARDED_BY(mMutex) = false;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700942
Robert Carr05086b22020-10-13 18:22:51 -0700943public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700944 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
945 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
946 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700947
Robert Carr05086b22020-10-13 18:22:51 -0700948 void allocateBuffers() override {
949 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
950 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
951 auto gbp = getIGraphicBufferProducer();
952 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
953 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
954 gbp->allocateBuffers(reqWidth, reqHeight,
955 reqFormat, reqUsage);
956
957 }).detach();
958 }
Robert Carr9c006e02020-10-14 13:41:57 -0700959
Marin Shalamanovc5986772021-03-16 16:09:49 +0100960 status_t setFrameRate(float frameRate, int8_t compatibility,
961 int8_t changeFrameRateStrategy) override {
Ady Abraham6cdd3fd2023-09-07 18:45:58 -0700962 if (flags::bq_setframerate()) {
963 return Surface::setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
964 }
965
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000966 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700967 if (mDestroyed) {
968 return DEAD_OBJECT;
969 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100970 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
971 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700972 return BAD_VALUE;
973 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100974 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700975 }
Robert Carr9b611b72020-10-19 12:00:23 -0700976
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800977 status_t setFrameTimelineInfo(uint64_t frameNumber,
978 const FrameTimelineInfo& frameTimelineInfo) override {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000979 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700980 if (mDestroyed) {
981 return DEAD_OBJECT;
982 }
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800983 return mBbq->setFrameTimelineInfo(frameNumber, frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700984 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700985
986 void destroy() override {
987 Surface::destroy();
988
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000989 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700990 mDestroyed = true;
991 mBbq = nullptr;
992 }
Robert Carr05086b22020-10-13 18:22:51 -0700993};
994
Robert Carr9c006e02020-10-14 13:41:57 -0700995// TODO: Can we coalesce this with frame updates? Need to confirm
996// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200997status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
998 bool shouldBeSeamless) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000999 std::lock_guard _lock{mMutex};
Robert Carr9c006e02020-10-14 13:41:57 -07001000 SurfaceComposerClient::Transaction t;
1001
Marin Shalamanov46084422020-10-13 12:33:42 +02001002 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -07001003}
1004
Ady Abrahamd6e409e2023-01-19 16:07:31 -08001005status_t BLASTBufferQueue::setFrameTimelineInfo(uint64_t frameNumber,
1006 const FrameTimelineInfo& frameTimelineInfo) {
1007 ATRACE_FORMAT("%s(%s) frameNumber: %" PRIu64 " vsyncId: %" PRId64, __func__, mName.c_str(),
1008 frameNumber, frameTimelineInfo.vsyncId);
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001009 std::lock_guard _lock{mMutex};
Ady Abrahamd6e409e2023-01-19 16:07:31 -08001010 mPendingFrameTimelines.push({frameNumber, frameTimelineInfo});
Jorim Jaggia3fe67b2020-12-01 00:24:33 +01001011 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -07001012}
1013
Hongguang Chen621ec582021-02-16 15:42:35 -08001014void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001015 std::lock_guard _lock{mMutex};
Hongguang Chen621ec582021-02-16 15:42:35 -08001016 SurfaceComposerClient::Transaction t;
1017
1018 t.setSidebandStream(mSurfaceControl, stream).apply();
1019}
1020
Vishnu Nair992496b2020-10-22 17:27:21 -07001021sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001022 std::lock_guard _lock{mMutex};
Vishnu Nair992496b2020-10-22 17:27:21 -07001023 sp<IBinder> scHandle = nullptr;
1024 if (includeSurfaceControlHandle && mSurfaceControl) {
1025 scHandle = mSurfaceControl->getHandle();
1026 }
1027 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -07001028}
1029
Vishnu Nairc4a40c12020-12-23 09:14:32 -08001030void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
1031 uint64_t frameNumber) {
1032 std::lock_guard _lock{mMutex};
1033 if (mLastAcquiredFrameNumber >= frameNumber) {
1034 // Apply the transaction since we have already acquired the desired frame.
1035 t->apply();
1036 } else {
chaviwaad6cf52021-03-23 17:27:20 -05001037 mPendingTransactions.emplace_back(frameNumber, *t);
1038 // Clear the transaction so it can't be applied elsewhere.
1039 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -08001040 }
1041}
1042
chaviw6a195272021-09-03 16:14:25 -05001043void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
1044 std::lock_guard _lock{mMutex};
1045
1046 SurfaceComposerClient::Transaction t;
1047 mergePendingTransactions(&t, frameNumber);
Robert Carr79dc06a2022-02-22 15:28:59 -08001048 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
1049 t.setApplyToken(mApplyToken).apply(false, true);
chaviw6a195272021-09-03 16:14:25 -05001050}
1051
1052void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
1053 uint64_t frameNumber) {
1054 auto mergeTransaction =
1055 [&t, currentFrameNumber = frameNumber](
1056 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
1057 auto& [targetFrameNumber, transaction] = pendingTransaction;
1058 if (currentFrameNumber < targetFrameNumber) {
1059 return false;
1060 }
1061 t->merge(std::move(transaction));
1062 return true;
1063 };
1064
1065 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
1066 mPendingTransactions.end(), mergeTransaction),
1067 mPendingTransactions.end());
1068}
1069
chaviwd84085a2022-02-08 11:07:04 -06001070SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
1071 uint64_t frameNumber) {
1072 std::lock_guard _lock{mMutex};
1073 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
1074 mergePendingTransactions(t, frameNumber);
1075 return t;
1076}
1077
Vishnu Nair89496122020-12-14 17:14:53 -08001078// Maintains a single worker thread per process that services a list of runnables.
1079class AsyncWorker : public Singleton<AsyncWorker> {
1080private:
1081 std::thread mThread;
1082 bool mDone = false;
1083 std::deque<std::function<void()>> mRunnables;
1084 std::mutex mMutex;
1085 std::condition_variable mCv;
1086 void run() {
1087 std::unique_lock<std::mutex> lock(mMutex);
1088 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -08001089 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001090 std::deque<std::function<void()>> runnables = std::move(mRunnables);
1091 mRunnables.clear();
1092 lock.unlock();
1093 // Run outside the lock since the runnable might trigger another
1094 // post to the async worker.
1095 execute(runnables);
1096 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -08001097 }
Wonsik Kim567533e2021-05-04 19:31:29 -07001098 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -08001099 }
1100 }
1101
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001102 void execute(std::deque<std::function<void()>>& runnables) {
1103 while (!runnables.empty()) {
1104 std::function<void()> runnable = runnables.front();
1105 runnables.pop_front();
1106 runnable();
1107 }
1108 }
1109
Vishnu Nair89496122020-12-14 17:14:53 -08001110public:
1111 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
1112
1113 ~AsyncWorker() {
1114 mDone = true;
1115 mCv.notify_all();
1116 if (mThread.joinable()) {
1117 mThread.join();
1118 }
1119 }
1120
1121 void post(std::function<void()> runnable) {
1122 std::unique_lock<std::mutex> lock(mMutex);
1123 mRunnables.emplace_back(std::move(runnable));
1124 mCv.notify_one();
1125 }
1126};
1127ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
1128
1129// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
1130class AsyncProducerListener : public BnProducerListener {
1131private:
1132 const sp<IProducerListener> mListener;
1133
1134public:
1135 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
1136
1137 void onBufferReleased() override {
1138 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
1139 }
1140
1141 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
1142 AsyncWorker::getInstance().post(
1143 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
1144 }
Sungtak Lee7c935092024-09-16 16:55:04 +00001145
1146 void onBufferDetached(int slot) override {
1147 AsyncWorker::getInstance().post(
1148 [listener = mListener, slot = slot]() { listener->onBufferDetached(slot); });
1149 }
1150
1151#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_CONSUMER_ATTACH_CALLBACK)
1152 void onBufferAttached() override {
1153 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferAttached(); });
1154 }
1155#endif
Vishnu Nair89496122020-12-14 17:14:53 -08001156};
1157
Patrick Williams078d7362024-08-27 10:20:39 -05001158#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1159class BBQBufferQueueCore : public BufferQueueCore {
1160public:
1161 explicit BBQBufferQueueCore(const wp<BLASTBufferQueue>& bbq) : mBLASTBufferQueue{bbq} {}
1162
1163 void notifyBufferReleased() const override {
1164 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1165 if (!bbq) {
1166 return;
1167 }
1168 bbq->mBufferReleaseReader->interruptBlockingRead();
1169 }
1170
1171private:
1172 wp<BLASTBufferQueue> mBLASTBufferQueue;
1173};
1174#endif
1175
Vishnu Nair89496122020-12-14 17:14:53 -08001176// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
1177// can be non-blocking when the producer is in the client process.
1178class BBQBufferQueueProducer : public BufferQueueProducer {
1179public:
Patrick Williamsca81c052024-08-15 12:38:34 -05001180 BBQBufferQueueProducer(const sp<BufferQueueCore>& core, const wp<BLASTBufferQueue>& bbq)
Brian Lindahlc794b692023-01-31 15:42:47 -07001181 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/),
Patrick Williamsca81c052024-08-15 12:38:34 -05001182 mBLASTBufferQueue(bbq) {}
Vishnu Nair89496122020-12-14 17:14:53 -08001183
1184 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
1185 QueueBufferOutput* output) override {
1186 if (!listener) {
1187 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
1188 }
1189
1190 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
1191 producerControlledByApp, output);
1192 }
Vishnu Nair17dde612020-12-28 11:39:59 -08001193
Brian Lindahlc794b692023-01-31 15:42:47 -07001194 // We want to resize the frame history when changing the size of the buffer queue
1195 status_t setMaxDequeuedBufferCount(int maxDequeuedBufferCount) override {
1196 int maxBufferCount;
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001197 if (status_t status = BufferQueueProducer::setMaxDequeuedBufferCount(maxDequeuedBufferCount,
1198 &maxBufferCount);
1199 status != OK) {
1200 return status;
Brian Lindahlc794b692023-01-31 15:42:47 -07001201 }
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001202
1203 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1204 if (!bbq) {
1205 return OK;
1206 }
1207
1208 // if we can't determine the max buffer count, then just skip growing the history size
1209 size_t newFrameHistorySize = maxBufferCount + 2; // +2 because triple buffer rendering
1210 // optimize away resizing the frame history unless it will grow
1211 if (newFrameHistorySize > FrameEventHistory::INITIAL_MAX_FRAME_HISTORY) {
1212 ALOGV("increasing frame history size to %zu", newFrameHistorySize);
1213 bbq->resizeFrameEventHistory(newFrameHistorySize);
1214 }
1215
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001216 return OK;
Brian Lindahlc794b692023-01-31 15:42:47 -07001217 }
1218
Vishnu Nair17dde612020-12-28 11:39:59 -08001219 int query(int what, int* value) override {
1220 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
1221 *value = 1;
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001222 return OK;
Vishnu Nair17dde612020-12-28 11:39:59 -08001223 }
1224 return BufferQueueProducer::query(what, value);
1225 }
Brian Lindahlc794b692023-01-31 15:42:47 -07001226
Patrick Williams078d7362024-08-27 10:20:39 -05001227#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1228 status_t waitForBufferRelease(std::unique_lock<std::mutex>& bufferQueueLock,
1229 nsecs_t timeout) const override {
1230 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1231 if (!bbq) {
1232 return OK;
1233 }
1234
1235 // BufferQueue has already checked if we have a free buffer. If there's an unread interrupt,
1236 // we want to ignore it. This must be done before unlocking the BufferQueue lock to ensure
1237 // we don't miss an interrupt.
1238 bbq->mBufferReleaseReader->clearInterrupts();
Patrick Williamsc16a4a52024-10-26 01:48:01 -05001239 UnlockGuard unlockGuard{bufferQueueLock};
Patrick Williams078d7362024-08-27 10:20:39 -05001240
1241 ATRACE_FORMAT("waiting for free buffer");
1242 ReleaseCallbackId id;
1243 sp<Fence> fence;
1244 uint32_t maxAcquiredBufferCount;
1245 status_t status =
1246 bbq->mBufferReleaseReader->readBlocking(id, fence, maxAcquiredBufferCount, timeout);
1247 if (status == TIMED_OUT) {
1248 return TIMED_OUT;
1249 } else if (status != OK) {
1250 // Waiting was interrupted or an error occurred. BufferQueueProducer will check if we
1251 // have a free buffer and call this method again if not.
1252 return OK;
1253 }
1254
1255 bbq->releaseBufferCallback(id, fence, maxAcquiredBufferCount);
1256 return OK;
1257 }
1258#endif
1259
Brian Lindahlc794b692023-01-31 15:42:47 -07001260private:
1261 const wp<BLASTBufferQueue> mBLASTBufferQueue;
Vishnu Nair89496122020-12-14 17:14:53 -08001262};
1263
1264// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
1265// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
1266// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
1267// we can deadlock.
1268void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
1269 sp<IGraphicBufferConsumer>* outConsumer) {
1270 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
1271 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
1272
Patrick Williams078d7362024-08-27 10:20:39 -05001273#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1274 auto core = sp<BBQBufferQueueCore>::make(this);
1275#else
1276 auto core = sp<BufferQueueCore>::make();
1277#endif
Vishnu Nair89496122020-12-14 17:14:53 -08001278 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
1279
Patrick Williams078d7362024-08-27 10:20:39 -05001280 auto producer = sp<BBQBufferQueueProducer>::make(core, this);
Vishnu Nair89496122020-12-14 17:14:53 -08001281 LOG_ALWAYS_FATAL_IF(producer == nullptr,
1282 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
1283
Patrick Williams078d7362024-08-27 10:20:39 -05001284 auto consumer = sp<BufferQueueConsumer>::make(core);
Vishnu Nair8b30dd12021-01-25 14:16:54 -08001285 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -08001286 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
1287 "BLASTBufferQueue: failed to create BufferQueueConsumer");
1288
1289 *outProducer = producer;
1290 *outConsumer = consumer;
1291}
1292
Brian Lindahlc794b692023-01-31 15:42:47 -07001293void BLASTBufferQueue::resizeFrameEventHistory(size_t newSize) {
1294 // This can be null during creation of the buffer queue, but resizing won't do anything at that
1295 // point in time, so just ignore. This can go away once the class relationships and lifetimes of
1296 // objects are cleaned up with a major refactor of BufferQueue as a whole.
1297 if (mBufferItemConsumer != nullptr) {
1298 std::unique_lock _lock{mMutex};
1299 mBufferItemConsumer->resizeFrameEventHistory(newSize);
1300 }
1301}
1302
chaviw497e81c2021-02-04 17:09:47 -08001303PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
1304 PixelFormat convertedFormat = format;
1305 switch (format) {
1306 case PIXEL_FORMAT_TRANSPARENT:
1307 case PIXEL_FORMAT_TRANSLUCENT:
1308 convertedFormat = PIXEL_FORMAT_RGBA_8888;
1309 break;
1310 case PIXEL_FORMAT_OPAQUE:
1311 convertedFormat = PIXEL_FORMAT_RGBX_8888;
1312 break;
1313 }
1314 return convertedFormat;
1315}
1316
Robert Carr82d07c92021-05-10 11:36:43 -07001317uint32_t BLASTBufferQueue::getLastTransformHint() const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001318 std::lock_guard _lock{mMutex};
Robert Carr82d07c92021-05-10 11:36:43 -07001319 if (mSurfaceControl != nullptr) {
1320 return mSurfaceControl->getTransformHint();
1321 } else {
1322 return 0;
1323 }
1324}
1325
chaviw0b020f82021-08-20 12:00:47 -05001326uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001327 std::lock_guard _lock{mMutex};
chaviw0b020f82021-08-20 12:00:47 -05001328 return mLastAcquiredFrameNumber;
1329}
1330
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001331bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001332 std::lock_guard _lock{mMutex};
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001333 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1334}
1335
Patrick Williamsf1e5df12022-10-17 21:37:42 +00001336void BLASTBufferQueue::setTransactionHangCallback(
1337 std::function<void(const std::string&)> callback) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001338 std::lock_guard _lock{mMutex};
Patrick Williams7c9fa272024-08-30 12:38:43 +00001339 mTransactionHangCallback = std::move(callback);
Robert Carr4c1b6462021-12-21 10:30:50 -08001340}
1341
Vishnu Nairaf15fab2024-07-30 08:59:26 -07001342void BLASTBufferQueue::setApplyToken(sp<IBinder> applyToken) {
1343 std::lock_guard _lock{mMutex};
1344 mApplyToken = std::move(applyToken);
1345}
1346
Patrick Williams7c9fa272024-08-30 12:38:43 +00001347#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1348
Patrick Williamsa419faa2024-10-29 16:50:27 -05001349void BLASTBufferQueue::updateBufferReleaseProducer() {
1350 // SELinux policy may prevent this process from sending the BufferReleaseChannel's file
1351 // descriptor to SurfaceFlinger, causing the entire transaction to be dropped. We send this
1352 // transaction independently of any other updates to ensure those updates aren't lost.
1353 SurfaceComposerClient::Transaction t;
1354 status_t status = t.setApplyToken(mApplyToken)
1355 .setBufferReleaseChannel(mSurfaceControl, mBufferReleaseProducer)
1356 .apply(false /* synchronous */, true /* oneWay */);
1357 if (status != OK) {
1358 ALOGW("[%s] %s - failed to set buffer release channel on %s", mName.c_str(),
1359 statusToString(status).c_str(), mSurfaceControl->getName().c_str());
1360 }
1361}
1362
Patrick Williamsc16a4a52024-10-26 01:48:01 -05001363void BLASTBufferQueue::drainBufferReleaseConsumer() {
1364 ATRACE_CALL();
1365 while (true) {
1366 ReleaseCallbackId id;
1367 sp<Fence> fence;
1368 uint32_t maxAcquiredBufferCount;
1369 status_t status =
1370 mBufferReleaseConsumer->readReleaseFence(id, fence, maxAcquiredBufferCount);
1371 if (status != OK) {
1372 return;
1373 }
1374 releaseBufferCallback(id, fence, maxAcquiredBufferCount);
1375 }
1376}
1377
Patrick Williams078d7362024-08-27 10:20:39 -05001378BLASTBufferQueue::BufferReleaseReader::BufferReleaseReader(BLASTBufferQueue& bbq) : mBbq{bbq} {
1379 mEpollFd = android::base::unique_fd{epoll_create1(EPOLL_CLOEXEC)};
Patrick Williams7c9fa272024-08-30 12:38:43 +00001380 LOG_ALWAYS_FATAL_IF(!mEpollFd.ok(),
1381 "Failed to create buffer release epoll file descriptor. errno=%d "
1382 "message='%s'",
1383 errno, strerror(errno));
1384
1385 epoll_event registerEndpointFd{};
1386 registerEndpointFd.events = EPOLLIN;
Patrick Williams078d7362024-08-27 10:20:39 -05001387 registerEndpointFd.data.fd = mBbq.mBufferReleaseConsumer->getFd();
1388 status_t status = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mBbq.mBufferReleaseConsumer->getFd(),
1389 &registerEndpointFd);
Patrick Williams7c9fa272024-08-30 12:38:43 +00001390 LOG_ALWAYS_FATAL_IF(status == -1,
1391 "Failed to register buffer release consumer file descriptor with epoll. "
1392 "errno=%d message='%s'",
1393 errno, strerror(errno));
1394
1395 mEventFd = android::base::unique_fd(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK));
1396 LOG_ALWAYS_FATAL_IF(!mEventFd.ok(),
1397 "Failed to create buffer release event file descriptor. errno=%d "
1398 "message='%s'",
1399 errno, strerror(errno));
1400
1401 epoll_event registerEventFd{};
1402 registerEventFd.events = EPOLLIN;
1403 registerEventFd.data.fd = mEventFd.get();
1404 status = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mEventFd.get(), &registerEventFd);
1405 LOG_ALWAYS_FATAL_IF(status == -1,
1406 "Failed to register buffer release event file descriptor with epoll. "
1407 "errno=%d message='%s'",
1408 errno, strerror(errno));
1409}
1410
Patrick Williams7c9fa272024-08-30 12:38:43 +00001411status_t BLASTBufferQueue::BufferReleaseReader::readBlocking(ReleaseCallbackId& outId,
1412 sp<Fence>& outFence,
Patrick Williams078d7362024-08-27 10:20:39 -05001413 uint32_t& outMaxAcquiredBufferCount,
1414 nsecs_t timeout) {
1415 // TODO(b/363290953) epoll_wait only has millisecond timeout precision. If timeout is less than
1416 // 1ms, then we round timeout up to 1ms. Otherwise, we round timeout to the nearest
1417 // millisecond. Once epoll_pwait2 can be used in libgui, we can specify timeout with nanosecond
1418 // precision.
1419 int timeoutMs = -1;
1420 if (timeout == 0) {
1421 timeoutMs = 0;
1422 } else if (timeout > 0) {
1423 const int nsPerMs = 1000000;
1424 if (timeout < nsPerMs) {
1425 timeoutMs = 1;
1426 } else {
1427 timeoutMs = static_cast<int>(
1428 std::chrono::round<std::chrono::milliseconds>(std::chrono::nanoseconds{timeout})
1429 .count());
1430 }
1431 }
1432
Patrick Williams7c9fa272024-08-30 12:38:43 +00001433 epoll_event event{};
Patrick Williams078d7362024-08-27 10:20:39 -05001434 int eventCount;
1435 do {
1436 eventCount = epoll_wait(mEpollFd.get(), &event, 1 /*maxevents*/, timeoutMs);
1437 } while (eventCount == -1 && errno != EINTR);
1438
1439 if (eventCount == -1) {
1440 ALOGE("epoll_wait error while waiting for buffer release. errno=%d message='%s'", errno,
1441 strerror(errno));
1442 return UNKNOWN_ERROR;
1443 }
1444
1445 if (eventCount == 0) {
1446 return TIMED_OUT;
Patrick Williams7c9fa272024-08-30 12:38:43 +00001447 }
1448
1449 if (event.data.fd == mEventFd.get()) {
Patrick Williams078d7362024-08-27 10:20:39 -05001450 clearInterrupts();
Patrick Williams7c9fa272024-08-30 12:38:43 +00001451 return WOULD_BLOCK;
1452 }
1453
Patrick Williams078d7362024-08-27 10:20:39 -05001454 return mBbq.mBufferReleaseConsumer->readReleaseFence(outId, outFence,
1455 outMaxAcquiredBufferCount);
Patrick Williams7c9fa272024-08-30 12:38:43 +00001456}
1457
1458void BLASTBufferQueue::BufferReleaseReader::interruptBlockingRead() {
Patrick Williams078d7362024-08-27 10:20:39 -05001459 if (eventfd_write(mEventFd.get(), 1) == -1) {
Patrick Williams7c9fa272024-08-30 12:38:43 +00001460 ALOGE("failed to notify dequeue event. errno=%d message='%s'", errno, strerror(errno));
1461 }
1462}
1463
Patrick Williams078d7362024-08-27 10:20:39 -05001464void BLASTBufferQueue::BufferReleaseReader::clearInterrupts() {
1465 eventfd_t value;
1466 if (eventfd_read(mEventFd.get(), &value) == -1 && errno != EWOULDBLOCK) {
1467 ALOGE("error while reading from eventfd. errno=%d message='%s'", errno, strerror(errno));
1468 }
1469}
1470
Patrick Williams7c9fa272024-08-30 12:38:43 +00001471#endif
1472
Robert Carr78c25dd2019-08-15 14:10:33 -07001473} // namespace android