blob: ddf5d394bf836f63fca9ecc035ea997a9930d5d8 [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)
Anton Ivanov81793802025-02-13 22:57:24 -0800200 mBufferItemConsumer = sp<BLASTBufferItemConsumer>::make(mProducer, mConsumer,
201 GraphicBuffer::USAGE_HW_COMPOSER |
202 GraphicBuffer::USAGE_HW_TEXTURE,
203 1, false, this);
Jim Shargod30823a2024-07-27 02:49:39 +0000204#else
Anton Ivanov81793802025-02-13 22:57:24 -0800205 mBufferItemConsumer = sp<BLASTBufferItemConsumer>::make(mConsumer,
206 GraphicBuffer::USAGE_HW_COMPOSER |
207 GraphicBuffer::USAGE_HW_TEXTURE,
208 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
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800247BLASTBufferQueue::~BLASTBufferQueue() {
Robert Carr4c1b6462021-12-21 10:30:50 -0800248 TransactionCompletedListener::getInstance()->removeQueueStallListener(this);
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800249 if (mPendingTransactions.empty()) {
250 return;
251 }
252 BQA_LOGE("Applying pending transactions on dtor %d",
253 static_cast<uint32_t>(mPendingTransactions.size()));
254 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800255 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
Robert Carr79dc06a2022-02-22 15:28:59 -0800256 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
257 t.setApplyToken(mApplyToken).apply(false, true);
chaviw3b4bdcf2022-03-17 09:27:03 -0500258
259 if (mTransactionReadyCallback) {
260 mTransactionReadyCallback(mSyncTransaction);
261 }
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800262}
263
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500264void BLASTBufferQueue::onFirstRef() {
265 // safe default, most producers are expected to override this
266 mProducer->setMaxDequeuedBufferCount(2);
267}
268
chaviw565ee542021-01-14 10:21:23 -0800269void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Naird2aaab12022-02-10 14:49:09 -0800270 int32_t format) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800271 LOG_ALWAYS_FATAL_IF(surface == nullptr, "BLASTBufferQueue: mSurfaceControl must not be NULL");
272
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000273 std::lock_guard _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800274 if (mFormat != format) {
275 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800276 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800277 }
278
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800279 const bool surfaceControlChanged = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairab066512022-01-04 22:28:00 +0000280 if (surfaceControlChanged && mSurfaceControl != nullptr) {
281 BQA_LOGD("Updating SurfaceControl without recreating BBQ");
282 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800283
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700284 // Always update the native object even though they might have the same layer handle, so we can
285 // get the updated transform hint from WM.
286 mSurfaceControl = surface;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800287 SurfaceComposerClient::Transaction t;
Brian Lindahl628cff42024-10-30 11:50:28 -0600288 bool applyTransaction = false;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800289 if (surfaceControlChanged) {
Patrick Williamsc16a4a52024-10-26 01:48:01 -0500290#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
Patrick Williamsa419faa2024-10-29 16:50:27 -0500291 updateBufferReleaseProducer();
Patrick Williamsc16a4a52024-10-26 01:48:01 -0500292#endif
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800293 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
294 layer_state_t::eEnableBackpressure);
Brian Lindahl628cff42024-10-30 11:50:28 -0600295 // Migrate the picture profile handle to the new surface control.
296 if (com_android_graphics_libgui_flags_apply_picture_profiles() &&
297 mPictureProfileHandle.has_value()) {
298 t.setPictureProfileHandle(mSurfaceControl, *mPictureProfileHandle);
299 }
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800300 applyTransaction = true;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800301 }
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800302 mTransformHint = mSurfaceControl->getTransformHint();
303 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700304 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
305 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800306
Vishnu Nairea0de002020-11-17 17:42:37 -0800307 ui::Size newSize(width, height);
308 if (mRequestedSize != newSize) {
309 mRequestedSize.set(newSize);
310 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000311 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800312 // If the buffer supports scaling, update the frame immediately since the client may
313 // want to scale the existing buffer to the new size.
314 mSize = mRequestedSize;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800315 if (mUpdateDestinationFrame) {
316 t.setDestinationFrame(mSurfaceControl, Rect(newSize));
317 applyTransaction = true;
318 }
Vishnu Nair53c936c2020-12-03 11:46:37 -0800319 }
Robert Carrfc416512020-04-02 12:32:44 -0700320 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800321 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800322 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
Patrick Williamsc16a4a52024-10-26 01:48:01 -0500323 t.setApplyToken(mApplyToken).apply(false /* synchronous */, true /* oneWay */);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800324 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700325}
326
chaviwd7deef72021-10-06 11:53:40 -0500327static std::optional<SurfaceControlStats> findMatchingStat(
328 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
329 for (auto stat : stats) {
330 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
331 return stat;
332 }
333 }
334 return std::nullopt;
335}
336
Patrick Williams5312ec12024-08-23 16:11:10 -0500337TransactionCompletedCallbackTakesContext BLASTBufferQueue::makeTransactionCommittedCallbackThunk() {
338 return [bbq = sp<BLASTBufferQueue>::fromExisting(
339 this)](void* /*context*/, nsecs_t latchTime, const sp<Fence>& presentFence,
340 const std::vector<SurfaceControlStats>& stats) {
341 bbq->transactionCommittedCallback(latchTime, presentFence, stats);
342 };
chaviwd7deef72021-10-06 11:53:40 -0500343}
344
345void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
346 const sp<Fence>& /*presentFence*/,
347 const std::vector<SurfaceControlStats>& stats) {
348 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000349 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600350 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500351 BQA_LOGV("transactionCommittedCallback");
352 if (!mSurfaceControlsWithPendingCallback.empty()) {
353 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
354 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
355 if (stat) {
356 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
357
358 // We need to check if we were waiting for a transaction callback in order to
359 // process any pending buffers and unblock. It's possible to get transaction
chaviwc1cf4022022-06-03 13:32:33 -0500360 // callbacks for previous requests so we need to ensure that there are no pending
361 // frame numbers that were in a sync. We remove the frame from mSyncedFrameNumbers
362 // set and then check if it's empty. If there are no more pending syncs, we can
363 // proceed with flushing the shadow queue.
chaviwc1cf4022022-06-03 13:32:33 -0500364 mSyncedFrameNumbers.erase(currFrameNumber);
Chavi Weingartend48797b2023-08-04 13:11:39 +0000365 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500366 flushShadowQueue();
367 }
368 } else {
chaviw768bfa02021-11-01 09:50:57 -0500369 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviwd7deef72021-10-06 11:53:40 -0500370 }
371 } else {
372 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
373 "empty.");
374 }
chaviwd7deef72021-10-06 11:53:40 -0500375 }
376}
377
Patrick Williams5312ec12024-08-23 16:11:10 -0500378TransactionCompletedCallbackTakesContext BLASTBufferQueue::makeTransactionCallbackThunk() {
379 return [bbq = sp<BLASTBufferQueue>::fromExisting(
380 this)](void* /*context*/, nsecs_t latchTime, const sp<Fence>& presentFence,
381 const std::vector<SurfaceControlStats>& stats) {
382 bbq->transactionCallback(latchTime, presentFence, stats);
383 };
Robert Carr78c25dd2019-08-15 14:10:33 -0700384}
385
386void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
387 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700388 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000389 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600390 BBQ_TRACE();
chaviw71c2cc42020-10-23 16:42:02 -0700391 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700392
chaviw42026162021-04-16 15:46:12 -0500393 if (!mSurfaceControlsWithPendingCallback.empty()) {
394 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
395 mSurfaceControlsWithPendingCallback.pop();
chaviwd7deef72021-10-06 11:53:40 -0500396 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
397 if (statsOptional) {
398 SurfaceControlStats stat = *statsOptional;
Vishnu Nair71fcf912022-10-18 09:14:20 -0700399 if (stat.transformHint) {
400 mTransformHint = *stat.transformHint;
401 mBufferItemConsumer->setTransformHint(mTransformHint);
402 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
403 }
Vishnu Nairde66dc72021-06-17 17:54:41 -0700404 // Update frametime stamps if the frame was latched and presented, indicated by a
405 // valid latch time.
406 if (stat.latchTime > 0) {
407 mBufferItemConsumer
408 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
Alec Mouri21d94322023-10-17 19:51:39 +0000409 stat.frameEventStats.previousFrameNumber,
Vishnu Nairde66dc72021-06-17 17:54:41 -0700410 stat.frameEventStats.refreshStartTime,
411 stat.frameEventStats.gpuCompositionDoneFence,
412 stat.presentFence, stat.previousReleaseFence,
413 stat.frameEventStats.compositorTiming,
414 stat.latchTime,
415 stat.frameEventStats.dequeueReadyTime);
416 }
Robert Carr405e2f62021-12-31 16:59:34 -0800417 auto currFrameNumber = stat.frameEventStats.frameNumber;
418 std::vector<ReleaseCallbackId> staleReleases;
419 for (const auto& [key, value]: mSubmitted) {
420 if (currFrameNumber > key.framenumber) {
421 staleReleases.push_back(key);
422 }
423 }
424 for (const auto& staleRelease : staleReleases) {
Robert Carr405e2f62021-12-31 16:59:34 -0800425 releaseBufferCallbackLocked(staleRelease,
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700426 stat.previousReleaseFence
427 ? stat.previousReleaseFence
428 : Fence::NO_FENCE,
429 stat.currentMaxAcquiredBufferCount,
430 true /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800431 }
chaviwd7deef72021-10-06 11:53:40 -0500432 } else {
chaviw768bfa02021-11-01 09:50:57 -0500433 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500434 }
435 } else {
436 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
437 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800438 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700439 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700440}
441
Patrick Williams7c9fa272024-08-30 12:38:43 +0000442void BLASTBufferQueue::flushShadowQueue() {
443 BQA_LOGV("flushShadowQueue");
444 int numFramesToFlush = mNumFrameAvailable;
445 while (numFramesToFlush > 0) {
446 acquireNextBufferLocked(std::nullopt);
447 numFramesToFlush--;
448 }
449}
450
Vishnu Nair1506b182021-02-22 14:35:15 -0800451// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
452// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
453// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
454// Otherwise, this is a no-op.
Patrick Williams5312ec12024-08-23 16:11:10 -0500455ReleaseBufferCallback BLASTBufferQueue::makeReleaseBufferCallbackThunk() {
456 return [weakBbq = wp<BLASTBufferQueue>::fromExisting(
457 this)](const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
458 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
459 sp<BLASTBufferQueue> bbq = weakBbq.promote();
460 if (!bbq) {
461 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
462 return;
463 }
464 bbq->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
Patrick Williamsc16a4a52024-10-26 01:48:01 -0500465#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
466 bbq->drainBufferReleaseConsumer();
467#endif
Patrick Williams5312ec12024-08-23 16:11:10 -0500468 };
Vishnu Nair1506b182021-02-22 14:35:15 -0800469}
470
chaviw69058fb2021-09-27 09:37:30 -0500471void BLASTBufferQueue::releaseBufferCallback(
472 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
473 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000474 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600475 BBQ_TRACE();
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700476 releaseBufferCallbackLocked(id, releaseFence, currentMaxAcquiredBufferCount,
477 false /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800478}
479
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700480void BLASTBufferQueue::releaseBufferCallbackLocked(
481 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
482 std::optional<uint32_t> currentMaxAcquiredBufferCount, bool fakeRelease) {
Robert Carr405e2f62021-12-31 16:59:34 -0800483 ATRACE_CALL();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700484 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800485
Ady Abraham899dcdb2021-06-15 16:56:21 -0700486 // Calculate how many buffers we need to hold before we release them back
487 // to the buffer queue. This will prevent higher latency when we are running
488 // on a lower refresh rate than the max supported. We only do that for EGL
489 // clients as others don't care about latency
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000490 const auto it = mSubmitted.find(id);
491 const bool isEGL = it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
Ady Abraham899dcdb2021-06-15 16:56:21 -0700492
chaviw69058fb2021-09-27 09:37:30 -0500493 if (currentMaxAcquiredBufferCount) {
494 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
495 }
496
liulijunf90df632022-11-14 14:24:48 +0800497 const uint32_t numPendingBuffersToHold =
498 isEGL ? std::max(0, mMaxAcquiredBuffers - (int32_t)mCurrentMaxAcquiredBufferCount) : 0;
Robert Carr405e2f62021-12-31 16:59:34 -0800499
500 auto rb = ReleasedBuffer{id, releaseFence};
501 if (std::find(mPendingRelease.begin(), mPendingRelease.end(), rb) == mPendingRelease.end()) {
502 mPendingRelease.emplace_back(rb);
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700503 if (fakeRelease) {
504 BQA_LOGE("Faking releaseBufferCallback from transactionCompleteCallback %" PRIu64,
505 id.framenumber);
506 BBQ_TRACE("FakeReleaseCallback");
507 }
Robert Carr405e2f62021-12-31 16:59:34 -0800508 }
Ady Abraham899dcdb2021-06-15 16:56:21 -0700509
510 // Release all buffers that are beyond the ones that we need to hold
511 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500512 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700513 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500514 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwc1cf4022022-06-03 13:32:33 -0500515 // Don't process the transactions here if mSyncedFrameNumbers is not empty. That means
516 // are still transactions that have sync buffers in them that have not been applied or
517 // dropped. Instead, let onFrameAvailable handle processing them since it will merge with
518 // the syncTransaction.
519 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500520 acquireNextBufferLocked(std::nullopt);
521 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800522 }
523
Ady Abraham899dcdb2021-06-15 16:56:21 -0700524 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700525 ATRACE_INT(mQueuedBufferTrace.c_str(),
526 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800527 mCallbackCV.notify_all();
528}
529
chaviw0acd33a2021-11-02 11:55:37 -0500530void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
531 const sp<Fence>& releaseFence) {
532 auto it = mSubmitted.find(callbackId);
533 if (it == mSubmitted.end()) {
chaviw0acd33a2021-11-02 11:55:37 -0500534 return;
535 }
536 mNumAcquired--;
chaviw57ae4b22022-02-03 16:51:39 -0600537 BBQ_TRACE("frame=%" PRIu64, callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500538 BQA_LOGV("released %s", callbackId.to_string().c_str());
539 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
540 mSubmitted.erase(it);
chaviwc1cf4022022-06-03 13:32:33 -0500541 // Remove the frame number from mSyncedFrameNumbers since we can get a release callback
542 // without getting a transaction committed if the buffer was dropped.
543 mSyncedFrameNumbers.erase(callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500544}
545
Chavi Weingarten70670e62023-02-22 17:36:40 +0000546static ui::Size getBufferSize(const BufferItem& item) {
547 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
548 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
549
550 // Take the buffer's orientation into account
551 if (item.mTransform & ui::Transform::ROT_90) {
552 std::swap(bufWidth, bufHeight);
553 }
554 return ui::Size(bufWidth, bufHeight);
555}
556
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000557status_t BLASTBufferQueue::acquireNextBufferLocked(
chaviwd7deef72021-10-06 11:53:40 -0500558 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800559 // Check if we have frames available and we have not acquired the maximum number of buffers.
560 // Even with this check, the consumer can fail to acquire an additional buffer if the consumer
561 // has already acquired (mMaxAcquiredBuffers + 1) and the new buffer is not droppable. In this
562 // case mBufferItemConsumer->acquireBuffer will return with NO_BUFFER_AVAILABLE.
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000563 if (mNumFrameAvailable == 0) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800564 BQA_LOGV("Can't acquire next buffer. No available frames");
565 return BufferQueue::NO_BUFFER_AVAILABLE;
566 }
567
568 if (mNumAcquired >= (mMaxAcquiredBuffers + 2)) {
569 BQA_LOGV("Can't acquire next buffer. Already acquired max frames %d max:%d + 2",
570 mNumAcquired, mMaxAcquiredBuffers);
571 return BufferQueue::NO_BUFFER_AVAILABLE;
Valerie Haud3b90d22019-11-06 09:37:31 -0800572 }
573
Valerie Haua32c5522019-12-09 10:11:08 -0800574 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700575 BQA_LOGE("ERROR : surface control is null");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000576 return NAME_NOT_FOUND;
Valerie Haud3b90d22019-11-06 09:37:31 -0800577 }
578
Robert Carr78c25dd2019-08-15 14:10:33 -0700579 SurfaceComposerClient::Transaction localTransaction;
580 bool applyTransaction = true;
581 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500582 if (transaction) {
583 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700584 applyTransaction = false;
585 }
586
Patrick Williams3ced5382024-08-21 15:39:32 -0500587 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800588
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800589 status_t status =
590 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800591 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
592 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000593 return status;
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800594 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700595 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000596 return status;
Robert Carr78c25dd2019-08-15 14:10:33 -0700597 }
chaviw57ae4b22022-02-03 16:51:39 -0600598
Valerie Haua32c5522019-12-09 10:11:08 -0800599 auto buffer = bufferItem.mGraphicBuffer;
600 mNumFrameAvailable--;
chaviw57ae4b22022-02-03 16:51:39 -0600601 BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800602
603 if (buffer == nullptr) {
604 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700605 BQA_LOGE("Buffer was empty");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000606 return BAD_VALUE;
Valerie Haua32c5522019-12-09 10:11:08 -0800607 }
608
Vishnu Nair670b3f72020-09-29 17:52:18 -0700609 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700610 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800611 "buffer{size=%dx%d transform=%d}",
612 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
613 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
614 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000615 return acquireNextBufferLocked(transaction);
Vishnu Nair670b3f72020-09-29 17:52:18 -0700616 }
617
Valerie Haua32c5522019-12-09 10:11:08 -0800618 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700619 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
620 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
621 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700622
Valerie Hau871d6352020-01-29 08:44:02 -0800623 bool needsDisconnect = false;
624 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
625
626 // if producer disconnected before, notify SurfaceFlinger
627 if (needsDisconnect) {
628 t->notifyProducerDisconnect(mSurfaceControl);
629 }
630
Chavi Weingarten70670e62023-02-22 17:36:40 +0000631 // Only update mSize for destination bounds if the incoming buffer matches the requested size.
632 // Otherwise, it could cause stretching since the destination bounds will update before the
633 // buffer with the new size is acquired.
Vishnu Nair5b5f6932023-04-12 16:28:19 -0700634 if (mRequestedSize == getBufferSize(bufferItem) ||
635 bufferItem.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Chavi Weingarten70670e62023-02-22 17:36:40 +0000636 mSize = mRequestedSize;
637 }
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700638 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000639 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
640 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700641 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800642
Patrick Williams5312ec12024-08-23 16:11:10 -0500643 auto releaseBufferCallback = makeReleaseBufferCallbackThunk();
Anton Ivanov81793802025-02-13 22:57:24 -0800644 sp<Fence> fence =
645 bufferItem.mFence ? sp<Fence>::make(bufferItem.mFence->dup()) : Fence::NO_FENCE;
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900646
647 nsecs_t dequeueTime = -1;
648 {
649 std::lock_guard _lock{mTimestampMutex};
650 auto dequeueTimeIt = mDequeueTimestamps.find(buffer->getId());
651 if (dequeueTimeIt != mDequeueTimestamps.end()) {
652 dequeueTime = dequeueTimeIt->second;
653 mDequeueTimestamps.erase(dequeueTimeIt);
654 }
655 }
656
liulijuneb489f62022-10-17 22:02:14 +0800657 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, mProducerId,
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900658 releaseBufferCallback, dequeueTime);
John Reck137069e2020-12-10 22:07:37 -0500659 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
660 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
661 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Patrick Williams5312ec12024-08-23 16:11:10 -0500662 t->addTransactionCompletedCallback(makeTransactionCallbackThunk(), nullptr);
chaviwf2dace72021-11-17 17:36:50 -0600663
chaviw42026162021-04-16 15:46:12 -0500664 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700665
Vishnu Naird2aaab12022-02-10 14:49:09 -0800666 if (mUpdateDestinationFrame) {
667 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
668 } else {
669 const bool ignoreDestinationFrame =
670 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
671 t->setFlags(mSurfaceControl,
672 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
673 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700674 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700675 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800676 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800677 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800678 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800679 if (!bufferItem.mIsAutoTimestamp) {
680 t->setDesiredPresentTime(bufferItem.mTimestamp);
681 }
Brian Lindahl628cff42024-10-30 11:50:28 -0600682 if (com_android_graphics_libgui_flags_apply_picture_profiles() &&
683 bufferItem.mPictureProfileHandle.has_value()) {
684 t->setPictureProfileHandle(mSurfaceControl, *bufferItem.mPictureProfileHandle);
685 // The current picture profile must be maintained in case the BBQ gets its
686 // SurfaceControl switched out.
687 mPictureProfileHandle = bufferItem.mPictureProfileHandle;
688 // Clear out the picture profile if the requestor has asked for it to be cleared
689 if (mPictureProfileHandle == PictureProfileHandle::NONE) {
690 mPictureProfileHandle = std::nullopt;
691 }
692 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700693
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800694 // Drop stale frame timeline infos
695 while (!mPendingFrameTimelines.empty() &&
696 mPendingFrameTimelines.front().first < bufferItem.mFrameNumber) {
697 ATRACE_FORMAT_INSTANT("dropping stale frameNumber: %" PRIu64 " vsyncId: %" PRId64,
698 mPendingFrameTimelines.front().first,
699 mPendingFrameTimelines.front().second.vsyncId);
700 mPendingFrameTimelines.pop();
701 }
702
703 if (!mPendingFrameTimelines.empty() &&
704 mPendingFrameTimelines.front().first == bufferItem.mFrameNumber) {
705 ATRACE_FORMAT_INSTANT("Transaction::setFrameTimelineInfo frameNumber: %" PRIu64
706 " vsyncId: %" PRId64,
707 bufferItem.mFrameNumber,
708 mPendingFrameTimelines.front().second.vsyncId);
709 t->setFrameTimelineInfo(mPendingFrameTimelines.front().second);
710 mPendingFrameTimelines.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100711 }
712
chaviw6a195272021-09-03 16:14:25 -0500713 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700714 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800715 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
716 t->setApplyToken(mApplyToken).apply(false, true);
717 mAppliedLastTransaction = true;
718 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
719 } else {
720 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
721 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700722 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700723
chaviwd7deef72021-10-06 11:53:40 -0500724 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800725 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700726 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500727 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800728 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700729 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700730 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000731 return OK;
Robert Carr78c25dd2019-08-15 14:10:33 -0700732}
733
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800734Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
735 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800736 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800737 }
738 return item.mCrop;
739}
740
chaviwd7deef72021-10-06 11:53:40 -0500741void BLASTBufferQueue::acquireAndReleaseBuffer() {
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000742 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500743 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500744 status_t status =
745 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
746 if (status != OK) {
747 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
748 statusToString(status).c_str());
749 return;
750 }
chaviwd7deef72021-10-06 11:53:40 -0500751 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500752 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500753}
754
Vishnu Nairaef1de92020-10-22 12:15:53 -0700755void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000756 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
757 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
chaviwc1cf4022022-06-03 13:32:33 -0500758
Tianhao Yao4861b102022-02-03 20:18:35 +0000759 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000760 UNIQUE_LOCK_WITH_ASSERTION(mMutex);
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000761 BBQ_TRACE();
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000762 bool waitForTransactionCallback = !mSyncedFrameNumbers.empty();
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800763
Tianhao Yao4861b102022-02-03 20:18:35 +0000764 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
765 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800766
Tianhao Yao4861b102022-02-03 20:18:35 +0000767 if (syncTransactionSet) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000768 // If we are going to re-use the same mSyncTransaction, release the buffer that may
769 // already be set in the Transaction. This is to allow us a free slot early to continue
770 // processing a new buffer.
771 if (!mAcquireSingleBuffer) {
772 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
773 if (bufferData) {
774 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
775 bufferData->frameNumber);
776 releaseBuffer(bufferData->generateReleaseCallbackId(),
777 bufferData->acquireFence);
Tianhao Yao4861b102022-02-03 20:18:35 +0000778 }
779 }
chaviw0acd33a2021-11-02 11:55:37 -0500780
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000781 if (waitForTransactionCallback) {
782 // We are waiting on a previous sync's transaction callback so allow another sync
783 // transaction to proceed.
784 //
785 // We need to first flush out the transactions that were in between the two syncs.
786 // We do this by merging them into mSyncTransaction so any buffer merging will get
787 // a release callback invoked.
788 while (mNumFrameAvailable > 0) {
789 // flush out the shadow queue
790 acquireAndReleaseBuffer();
791 }
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800792 } else {
793 // Make sure the frame available count is 0 before proceeding with a sync to ensure
794 // the correct frame is used for the sync. The only way mNumFrameAvailable would be
795 // greater than 0 is if we already ran out of buffers previously. This means we
796 // need to flush the buffers before proceeding with the sync.
797 while (mNumFrameAvailable > 0) {
798 BQA_LOGD("waiting until no queued buffers");
799 mCallbackCV.wait(_lock);
800 }
chaviwd7deef72021-10-06 11:53:40 -0500801 }
802 }
803
Tianhao Yao4861b102022-02-03 20:18:35 +0000804 // add to shadow queue
805 mNumFrameAvailable++;
chaviwc1cf4022022-06-03 13:32:33 -0500806 if (waitForTransactionCallback && mNumFrameAvailable >= 2) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000807 acquireAndReleaseBuffer();
808 }
809 ATRACE_INT(mQueuedBufferTrace.c_str(),
810 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
811
812 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
813 item.mFrameNumber, boolToString(syncTransactionSet));
814
815 if (syncTransactionSet) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800816 // Add to mSyncedFrameNumbers before waiting in case any buffers are released
817 // while waiting for a free buffer. The release and commit callback will try to
818 // acquire buffers if there are any available, but we don't want it to acquire
819 // in the case where a sync transaction wants the buffer.
820 mSyncedFrameNumbers.emplace(item.mFrameNumber);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000821 // If there's no available buffer and we're in a sync transaction, we need to wait
822 // instead of returning since we guarantee a buffer will be acquired for the sync.
823 while (acquireNextBufferLocked(mSyncTransaction) == BufferQueue::NO_BUFFER_AVAILABLE) {
824 BQA_LOGD("waiting for available buffer");
825 mCallbackCV.wait(_lock);
826 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000827
828 // Only need a commit callback when syncing to ensure the buffer that's synced has been
829 // sent to SF
Patrick Williams5312ec12024-08-23 16:11:10 -0500830 mSyncTransaction
831 ->addTransactionCommittedCallback(makeTransactionCommittedCallbackThunk(),
832 nullptr);
Tianhao Yao4861b102022-02-03 20:18:35 +0000833 if (mAcquireSingleBuffer) {
834 prevCallback = mTransactionReadyCallback;
835 prevTransaction = mSyncTransaction;
836 mTransactionReadyCallback = nullptr;
837 mSyncTransaction = nullptr;
838 }
chaviwc1cf4022022-06-03 13:32:33 -0500839 } else if (!waitForTransactionCallback) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000840 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800841 }
842 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000843 if (prevCallback) {
844 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500845 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800846}
847
Vishnu Nairaef1de92020-10-22 12:15:53 -0700848void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
849 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
850 // Do nothing since we are not storing unacquired buffer items locally.
851}
852
Vishnu Nairadf632b2021-01-07 14:05:08 -0800853void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000854 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800855 mDequeueTimestamps[bufferId] = systemTime();
Patrick Williams4b9507d2024-07-25 09:55:52 -0500856};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800857
858void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
Patrick Williams3ced5382024-08-21 15:39:32 -0500859 std::lock_guard _lock{mTimestampMutex};
860 mDequeueTimestamps.erase(bufferId);
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500861}
Vishnu Nairadf632b2021-01-07 14:05:08 -0800862
Chavi Weingartenc398c012023-04-12 17:26:02 +0000863bool BLASTBufferQueue::syncNextTransaction(
Tianhao Yao4861b102022-02-03 20:18:35 +0000864 std::function<void(SurfaceComposerClient::Transaction*)> callback,
865 bool acquireSingleBuffer) {
Chavi Weingartenc398c012023-04-12 17:26:02 +0000866 LOG_ALWAYS_FATAL_IF(!callback,
867 "BLASTBufferQueue: callback passed in to syncNextTransaction must not be "
868 "NULL");
chaviw3b4bdcf2022-03-17 09:27:03 -0500869
Chavi Weingartenc398c012023-04-12 17:26:02 +0000870 std::lock_guard _lock{mMutex};
871 BBQ_TRACE();
872 if (mTransactionReadyCallback) {
873 ALOGW("Attempting to overwrite transaction callback in syncNextTransaction");
874 return false;
Tianhao Yao4861b102022-02-03 20:18:35 +0000875 }
chaviw3b4bdcf2022-03-17 09:27:03 -0500876
Chavi Weingartenc398c012023-04-12 17:26:02 +0000877 mTransactionReadyCallback = callback;
878 mSyncTransaction = new SurfaceComposerClient::Transaction();
879 mAcquireSingleBuffer = acquireSingleBuffer;
880 return true;
Tianhao Yao4861b102022-02-03 20:18:35 +0000881}
882
883void BLASTBufferQueue::stopContinuousSyncTransaction() {
884 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
885 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
886 {
887 std::lock_guard _lock{mMutex};
Chavi Weingartenc398c012023-04-12 17:26:02 +0000888 if (mAcquireSingleBuffer || !mTransactionReadyCallback) {
889 ALOGW("Attempting to stop continuous sync when none are active");
890 return;
Tianhao Yao4861b102022-02-03 20:18:35 +0000891 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000892
893 prevCallback = mTransactionReadyCallback;
894 prevTransaction = mSyncTransaction;
895
Tianhao Yao4861b102022-02-03 20:18:35 +0000896 mTransactionReadyCallback = nullptr;
897 mSyncTransaction = nullptr;
898 mAcquireSingleBuffer = true;
899 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000900
Tianhao Yao4861b102022-02-03 20:18:35 +0000901 if (prevCallback) {
902 prevCallback(prevTransaction);
903 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700904}
905
Chavi Weingartenc398c012023-04-12 17:26:02 +0000906void BLASTBufferQueue::clearSyncTransaction() {
907 std::lock_guard _lock{mMutex};
908 if (!mAcquireSingleBuffer) {
909 ALOGW("Attempting to clear sync transaction when none are active");
910 return;
911 }
912
913 mTransactionReadyCallback = nullptr;
914 mSyncTransaction = nullptr;
915}
916
Vishnu Nairea0de002020-11-17 17:42:37 -0800917bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700918 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
919 // Only reject buffers if scaling mode is freeze.
920 return false;
921 }
922
Chavi Weingarten70670e62023-02-22 17:36:40 +0000923 ui::Size bufferSize = getBufferSize(item);
Vishnu Nairea0de002020-11-17 17:42:37 -0800924 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800925 return false;
926 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700927
Vishnu Nair670b3f72020-09-29 17:52:18 -0700928 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800929 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700930}
Vishnu Nairbf255772020-10-16 10:54:41 -0700931
Robert Carr05086b22020-10-13 18:22:51 -0700932class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700933private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700934 std::mutex mMutex;
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000935 sp<BLASTBufferQueue> mBbq GUARDED_BY(mMutex);
936 bool mDestroyed GUARDED_BY(mMutex) = false;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700937
Robert Carr05086b22020-10-13 18:22:51 -0700938public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700939 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
940 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
941 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700942
Robert Carr05086b22020-10-13 18:22:51 -0700943 void allocateBuffers() override {
944 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
945 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
946 auto gbp = getIGraphicBufferProducer();
947 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
948 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
949 gbp->allocateBuffers(reqWidth, reqHeight,
950 reqFormat, reqUsage);
951
952 }).detach();
953 }
Robert Carr9c006e02020-10-14 13:41:57 -0700954
Marin Shalamanovc5986772021-03-16 16:09:49 +0100955 status_t setFrameRate(float frameRate, int8_t compatibility,
956 int8_t changeFrameRateStrategy) override {
Ady Abraham6cdd3fd2023-09-07 18:45:58 -0700957 if (flags::bq_setframerate()) {
958 return Surface::setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
959 }
960
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000961 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700962 if (mDestroyed) {
963 return DEAD_OBJECT;
964 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100965 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
966 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700967 return BAD_VALUE;
968 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100969 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700970 }
Robert Carr9b611b72020-10-19 12:00:23 -0700971
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800972 status_t setFrameTimelineInfo(uint64_t frameNumber,
973 const FrameTimelineInfo& frameTimelineInfo) override {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000974 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700975 if (mDestroyed) {
976 return DEAD_OBJECT;
977 }
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800978 return mBbq->setFrameTimelineInfo(frameNumber, frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700979 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700980
981 void destroy() override {
982 Surface::destroy();
983
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000984 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700985 mDestroyed = true;
986 mBbq = nullptr;
987 }
Robert Carr05086b22020-10-13 18:22:51 -0700988};
989
Robert Carr9c006e02020-10-14 13:41:57 -0700990// TODO: Can we coalesce this with frame updates? Need to confirm
991// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200992status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
993 bool shouldBeSeamless) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000994 std::lock_guard _lock{mMutex};
Robert Carr9c006e02020-10-14 13:41:57 -0700995 SurfaceComposerClient::Transaction t;
996
Marin Shalamanov46084422020-10-13 12:33:42 +0200997 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700998}
999
Ady Abrahamd6e409e2023-01-19 16:07:31 -08001000status_t BLASTBufferQueue::setFrameTimelineInfo(uint64_t frameNumber,
1001 const FrameTimelineInfo& frameTimelineInfo) {
1002 ATRACE_FORMAT("%s(%s) frameNumber: %" PRIu64 " vsyncId: %" PRId64, __func__, mName.c_str(),
1003 frameNumber, frameTimelineInfo.vsyncId);
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001004 std::lock_guard _lock{mMutex};
Ady Abrahamd6e409e2023-01-19 16:07:31 -08001005 mPendingFrameTimelines.push({frameNumber, frameTimelineInfo});
Jorim Jaggia3fe67b2020-12-01 00:24:33 +01001006 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -07001007}
1008
Hongguang Chen621ec582021-02-16 15:42:35 -08001009void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001010 std::lock_guard _lock{mMutex};
Hongguang Chen621ec582021-02-16 15:42:35 -08001011 SurfaceComposerClient::Transaction t;
1012
1013 t.setSidebandStream(mSurfaceControl, stream).apply();
1014}
1015
Vishnu Nair992496b2020-10-22 17:27:21 -07001016sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001017 std::lock_guard _lock{mMutex};
Vishnu Nair992496b2020-10-22 17:27:21 -07001018 sp<IBinder> scHandle = nullptr;
1019 if (includeSurfaceControlHandle && mSurfaceControl) {
1020 scHandle = mSurfaceControl->getHandle();
1021 }
Anton Ivanov81793802025-02-13 22:57:24 -08001022 return sp<BBQSurface>::make(mProducer, true, scHandle,
1023 sp<BLASTBufferQueue>::fromExisting(this));
Robert Carr05086b22020-10-13 18:22:51 -07001024}
1025
Vishnu Nairc4a40c12020-12-23 09:14:32 -08001026void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
1027 uint64_t frameNumber) {
1028 std::lock_guard _lock{mMutex};
1029 if (mLastAcquiredFrameNumber >= frameNumber) {
1030 // Apply the transaction since we have already acquired the desired frame.
Vishnu Nair7345cbb2024-12-09 20:01:47 +00001031 t->setApplyToken(mApplyToken).apply();
Vishnu Nairc4a40c12020-12-23 09:14:32 -08001032 } else {
chaviwaad6cf52021-03-23 17:27:20 -05001033 mPendingTransactions.emplace_back(frameNumber, *t);
1034 // Clear the transaction so it can't be applied elsewhere.
1035 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -08001036 }
1037}
1038
chaviw6a195272021-09-03 16:14:25 -05001039void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
1040 std::lock_guard _lock{mMutex};
1041
1042 SurfaceComposerClient::Transaction t;
1043 mergePendingTransactions(&t, frameNumber);
Robert Carr79dc06a2022-02-22 15:28:59 -08001044 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
1045 t.setApplyToken(mApplyToken).apply(false, true);
chaviw6a195272021-09-03 16:14:25 -05001046}
1047
1048void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
1049 uint64_t frameNumber) {
1050 auto mergeTransaction =
1051 [&t, currentFrameNumber = frameNumber](
1052 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
1053 auto& [targetFrameNumber, transaction] = pendingTransaction;
1054 if (currentFrameNumber < targetFrameNumber) {
1055 return false;
1056 }
1057 t->merge(std::move(transaction));
1058 return true;
1059 };
1060
1061 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
1062 mPendingTransactions.end(), mergeTransaction),
1063 mPendingTransactions.end());
1064}
1065
chaviwd84085a2022-02-08 11:07:04 -06001066SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
1067 uint64_t frameNumber) {
1068 std::lock_guard _lock{mMutex};
1069 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
1070 mergePendingTransactions(t, frameNumber);
1071 return t;
1072}
1073
Vishnu Nair89496122020-12-14 17:14:53 -08001074// Maintains a single worker thread per process that services a list of runnables.
1075class AsyncWorker : public Singleton<AsyncWorker> {
1076private:
1077 std::thread mThread;
1078 bool mDone = false;
1079 std::deque<std::function<void()>> mRunnables;
1080 std::mutex mMutex;
1081 std::condition_variable mCv;
1082 void run() {
1083 std::unique_lock<std::mutex> lock(mMutex);
1084 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -08001085 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001086 std::deque<std::function<void()>> runnables = std::move(mRunnables);
1087 mRunnables.clear();
1088 lock.unlock();
1089 // Run outside the lock since the runnable might trigger another
1090 // post to the async worker.
1091 execute(runnables);
1092 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -08001093 }
Wonsik Kim567533e2021-05-04 19:31:29 -07001094 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -08001095 }
1096 }
1097
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001098 void execute(std::deque<std::function<void()>>& runnables) {
1099 while (!runnables.empty()) {
1100 std::function<void()> runnable = runnables.front();
1101 runnables.pop_front();
1102 runnable();
1103 }
1104 }
1105
Vishnu Nair89496122020-12-14 17:14:53 -08001106public:
1107 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
1108
1109 ~AsyncWorker() {
1110 mDone = true;
1111 mCv.notify_all();
1112 if (mThread.joinable()) {
1113 mThread.join();
1114 }
1115 }
1116
1117 void post(std::function<void()> runnable) {
1118 std::unique_lock<std::mutex> lock(mMutex);
1119 mRunnables.emplace_back(std::move(runnable));
1120 mCv.notify_one();
1121 }
1122};
1123ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
1124
1125// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
1126class AsyncProducerListener : public BnProducerListener {
1127private:
1128 const sp<IProducerListener> mListener;
1129
1130public:
1131 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
1132
1133 void onBufferReleased() override {
1134 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
1135 }
1136
1137 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
1138 AsyncWorker::getInstance().post(
1139 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
1140 }
Sungtak Lee7c935092024-09-16 16:55:04 +00001141
1142 void onBufferDetached(int slot) override {
1143 AsyncWorker::getInstance().post(
1144 [listener = mListener, slot = slot]() { listener->onBufferDetached(slot); });
1145 }
1146
1147#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_CONSUMER_ATTACH_CALLBACK)
1148 void onBufferAttached() override {
1149 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferAttached(); });
1150 }
1151#endif
Vishnu Nair89496122020-12-14 17:14:53 -08001152};
1153
Patrick Williams078d7362024-08-27 10:20:39 -05001154#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1155class BBQBufferQueueCore : public BufferQueueCore {
1156public:
1157 explicit BBQBufferQueueCore(const wp<BLASTBufferQueue>& bbq) : mBLASTBufferQueue{bbq} {}
1158
1159 void notifyBufferReleased() const override {
1160 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1161 if (!bbq) {
1162 return;
1163 }
1164 bbq->mBufferReleaseReader->interruptBlockingRead();
1165 }
1166
1167private:
1168 wp<BLASTBufferQueue> mBLASTBufferQueue;
1169};
1170#endif
1171
Vishnu Nair89496122020-12-14 17:14:53 -08001172// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
1173// can be non-blocking when the producer is in the client process.
1174class BBQBufferQueueProducer : public BufferQueueProducer {
1175public:
Patrick Williamsca81c052024-08-15 12:38:34 -05001176 BBQBufferQueueProducer(const sp<BufferQueueCore>& core, const wp<BLASTBufferQueue>& bbq)
Brian Lindahlc794b692023-01-31 15:42:47 -07001177 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/),
Patrick Williamsca81c052024-08-15 12:38:34 -05001178 mBLASTBufferQueue(bbq) {}
Vishnu Nair89496122020-12-14 17:14:53 -08001179
1180 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
1181 QueueBufferOutput* output) override {
1182 if (!listener) {
1183 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
1184 }
1185
Anton Ivanov81793802025-02-13 22:57:24 -08001186 return BufferQueueProducer::connect(sp<AsyncProducerListener>::make(listener), api,
Vishnu Nair89496122020-12-14 17:14:53 -08001187 producerControlledByApp, output);
1188 }
Vishnu Nair17dde612020-12-28 11:39:59 -08001189
Brian Lindahlc794b692023-01-31 15:42:47 -07001190 // We want to resize the frame history when changing the size of the buffer queue
1191 status_t setMaxDequeuedBufferCount(int maxDequeuedBufferCount) override {
1192 int maxBufferCount;
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001193 if (status_t status = BufferQueueProducer::setMaxDequeuedBufferCount(maxDequeuedBufferCount,
1194 &maxBufferCount);
1195 status != OK) {
1196 return status;
Brian Lindahlc794b692023-01-31 15:42:47 -07001197 }
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001198
1199 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1200 if (!bbq) {
1201 return OK;
1202 }
1203
1204 // if we can't determine the max buffer count, then just skip growing the history size
1205 size_t newFrameHistorySize = maxBufferCount + 2; // +2 because triple buffer rendering
1206 // optimize away resizing the frame history unless it will grow
1207 if (newFrameHistorySize > FrameEventHistory::INITIAL_MAX_FRAME_HISTORY) {
1208 ALOGV("increasing frame history size to %zu", newFrameHistorySize);
1209 bbq->resizeFrameEventHistory(newFrameHistorySize);
1210 }
1211
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001212 return OK;
Brian Lindahlc794b692023-01-31 15:42:47 -07001213 }
1214
Vishnu Nair17dde612020-12-28 11:39:59 -08001215 int query(int what, int* value) override {
1216 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
1217 *value = 1;
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001218 return OK;
Vishnu Nair17dde612020-12-28 11:39:59 -08001219 }
1220 return BufferQueueProducer::query(what, value);
1221 }
Brian Lindahlc794b692023-01-31 15:42:47 -07001222
Patrick Williams078d7362024-08-27 10:20:39 -05001223#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1224 status_t waitForBufferRelease(std::unique_lock<std::mutex>& bufferQueueLock,
1225 nsecs_t timeout) const override {
Melody Hsueee4c9c2025-01-16 16:11:14 +00001226 const auto startTime = std::chrono::steady_clock::now();
Patrick Williams078d7362024-08-27 10:20:39 -05001227 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1228 if (!bbq) {
1229 return OK;
1230 }
1231
1232 // BufferQueue has already checked if we have a free buffer. If there's an unread interrupt,
1233 // we want to ignore it. This must be done before unlocking the BufferQueue lock to ensure
1234 // we don't miss an interrupt.
1235 bbq->mBufferReleaseReader->clearInterrupts();
Patrick Williamsc16a4a52024-10-26 01:48:01 -05001236 UnlockGuard unlockGuard{bufferQueueLock};
Patrick Williams078d7362024-08-27 10:20:39 -05001237
1238 ATRACE_FORMAT("waiting for free buffer");
1239 ReleaseCallbackId id;
1240 sp<Fence> fence;
1241 uint32_t maxAcquiredBufferCount;
1242 status_t status =
1243 bbq->mBufferReleaseReader->readBlocking(id, fence, maxAcquiredBufferCount, timeout);
1244 if (status == TIMED_OUT) {
1245 return TIMED_OUT;
1246 } else if (status != OK) {
1247 // Waiting was interrupted or an error occurred. BufferQueueProducer will check if we
1248 // have a free buffer and call this method again if not.
1249 return OK;
1250 }
1251
1252 bbq->releaseBufferCallback(id, fence, maxAcquiredBufferCount);
Melody Hsueee4c9c2025-01-16 16:11:14 +00001253 const nsecs_t durationNanos = std::chrono::duration_cast<std::chrono::nanoseconds>(
1254 std::chrono::steady_clock::now() - startTime)
1255 .count();
1256 // Provide a callback for Choreographer to start buffer stuffing recovery when blocked
1257 // on buffer release.
1258 std::function<void(const nsecs_t)> callbackCopy = bbq->getWaitForBufferReleaseCallback();
1259 if (callbackCopy) callbackCopy(durationNanos);
1260
Patrick Williams078d7362024-08-27 10:20:39 -05001261 return OK;
1262 }
1263#endif
1264
Brian Lindahlc794b692023-01-31 15:42:47 -07001265private:
1266 const wp<BLASTBufferQueue> mBLASTBufferQueue;
Vishnu Nair89496122020-12-14 17:14:53 -08001267};
1268
1269// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
1270// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
1271// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
1272// we can deadlock.
1273void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
1274 sp<IGraphicBufferConsumer>* outConsumer) {
1275 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
1276 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
1277
Patrick Williams078d7362024-08-27 10:20:39 -05001278#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1279 auto core = sp<BBQBufferQueueCore>::make(this);
1280#else
1281 auto core = sp<BufferQueueCore>::make();
1282#endif
Vishnu Nair89496122020-12-14 17:14:53 -08001283 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
1284
Patrick Williams078d7362024-08-27 10:20:39 -05001285 auto producer = sp<BBQBufferQueueProducer>::make(core, this);
Vishnu Nair89496122020-12-14 17:14:53 -08001286 LOG_ALWAYS_FATAL_IF(producer == nullptr,
1287 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
1288
Patrick Williams078d7362024-08-27 10:20:39 -05001289 auto consumer = sp<BufferQueueConsumer>::make(core);
Vishnu Nair8b30dd12021-01-25 14:16:54 -08001290 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -08001291 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
1292 "BLASTBufferQueue: failed to create BufferQueueConsumer");
1293
1294 *outProducer = producer;
1295 *outConsumer = consumer;
1296}
1297
Brian Lindahlc794b692023-01-31 15:42:47 -07001298void BLASTBufferQueue::resizeFrameEventHistory(size_t newSize) {
1299 // This can be null during creation of the buffer queue, but resizing won't do anything at that
1300 // point in time, so just ignore. This can go away once the class relationships and lifetimes of
1301 // objects are cleaned up with a major refactor of BufferQueue as a whole.
1302 if (mBufferItemConsumer != nullptr) {
1303 std::unique_lock _lock{mMutex};
1304 mBufferItemConsumer->resizeFrameEventHistory(newSize);
1305 }
1306}
1307
chaviw497e81c2021-02-04 17:09:47 -08001308PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
1309 PixelFormat convertedFormat = format;
1310 switch (format) {
1311 case PIXEL_FORMAT_TRANSPARENT:
1312 case PIXEL_FORMAT_TRANSLUCENT:
1313 convertedFormat = PIXEL_FORMAT_RGBA_8888;
1314 break;
1315 case PIXEL_FORMAT_OPAQUE:
1316 convertedFormat = PIXEL_FORMAT_RGBX_8888;
1317 break;
1318 }
1319 return convertedFormat;
1320}
1321
Robert Carr82d07c92021-05-10 11:36:43 -07001322uint32_t BLASTBufferQueue::getLastTransformHint() const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001323 std::lock_guard _lock{mMutex};
Robert Carr82d07c92021-05-10 11:36:43 -07001324 if (mSurfaceControl != nullptr) {
1325 return mSurfaceControl->getTransformHint();
1326 } else {
1327 return 0;
1328 }
1329}
1330
chaviw0b020f82021-08-20 12:00:47 -05001331uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001332 std::lock_guard _lock{mMutex};
chaviw0b020f82021-08-20 12:00:47 -05001333 return mLastAcquiredFrameNumber;
1334}
1335
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001336bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001337 std::lock_guard _lock{mMutex};
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001338 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1339}
1340
Patrick Williamsf1e5df12022-10-17 21:37:42 +00001341void BLASTBufferQueue::setTransactionHangCallback(
1342 std::function<void(const std::string&)> callback) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001343 std::lock_guard _lock{mMutex};
Patrick Williams7c9fa272024-08-30 12:38:43 +00001344 mTransactionHangCallback = std::move(callback);
Robert Carr4c1b6462021-12-21 10:30:50 -08001345}
1346
Vishnu Nairaf15fab2024-07-30 08:59:26 -07001347void BLASTBufferQueue::setApplyToken(sp<IBinder> applyToken) {
1348 std::lock_guard _lock{mMutex};
1349 mApplyToken = std::move(applyToken);
1350}
1351
Melody Hsueee4c9c2025-01-16 16:11:14 +00001352void BLASTBufferQueue::setWaitForBufferReleaseCallback(
1353 std::function<void(const nsecs_t)> callback) {
Melody Hsue59a4df2024-12-10 00:31:59 +00001354 std::lock_guard _lock{mWaitForBufferReleaseMutex};
1355 mWaitForBufferReleaseCallback = std::move(callback);
1356}
1357
Melody Hsueee4c9c2025-01-16 16:11:14 +00001358std::function<void(const nsecs_t)> BLASTBufferQueue::getWaitForBufferReleaseCallback() const {
Melody Hsue59a4df2024-12-10 00:31:59 +00001359 std::lock_guard _lock{mWaitForBufferReleaseMutex};
1360 return mWaitForBufferReleaseCallback;
1361}
1362
Patrick Williams7c9fa272024-08-30 12:38:43 +00001363#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1364
Patrick Williamsa419faa2024-10-29 16:50:27 -05001365void BLASTBufferQueue::updateBufferReleaseProducer() {
1366 // SELinux policy may prevent this process from sending the BufferReleaseChannel's file
1367 // descriptor to SurfaceFlinger, causing the entire transaction to be dropped. We send this
1368 // transaction independently of any other updates to ensure those updates aren't lost.
1369 SurfaceComposerClient::Transaction t;
1370 status_t status = t.setApplyToken(mApplyToken)
1371 .setBufferReleaseChannel(mSurfaceControl, mBufferReleaseProducer)
1372 .apply(false /* synchronous */, true /* oneWay */);
1373 if (status != OK) {
1374 ALOGW("[%s] %s - failed to set buffer release channel on %s", mName.c_str(),
1375 statusToString(status).c_str(), mSurfaceControl->getName().c_str());
1376 }
1377}
1378
Patrick Williamsc16a4a52024-10-26 01:48:01 -05001379void BLASTBufferQueue::drainBufferReleaseConsumer() {
1380 ATRACE_CALL();
1381 while (true) {
1382 ReleaseCallbackId id;
1383 sp<Fence> fence;
1384 uint32_t maxAcquiredBufferCount;
1385 status_t status =
1386 mBufferReleaseConsumer->readReleaseFence(id, fence, maxAcquiredBufferCount);
1387 if (status != OK) {
1388 return;
1389 }
1390 releaseBufferCallback(id, fence, maxAcquiredBufferCount);
1391 }
1392}
1393
Patrick Williams078d7362024-08-27 10:20:39 -05001394BLASTBufferQueue::BufferReleaseReader::BufferReleaseReader(BLASTBufferQueue& bbq) : mBbq{bbq} {
1395 mEpollFd = android::base::unique_fd{epoll_create1(EPOLL_CLOEXEC)};
Patrick Williams7c9fa272024-08-30 12:38:43 +00001396 LOG_ALWAYS_FATAL_IF(!mEpollFd.ok(),
1397 "Failed to create buffer release epoll file descriptor. errno=%d "
1398 "message='%s'",
1399 errno, strerror(errno));
1400
1401 epoll_event registerEndpointFd{};
1402 registerEndpointFd.events = EPOLLIN;
Patrick Williams078d7362024-08-27 10:20:39 -05001403 registerEndpointFd.data.fd = mBbq.mBufferReleaseConsumer->getFd();
1404 status_t status = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mBbq.mBufferReleaseConsumer->getFd(),
1405 &registerEndpointFd);
Patrick Williams7c9fa272024-08-30 12:38:43 +00001406 LOG_ALWAYS_FATAL_IF(status == -1,
1407 "Failed to register buffer release consumer file descriptor with epoll. "
1408 "errno=%d message='%s'",
1409 errno, strerror(errno));
1410
1411 mEventFd = android::base::unique_fd(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK));
1412 LOG_ALWAYS_FATAL_IF(!mEventFd.ok(),
1413 "Failed to create buffer release event file descriptor. errno=%d "
1414 "message='%s'",
1415 errno, strerror(errno));
1416
1417 epoll_event registerEventFd{};
1418 registerEventFd.events = EPOLLIN;
1419 registerEventFd.data.fd = mEventFd.get();
1420 status = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mEventFd.get(), &registerEventFd);
1421 LOG_ALWAYS_FATAL_IF(status == -1,
1422 "Failed to register buffer release event file descriptor with epoll. "
1423 "errno=%d message='%s'",
1424 errno, strerror(errno));
1425}
1426
Patrick Williams7c9fa272024-08-30 12:38:43 +00001427status_t BLASTBufferQueue::BufferReleaseReader::readBlocking(ReleaseCallbackId& outId,
1428 sp<Fence>& outFence,
Patrick Williams078d7362024-08-27 10:20:39 -05001429 uint32_t& outMaxAcquiredBufferCount,
1430 nsecs_t timeout) {
1431 // TODO(b/363290953) epoll_wait only has millisecond timeout precision. If timeout is less than
1432 // 1ms, then we round timeout up to 1ms. Otherwise, we round timeout to the nearest
1433 // millisecond. Once epoll_pwait2 can be used in libgui, we can specify timeout with nanosecond
1434 // precision.
1435 int timeoutMs = -1;
1436 if (timeout == 0) {
1437 timeoutMs = 0;
1438 } else if (timeout > 0) {
1439 const int nsPerMs = 1000000;
1440 if (timeout < nsPerMs) {
1441 timeoutMs = 1;
1442 } else {
1443 timeoutMs = static_cast<int>(
1444 std::chrono::round<std::chrono::milliseconds>(std::chrono::nanoseconds{timeout})
1445 .count());
1446 }
1447 }
1448
Patrick Williams7c9fa272024-08-30 12:38:43 +00001449 epoll_event event{};
Patrick Williams078d7362024-08-27 10:20:39 -05001450 int eventCount;
1451 do {
1452 eventCount = epoll_wait(mEpollFd.get(), &event, 1 /*maxevents*/, timeoutMs);
1453 } while (eventCount == -1 && errno != EINTR);
1454
1455 if (eventCount == -1) {
1456 ALOGE("epoll_wait error while waiting for buffer release. errno=%d message='%s'", errno,
1457 strerror(errno));
1458 return UNKNOWN_ERROR;
1459 }
1460
1461 if (eventCount == 0) {
1462 return TIMED_OUT;
Patrick Williams7c9fa272024-08-30 12:38:43 +00001463 }
1464
1465 if (event.data.fd == mEventFd.get()) {
Patrick Williams078d7362024-08-27 10:20:39 -05001466 clearInterrupts();
Patrick Williams7c9fa272024-08-30 12:38:43 +00001467 return WOULD_BLOCK;
1468 }
1469
Patrick Williams078d7362024-08-27 10:20:39 -05001470 return mBbq.mBufferReleaseConsumer->readReleaseFence(outId, outFence,
1471 outMaxAcquiredBufferCount);
Patrick Williams7c9fa272024-08-30 12:38:43 +00001472}
1473
1474void BLASTBufferQueue::BufferReleaseReader::interruptBlockingRead() {
Patrick Williams078d7362024-08-27 10:20:39 -05001475 if (eventfd_write(mEventFd.get(), 1) == -1) {
Patrick Williams7c9fa272024-08-30 12:38:43 +00001476 ALOGE("failed to notify dequeue event. errno=%d message='%s'", errno, strerror(errno));
1477 }
1478}
1479
Patrick Williams078d7362024-08-27 10:20:39 -05001480void BLASTBufferQueue::BufferReleaseReader::clearInterrupts() {
1481 eventfd_t value;
1482 if (eventfd_read(mEventFd.get(), &value) == -1 && errno != EWOULDBLOCK) {
1483 ALOGE("error while reading from eventfd. errno=%d message='%s'", errno, strerror(errno));
1484 }
1485}
1486
Patrick Williams7c9fa272024-08-30 12:38:43 +00001487#endif
1488
Robert Carr78c25dd2019-08-15 14:10:33 -07001489} // namespace android