blob: c770db9cf3491b955f58e777b9551792e2c36373 [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
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;
Anton Ivanov7016de52025-02-05 17:39:41 -0800418 // Release stale buffers.
419 for (const auto& [key, _] : mSubmitted) {
420 if (currFrameNumber <= key.framenumber) {
421 continue; // not stale.
Robert Carr405e2f62021-12-31 16:59:34 -0800422 }
Anton Ivanov7016de52025-02-05 17:39:41 -0800423 releaseBufferCallbackLocked(key,
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700424 stat.previousReleaseFence
425 ? stat.previousReleaseFence
426 : Fence::NO_FENCE,
427 stat.currentMaxAcquiredBufferCount,
428 true /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800429 }
chaviwd7deef72021-10-06 11:53:40 -0500430 } else {
chaviw768bfa02021-11-01 09:50:57 -0500431 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500432 }
433 } else {
434 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
435 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800436 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700437 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700438}
439
Patrick Williams7c9fa272024-08-30 12:38:43 +0000440void BLASTBufferQueue::flushShadowQueue() {
441 BQA_LOGV("flushShadowQueue");
442 int numFramesToFlush = mNumFrameAvailable;
443 while (numFramesToFlush > 0) {
444 acquireNextBufferLocked(std::nullopt);
445 numFramesToFlush--;
446 }
447}
448
Vishnu Nair1506b182021-02-22 14:35:15 -0800449// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
450// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
451// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
452// Otherwise, this is a no-op.
Patrick Williams5312ec12024-08-23 16:11:10 -0500453ReleaseBufferCallback BLASTBufferQueue::makeReleaseBufferCallbackThunk() {
454 return [weakBbq = wp<BLASTBufferQueue>::fromExisting(
455 this)](const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
456 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
457 sp<BLASTBufferQueue> bbq = weakBbq.promote();
458 if (!bbq) {
459 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
460 return;
461 }
462 bbq->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
Patrick Williamsc16a4a52024-10-26 01:48:01 -0500463#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
464 bbq->drainBufferReleaseConsumer();
465#endif
Patrick Williams5312ec12024-08-23 16:11:10 -0500466 };
Vishnu Nair1506b182021-02-22 14:35:15 -0800467}
468
chaviw69058fb2021-09-27 09:37:30 -0500469void BLASTBufferQueue::releaseBufferCallback(
470 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
471 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000472 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600473 BBQ_TRACE();
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700474 releaseBufferCallbackLocked(id, releaseFence, currentMaxAcquiredBufferCount,
475 false /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800476}
477
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700478void BLASTBufferQueue::releaseBufferCallbackLocked(
479 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
480 std::optional<uint32_t> currentMaxAcquiredBufferCount, bool fakeRelease) {
Robert Carr405e2f62021-12-31 16:59:34 -0800481 ATRACE_CALL();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700482 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800483
Ady Abraham899dcdb2021-06-15 16:56:21 -0700484 // Calculate how many buffers we need to hold before we release them back
485 // to the buffer queue. This will prevent higher latency when we are running
486 // on a lower refresh rate than the max supported. We only do that for EGL
487 // clients as others don't care about latency
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000488 const auto it = mSubmitted.find(id);
489 const bool isEGL = it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
Ady Abraham899dcdb2021-06-15 16:56:21 -0700490
chaviw69058fb2021-09-27 09:37:30 -0500491 if (currentMaxAcquiredBufferCount) {
492 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
493 }
494
liulijunf90df632022-11-14 14:24:48 +0800495 const uint32_t numPendingBuffersToHold =
496 isEGL ? std::max(0, mMaxAcquiredBuffers - (int32_t)mCurrentMaxAcquiredBufferCount) : 0;
Robert Carr405e2f62021-12-31 16:59:34 -0800497
498 auto rb = ReleasedBuffer{id, releaseFence};
499 if (std::find(mPendingRelease.begin(), mPendingRelease.end(), rb) == mPendingRelease.end()) {
500 mPendingRelease.emplace_back(rb);
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700501 if (fakeRelease) {
502 BQA_LOGE("Faking releaseBufferCallback from transactionCompleteCallback %" PRIu64,
503 id.framenumber);
504 BBQ_TRACE("FakeReleaseCallback");
505 }
Robert Carr405e2f62021-12-31 16:59:34 -0800506 }
Ady Abraham899dcdb2021-06-15 16:56:21 -0700507
508 // Release all buffers that are beyond the ones that we need to hold
509 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500510 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700511 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500512 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwc1cf4022022-06-03 13:32:33 -0500513 // Don't process the transactions here if mSyncedFrameNumbers is not empty. That means
514 // are still transactions that have sync buffers in them that have not been applied or
515 // dropped. Instead, let onFrameAvailable handle processing them since it will merge with
516 // the syncTransaction.
517 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500518 acquireNextBufferLocked(std::nullopt);
519 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800520 }
521
Ady Abraham899dcdb2021-06-15 16:56:21 -0700522 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700523 ATRACE_INT(mQueuedBufferTrace.c_str(),
524 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800525 mCallbackCV.notify_all();
526}
527
chaviw0acd33a2021-11-02 11:55:37 -0500528void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
529 const sp<Fence>& releaseFence) {
530 auto it = mSubmitted.find(callbackId);
531 if (it == mSubmitted.end()) {
chaviw0acd33a2021-11-02 11:55:37 -0500532 return;
533 }
534 mNumAcquired--;
chaviw57ae4b22022-02-03 16:51:39 -0600535 BBQ_TRACE("frame=%" PRIu64, callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500536 BQA_LOGV("released %s", callbackId.to_string().c_str());
537 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
538 mSubmitted.erase(it);
chaviwc1cf4022022-06-03 13:32:33 -0500539 // Remove the frame number from mSyncedFrameNumbers since we can get a release callback
540 // without getting a transaction committed if the buffer was dropped.
541 mSyncedFrameNumbers.erase(callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500542}
543
Chavi Weingarten70670e62023-02-22 17:36:40 +0000544static ui::Size getBufferSize(const BufferItem& item) {
545 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
546 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
547
548 // Take the buffer's orientation into account
549 if (item.mTransform & ui::Transform::ROT_90) {
550 std::swap(bufWidth, bufHeight);
551 }
552 return ui::Size(bufWidth, bufHeight);
553}
554
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000555status_t BLASTBufferQueue::acquireNextBufferLocked(
chaviwd7deef72021-10-06 11:53:40 -0500556 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800557 // Check if we have frames available and we have not acquired the maximum number of buffers.
558 // Even with this check, the consumer can fail to acquire an additional buffer if the consumer
559 // has already acquired (mMaxAcquiredBuffers + 1) and the new buffer is not droppable. In this
560 // case mBufferItemConsumer->acquireBuffer will return with NO_BUFFER_AVAILABLE.
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000561 if (mNumFrameAvailable == 0) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800562 BQA_LOGV("Can't acquire next buffer. No available frames");
563 return BufferQueue::NO_BUFFER_AVAILABLE;
564 }
565
566 if (mNumAcquired >= (mMaxAcquiredBuffers + 2)) {
567 BQA_LOGV("Can't acquire next buffer. Already acquired max frames %d max:%d + 2",
568 mNumAcquired, mMaxAcquiredBuffers);
569 return BufferQueue::NO_BUFFER_AVAILABLE;
Valerie Haud3b90d22019-11-06 09:37:31 -0800570 }
571
Valerie Haua32c5522019-12-09 10:11:08 -0800572 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700573 BQA_LOGE("ERROR : surface control is null");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000574 return NAME_NOT_FOUND;
Valerie Haud3b90d22019-11-06 09:37:31 -0800575 }
576
Robert Carr78c25dd2019-08-15 14:10:33 -0700577 SurfaceComposerClient::Transaction localTransaction;
578 bool applyTransaction = true;
579 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500580 if (transaction) {
581 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700582 applyTransaction = false;
583 }
584
Patrick Williams3ced5382024-08-21 15:39:32 -0500585 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800586
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800587 status_t status =
588 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800589 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
590 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000591 return status;
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800592 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700593 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000594 return status;
Robert Carr78c25dd2019-08-15 14:10:33 -0700595 }
chaviw57ae4b22022-02-03 16:51:39 -0600596
Valerie Haua32c5522019-12-09 10:11:08 -0800597 auto buffer = bufferItem.mGraphicBuffer;
598 mNumFrameAvailable--;
chaviw57ae4b22022-02-03 16:51:39 -0600599 BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800600
601 if (buffer == nullptr) {
602 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700603 BQA_LOGE("Buffer was empty");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000604 return BAD_VALUE;
Valerie Haua32c5522019-12-09 10:11:08 -0800605 }
606
Vishnu Nair670b3f72020-09-29 17:52:18 -0700607 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700608 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800609 "buffer{size=%dx%d transform=%d}",
610 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
611 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
612 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000613 return acquireNextBufferLocked(transaction);
Vishnu Nair670b3f72020-09-29 17:52:18 -0700614 }
615
Valerie Haua32c5522019-12-09 10:11:08 -0800616 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700617 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
618 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
Anton Ivanov7016de52025-02-05 17:39:41 -0800619 mSubmitted.emplace_or_replace(releaseCallbackId, bufferItem);
Robert Carr78c25dd2019-08-15 14:10:33 -0700620
Valerie Hau871d6352020-01-29 08:44:02 -0800621 bool needsDisconnect = false;
622 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
623
624 // if producer disconnected before, notify SurfaceFlinger
625 if (needsDisconnect) {
626 t->notifyProducerDisconnect(mSurfaceControl);
627 }
628
Chavi Weingarten70670e62023-02-22 17:36:40 +0000629 // Only update mSize for destination bounds if the incoming buffer matches the requested size.
630 // Otherwise, it could cause stretching since the destination bounds will update before the
631 // buffer with the new size is acquired.
Vishnu Nair5b5f6932023-04-12 16:28:19 -0700632 if (mRequestedSize == getBufferSize(bufferItem) ||
633 bufferItem.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Chavi Weingarten70670e62023-02-22 17:36:40 +0000634 mSize = mRequestedSize;
635 }
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700636 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000637 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
638 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700639 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800640
Patrick Williams5312ec12024-08-23 16:11:10 -0500641 auto releaseBufferCallback = makeReleaseBufferCallbackThunk();
chaviwba4320c2021-09-15 15:20:53 -0500642 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900643
644 nsecs_t dequeueTime = -1;
645 {
646 std::lock_guard _lock{mTimestampMutex};
647 auto dequeueTimeIt = mDequeueTimestamps.find(buffer->getId());
648 if (dequeueTimeIt != mDequeueTimestamps.end()) {
649 dequeueTime = dequeueTimeIt->second;
650 mDequeueTimestamps.erase(dequeueTimeIt);
651 }
652 }
653
liulijuneb489f62022-10-17 22:02:14 +0800654 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, mProducerId,
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900655 releaseBufferCallback, dequeueTime);
John Reck137069e2020-12-10 22:07:37 -0500656 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
657 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
658 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Patrick Williams5312ec12024-08-23 16:11:10 -0500659 t->addTransactionCompletedCallback(makeTransactionCallbackThunk(), nullptr);
chaviwf2dace72021-11-17 17:36:50 -0600660
chaviw42026162021-04-16 15:46:12 -0500661 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700662
Vishnu Naird2aaab12022-02-10 14:49:09 -0800663 if (mUpdateDestinationFrame) {
664 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
665 } else {
666 const bool ignoreDestinationFrame =
667 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
668 t->setFlags(mSurfaceControl,
669 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
670 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700671 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700672 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800673 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800674 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800675 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800676 if (!bufferItem.mIsAutoTimestamp) {
677 t->setDesiredPresentTime(bufferItem.mTimestamp);
678 }
Brian Lindahl628cff42024-10-30 11:50:28 -0600679 if (com_android_graphics_libgui_flags_apply_picture_profiles() &&
680 bufferItem.mPictureProfileHandle.has_value()) {
681 t->setPictureProfileHandle(mSurfaceControl, *bufferItem.mPictureProfileHandle);
682 // The current picture profile must be maintained in case the BBQ gets its
683 // SurfaceControl switched out.
684 mPictureProfileHandle = bufferItem.mPictureProfileHandle;
685 // Clear out the picture profile if the requestor has asked for it to be cleared
686 if (mPictureProfileHandle == PictureProfileHandle::NONE) {
687 mPictureProfileHandle = std::nullopt;
688 }
689 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700690
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800691 // Drop stale frame timeline infos
692 while (!mPendingFrameTimelines.empty() &&
693 mPendingFrameTimelines.front().first < bufferItem.mFrameNumber) {
694 ATRACE_FORMAT_INSTANT("dropping stale frameNumber: %" PRIu64 " vsyncId: %" PRId64,
695 mPendingFrameTimelines.front().first,
696 mPendingFrameTimelines.front().second.vsyncId);
697 mPendingFrameTimelines.pop();
698 }
699
700 if (!mPendingFrameTimelines.empty() &&
701 mPendingFrameTimelines.front().first == bufferItem.mFrameNumber) {
702 ATRACE_FORMAT_INSTANT("Transaction::setFrameTimelineInfo frameNumber: %" PRIu64
703 " vsyncId: %" PRId64,
704 bufferItem.mFrameNumber,
705 mPendingFrameTimelines.front().second.vsyncId);
706 t->setFrameTimelineInfo(mPendingFrameTimelines.front().second);
707 mPendingFrameTimelines.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100708 }
709
chaviw6a195272021-09-03 16:14:25 -0500710 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700711 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800712 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
713 t->setApplyToken(mApplyToken).apply(false, true);
714 mAppliedLastTransaction = true;
715 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
716 } else {
717 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
718 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700719 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700720
chaviwd7deef72021-10-06 11:53:40 -0500721 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800722 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700723 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500724 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800725 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700726 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700727 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000728 return OK;
Robert Carr78c25dd2019-08-15 14:10:33 -0700729}
730
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800731Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
732 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800733 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800734 }
735 return item.mCrop;
736}
737
chaviwd7deef72021-10-06 11:53:40 -0500738void BLASTBufferQueue::acquireAndReleaseBuffer() {
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000739 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500740 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500741 status_t status =
742 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
743 if (status != OK) {
744 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
745 statusToString(status).c_str());
746 return;
747 }
chaviwd7deef72021-10-06 11:53:40 -0500748 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500749 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500750}
751
Vishnu Nairaef1de92020-10-22 12:15:53 -0700752void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000753 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
754 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
chaviwc1cf4022022-06-03 13:32:33 -0500755
Tianhao Yao4861b102022-02-03 20:18:35 +0000756 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000757 UNIQUE_LOCK_WITH_ASSERTION(mMutex);
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000758 BBQ_TRACE();
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000759 bool waitForTransactionCallback = !mSyncedFrameNumbers.empty();
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800760
Tianhao Yao4861b102022-02-03 20:18:35 +0000761 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
762 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800763
Tianhao Yao4861b102022-02-03 20:18:35 +0000764 if (syncTransactionSet) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000765 // If we are going to re-use the same mSyncTransaction, release the buffer that may
766 // already be set in the Transaction. This is to allow us a free slot early to continue
767 // processing a new buffer.
768 if (!mAcquireSingleBuffer) {
769 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
770 if (bufferData) {
771 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
772 bufferData->frameNumber);
773 releaseBuffer(bufferData->generateReleaseCallbackId(),
774 bufferData->acquireFence);
Tianhao Yao4861b102022-02-03 20:18:35 +0000775 }
776 }
chaviw0acd33a2021-11-02 11:55:37 -0500777
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000778 if (waitForTransactionCallback) {
779 // We are waiting on a previous sync's transaction callback so allow another sync
780 // transaction to proceed.
781 //
782 // We need to first flush out the transactions that were in between the two syncs.
783 // We do this by merging them into mSyncTransaction so any buffer merging will get
784 // a release callback invoked.
785 while (mNumFrameAvailable > 0) {
786 // flush out the shadow queue
787 acquireAndReleaseBuffer();
788 }
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800789 } else {
790 // Make sure the frame available count is 0 before proceeding with a sync to ensure
791 // the correct frame is used for the sync. The only way mNumFrameAvailable would be
792 // greater than 0 is if we already ran out of buffers previously. This means we
793 // need to flush the buffers before proceeding with the sync.
794 while (mNumFrameAvailable > 0) {
795 BQA_LOGD("waiting until no queued buffers");
796 mCallbackCV.wait(_lock);
797 }
chaviwd7deef72021-10-06 11:53:40 -0500798 }
799 }
800
Tianhao Yao4861b102022-02-03 20:18:35 +0000801 // add to shadow queue
802 mNumFrameAvailable++;
chaviwc1cf4022022-06-03 13:32:33 -0500803 if (waitForTransactionCallback && mNumFrameAvailable >= 2) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000804 acquireAndReleaseBuffer();
805 }
806 ATRACE_INT(mQueuedBufferTrace.c_str(),
807 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
808
809 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
810 item.mFrameNumber, boolToString(syncTransactionSet));
811
812 if (syncTransactionSet) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800813 // Add to mSyncedFrameNumbers before waiting in case any buffers are released
814 // while waiting for a free buffer. The release and commit callback will try to
815 // acquire buffers if there are any available, but we don't want it to acquire
816 // in the case where a sync transaction wants the buffer.
817 mSyncedFrameNumbers.emplace(item.mFrameNumber);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000818 // If there's no available buffer and we're in a sync transaction, we need to wait
819 // instead of returning since we guarantee a buffer will be acquired for the sync.
820 while (acquireNextBufferLocked(mSyncTransaction) == BufferQueue::NO_BUFFER_AVAILABLE) {
821 BQA_LOGD("waiting for available buffer");
822 mCallbackCV.wait(_lock);
823 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000824
825 // Only need a commit callback when syncing to ensure the buffer that's synced has been
826 // sent to SF
Patrick Williams5312ec12024-08-23 16:11:10 -0500827 mSyncTransaction
828 ->addTransactionCommittedCallback(makeTransactionCommittedCallbackThunk(),
829 nullptr);
Tianhao Yao4861b102022-02-03 20:18:35 +0000830 if (mAcquireSingleBuffer) {
831 prevCallback = mTransactionReadyCallback;
832 prevTransaction = mSyncTransaction;
833 mTransactionReadyCallback = nullptr;
834 mSyncTransaction = nullptr;
835 }
chaviwc1cf4022022-06-03 13:32:33 -0500836 } else if (!waitForTransactionCallback) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000837 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800838 }
839 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000840 if (prevCallback) {
841 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500842 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800843}
844
Vishnu Nairaef1de92020-10-22 12:15:53 -0700845void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
846 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
847 // Do nothing since we are not storing unacquired buffer items locally.
848}
849
Vishnu Nairadf632b2021-01-07 14:05:08 -0800850void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000851 std::lock_guard _lock{mTimestampMutex};
Anton Ivanov7016de52025-02-05 17:39:41 -0800852 mDequeueTimestamps.emplace_or_replace(bufferId, systemTime());
Patrick Williams4b9507d2024-07-25 09:55:52 -0500853};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800854
855void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
Patrick Williams3ced5382024-08-21 15:39:32 -0500856 std::lock_guard _lock{mTimestampMutex};
857 mDequeueTimestamps.erase(bufferId);
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500858}
Vishnu Nairadf632b2021-01-07 14:05:08 -0800859
Chavi Weingartenc398c012023-04-12 17:26:02 +0000860bool BLASTBufferQueue::syncNextTransaction(
Tianhao Yao4861b102022-02-03 20:18:35 +0000861 std::function<void(SurfaceComposerClient::Transaction*)> callback,
862 bool acquireSingleBuffer) {
Chavi Weingartenc398c012023-04-12 17:26:02 +0000863 LOG_ALWAYS_FATAL_IF(!callback,
864 "BLASTBufferQueue: callback passed in to syncNextTransaction must not be "
865 "NULL");
chaviw3b4bdcf2022-03-17 09:27:03 -0500866
Chavi Weingartenc398c012023-04-12 17:26:02 +0000867 std::lock_guard _lock{mMutex};
868 BBQ_TRACE();
869 if (mTransactionReadyCallback) {
870 ALOGW("Attempting to overwrite transaction callback in syncNextTransaction");
871 return false;
Tianhao Yao4861b102022-02-03 20:18:35 +0000872 }
chaviw3b4bdcf2022-03-17 09:27:03 -0500873
Chavi Weingartenc398c012023-04-12 17:26:02 +0000874 mTransactionReadyCallback = callback;
875 mSyncTransaction = new SurfaceComposerClient::Transaction();
876 mAcquireSingleBuffer = acquireSingleBuffer;
877 return true;
Tianhao Yao4861b102022-02-03 20:18:35 +0000878}
879
880void BLASTBufferQueue::stopContinuousSyncTransaction() {
881 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
882 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
883 {
884 std::lock_guard _lock{mMutex};
Chavi Weingartenc398c012023-04-12 17:26:02 +0000885 if (mAcquireSingleBuffer || !mTransactionReadyCallback) {
886 ALOGW("Attempting to stop continuous sync when none are active");
887 return;
Tianhao Yao4861b102022-02-03 20:18:35 +0000888 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000889
890 prevCallback = mTransactionReadyCallback;
891 prevTransaction = mSyncTransaction;
892
Tianhao Yao4861b102022-02-03 20:18:35 +0000893 mTransactionReadyCallback = nullptr;
894 mSyncTransaction = nullptr;
895 mAcquireSingleBuffer = true;
896 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000897
Tianhao Yao4861b102022-02-03 20:18:35 +0000898 if (prevCallback) {
899 prevCallback(prevTransaction);
900 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700901}
902
Chavi Weingartenc398c012023-04-12 17:26:02 +0000903void BLASTBufferQueue::clearSyncTransaction() {
904 std::lock_guard _lock{mMutex};
905 if (!mAcquireSingleBuffer) {
906 ALOGW("Attempting to clear sync transaction when none are active");
907 return;
908 }
909
910 mTransactionReadyCallback = nullptr;
911 mSyncTransaction = nullptr;
912}
913
Vishnu Nairea0de002020-11-17 17:42:37 -0800914bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700915 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
916 // Only reject buffers if scaling mode is freeze.
917 return false;
918 }
919
Chavi Weingarten70670e62023-02-22 17:36:40 +0000920 ui::Size bufferSize = getBufferSize(item);
Vishnu Nairea0de002020-11-17 17:42:37 -0800921 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800922 return false;
923 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700924
Vishnu Nair670b3f72020-09-29 17:52:18 -0700925 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800926 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700927}
Vishnu Nairbf255772020-10-16 10:54:41 -0700928
Robert Carr05086b22020-10-13 18:22:51 -0700929class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700930private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700931 std::mutex mMutex;
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000932 sp<BLASTBufferQueue> mBbq GUARDED_BY(mMutex);
933 bool mDestroyed GUARDED_BY(mMutex) = false;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700934
Robert Carr05086b22020-10-13 18:22:51 -0700935public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700936 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
937 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
938 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700939
Robert Carr05086b22020-10-13 18:22:51 -0700940 void allocateBuffers() override {
941 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
942 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
943 auto gbp = getIGraphicBufferProducer();
944 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
945 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
946 gbp->allocateBuffers(reqWidth, reqHeight,
947 reqFormat, reqUsage);
948
949 }).detach();
950 }
Robert Carr9c006e02020-10-14 13:41:57 -0700951
Marin Shalamanovc5986772021-03-16 16:09:49 +0100952 status_t setFrameRate(float frameRate, int8_t compatibility,
953 int8_t changeFrameRateStrategy) override {
Ady Abraham6cdd3fd2023-09-07 18:45:58 -0700954 if (flags::bq_setframerate()) {
955 return Surface::setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
956 }
957
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000958 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700959 if (mDestroyed) {
960 return DEAD_OBJECT;
961 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100962 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
963 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700964 return BAD_VALUE;
965 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100966 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700967 }
Robert Carr9b611b72020-10-19 12:00:23 -0700968
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800969 status_t setFrameTimelineInfo(uint64_t frameNumber,
970 const FrameTimelineInfo& frameTimelineInfo) override {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000971 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700972 if (mDestroyed) {
973 return DEAD_OBJECT;
974 }
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800975 return mBbq->setFrameTimelineInfo(frameNumber, frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700976 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700977
978 void destroy() override {
979 Surface::destroy();
980
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000981 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700982 mDestroyed = true;
983 mBbq = nullptr;
984 }
Robert Carr05086b22020-10-13 18:22:51 -0700985};
986
Robert Carr9c006e02020-10-14 13:41:57 -0700987// TODO: Can we coalesce this with frame updates? Need to confirm
988// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200989status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
990 bool shouldBeSeamless) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000991 std::lock_guard _lock{mMutex};
Robert Carr9c006e02020-10-14 13:41:57 -0700992 SurfaceComposerClient::Transaction t;
993
Marin Shalamanov46084422020-10-13 12:33:42 +0200994 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700995}
996
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800997status_t BLASTBufferQueue::setFrameTimelineInfo(uint64_t frameNumber,
998 const FrameTimelineInfo& frameTimelineInfo) {
999 ATRACE_FORMAT("%s(%s) frameNumber: %" PRIu64 " vsyncId: %" PRId64, __func__, mName.c_str(),
1000 frameNumber, frameTimelineInfo.vsyncId);
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001001 std::lock_guard _lock{mMutex};
Ady Abrahamd6e409e2023-01-19 16:07:31 -08001002 mPendingFrameTimelines.push({frameNumber, frameTimelineInfo});
Jorim Jaggia3fe67b2020-12-01 00:24:33 +01001003 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -07001004}
1005
Hongguang Chen621ec582021-02-16 15:42:35 -08001006void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001007 std::lock_guard _lock{mMutex};
Hongguang Chen621ec582021-02-16 15:42:35 -08001008 SurfaceComposerClient::Transaction t;
1009
1010 t.setSidebandStream(mSurfaceControl, stream).apply();
1011}
1012
Vishnu Nair992496b2020-10-22 17:27:21 -07001013sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001014 std::lock_guard _lock{mMutex};
Vishnu Nair992496b2020-10-22 17:27:21 -07001015 sp<IBinder> scHandle = nullptr;
1016 if (includeSurfaceControlHandle && mSurfaceControl) {
1017 scHandle = mSurfaceControl->getHandle();
1018 }
1019 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -07001020}
1021
Vishnu Nairc4a40c12020-12-23 09:14:32 -08001022void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
1023 uint64_t frameNumber) {
1024 std::lock_guard _lock{mMutex};
1025 if (mLastAcquiredFrameNumber >= frameNumber) {
1026 // Apply the transaction since we have already acquired the desired frame.
Vishnu Nair7345cbb2024-12-09 20:01:47 +00001027 t->setApplyToken(mApplyToken).apply();
Vishnu Nairc4a40c12020-12-23 09:14:32 -08001028 } else {
chaviwaad6cf52021-03-23 17:27:20 -05001029 mPendingTransactions.emplace_back(frameNumber, *t);
1030 // Clear the transaction so it can't be applied elsewhere.
1031 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -08001032 }
1033}
1034
chaviw6a195272021-09-03 16:14:25 -05001035void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
1036 std::lock_guard _lock{mMutex};
1037
1038 SurfaceComposerClient::Transaction t;
1039 mergePendingTransactions(&t, frameNumber);
Robert Carr79dc06a2022-02-22 15:28:59 -08001040 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
1041 t.setApplyToken(mApplyToken).apply(false, true);
chaviw6a195272021-09-03 16:14:25 -05001042}
1043
1044void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
1045 uint64_t frameNumber) {
1046 auto mergeTransaction =
1047 [&t, currentFrameNumber = frameNumber](
1048 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
1049 auto& [targetFrameNumber, transaction] = pendingTransaction;
1050 if (currentFrameNumber < targetFrameNumber) {
1051 return false;
1052 }
1053 t->merge(std::move(transaction));
1054 return true;
1055 };
1056
1057 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
1058 mPendingTransactions.end(), mergeTransaction),
1059 mPendingTransactions.end());
1060}
1061
chaviwd84085a2022-02-08 11:07:04 -06001062SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
1063 uint64_t frameNumber) {
1064 std::lock_guard _lock{mMutex};
1065 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
1066 mergePendingTransactions(t, frameNumber);
1067 return t;
1068}
1069
Vishnu Nair89496122020-12-14 17:14:53 -08001070// Maintains a single worker thread per process that services a list of runnables.
1071class AsyncWorker : public Singleton<AsyncWorker> {
1072private:
1073 std::thread mThread;
1074 bool mDone = false;
1075 std::deque<std::function<void()>> mRunnables;
1076 std::mutex mMutex;
1077 std::condition_variable mCv;
1078 void run() {
1079 std::unique_lock<std::mutex> lock(mMutex);
1080 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -08001081 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001082 std::deque<std::function<void()>> runnables = std::move(mRunnables);
1083 mRunnables.clear();
1084 lock.unlock();
1085 // Run outside the lock since the runnable might trigger another
1086 // post to the async worker.
1087 execute(runnables);
1088 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -08001089 }
Wonsik Kim567533e2021-05-04 19:31:29 -07001090 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -08001091 }
1092 }
1093
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001094 void execute(std::deque<std::function<void()>>& runnables) {
1095 while (!runnables.empty()) {
1096 std::function<void()> runnable = runnables.front();
1097 runnables.pop_front();
1098 runnable();
1099 }
1100 }
1101
Vishnu Nair89496122020-12-14 17:14:53 -08001102public:
1103 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
1104
1105 ~AsyncWorker() {
1106 mDone = true;
1107 mCv.notify_all();
1108 if (mThread.joinable()) {
1109 mThread.join();
1110 }
1111 }
1112
1113 void post(std::function<void()> runnable) {
1114 std::unique_lock<std::mutex> lock(mMutex);
1115 mRunnables.emplace_back(std::move(runnable));
1116 mCv.notify_one();
1117 }
1118};
1119ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
1120
1121// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
1122class AsyncProducerListener : public BnProducerListener {
1123private:
1124 const sp<IProducerListener> mListener;
1125
1126public:
1127 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
1128
1129 void onBufferReleased() override {
1130 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
1131 }
1132
1133 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
1134 AsyncWorker::getInstance().post(
1135 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
1136 }
Sungtak Lee7c935092024-09-16 16:55:04 +00001137
1138 void onBufferDetached(int slot) override {
1139 AsyncWorker::getInstance().post(
1140 [listener = mListener, slot = slot]() { listener->onBufferDetached(slot); });
1141 }
1142
1143#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_CONSUMER_ATTACH_CALLBACK)
1144 void onBufferAttached() override {
1145 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferAttached(); });
1146 }
1147#endif
Vishnu Nair89496122020-12-14 17:14:53 -08001148};
1149
Patrick Williams078d7362024-08-27 10:20:39 -05001150#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1151class BBQBufferQueueCore : public BufferQueueCore {
1152public:
1153 explicit BBQBufferQueueCore(const wp<BLASTBufferQueue>& bbq) : mBLASTBufferQueue{bbq} {}
1154
1155 void notifyBufferReleased() const override {
1156 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1157 if (!bbq) {
1158 return;
1159 }
1160 bbq->mBufferReleaseReader->interruptBlockingRead();
1161 }
1162
1163private:
1164 wp<BLASTBufferQueue> mBLASTBufferQueue;
1165};
1166#endif
1167
Vishnu Nair89496122020-12-14 17:14:53 -08001168// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
1169// can be non-blocking when the producer is in the client process.
1170class BBQBufferQueueProducer : public BufferQueueProducer {
1171public:
Patrick Williamsca81c052024-08-15 12:38:34 -05001172 BBQBufferQueueProducer(const sp<BufferQueueCore>& core, const wp<BLASTBufferQueue>& bbq)
Brian Lindahlc794b692023-01-31 15:42:47 -07001173 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/),
Patrick Williamsca81c052024-08-15 12:38:34 -05001174 mBLASTBufferQueue(bbq) {}
Vishnu Nair89496122020-12-14 17:14:53 -08001175
1176 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
1177 QueueBufferOutput* output) override {
1178 if (!listener) {
1179 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
1180 }
1181
1182 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
1183 producerControlledByApp, output);
1184 }
Vishnu Nair17dde612020-12-28 11:39:59 -08001185
Brian Lindahlc794b692023-01-31 15:42:47 -07001186 // We want to resize the frame history when changing the size of the buffer queue
1187 status_t setMaxDequeuedBufferCount(int maxDequeuedBufferCount) override {
1188 int maxBufferCount;
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001189 if (status_t status = BufferQueueProducer::setMaxDequeuedBufferCount(maxDequeuedBufferCount,
1190 &maxBufferCount);
1191 status != OK) {
1192 return status;
Brian Lindahlc794b692023-01-31 15:42:47 -07001193 }
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001194
1195 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1196 if (!bbq) {
1197 return OK;
1198 }
1199
1200 // if we can't determine the max buffer count, then just skip growing the history size
1201 size_t newFrameHistorySize = maxBufferCount + 2; // +2 because triple buffer rendering
1202 // optimize away resizing the frame history unless it will grow
1203 if (newFrameHistorySize > FrameEventHistory::INITIAL_MAX_FRAME_HISTORY) {
1204 ALOGV("increasing frame history size to %zu", newFrameHistorySize);
1205 bbq->resizeFrameEventHistory(newFrameHistorySize);
1206 }
1207
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001208 return OK;
Brian Lindahlc794b692023-01-31 15:42:47 -07001209 }
1210
Vishnu Nair17dde612020-12-28 11:39:59 -08001211 int query(int what, int* value) override {
1212 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
1213 *value = 1;
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001214 return OK;
Vishnu Nair17dde612020-12-28 11:39:59 -08001215 }
1216 return BufferQueueProducer::query(what, value);
1217 }
Brian Lindahlc794b692023-01-31 15:42:47 -07001218
Patrick Williams078d7362024-08-27 10:20:39 -05001219#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1220 status_t waitForBufferRelease(std::unique_lock<std::mutex>& bufferQueueLock,
1221 nsecs_t timeout) const override {
Melody Hsueee4c9c2025-01-16 16:11:14 +00001222 const auto startTime = std::chrono::steady_clock::now();
Patrick Williams078d7362024-08-27 10:20:39 -05001223 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1224 if (!bbq) {
1225 return OK;
1226 }
1227
1228 // BufferQueue has already checked if we have a free buffer. If there's an unread interrupt,
1229 // we want to ignore it. This must be done before unlocking the BufferQueue lock to ensure
1230 // we don't miss an interrupt.
1231 bbq->mBufferReleaseReader->clearInterrupts();
Patrick Williamsc16a4a52024-10-26 01:48:01 -05001232 UnlockGuard unlockGuard{bufferQueueLock};
Patrick Williams078d7362024-08-27 10:20:39 -05001233
1234 ATRACE_FORMAT("waiting for free buffer");
1235 ReleaseCallbackId id;
1236 sp<Fence> fence;
1237 uint32_t maxAcquiredBufferCount;
1238 status_t status =
1239 bbq->mBufferReleaseReader->readBlocking(id, fence, maxAcquiredBufferCount, timeout);
1240 if (status == TIMED_OUT) {
1241 return TIMED_OUT;
1242 } else if (status != OK) {
1243 // Waiting was interrupted or an error occurred. BufferQueueProducer will check if we
1244 // have a free buffer and call this method again if not.
1245 return OK;
1246 }
1247
1248 bbq->releaseBufferCallback(id, fence, maxAcquiredBufferCount);
Melody Hsueee4c9c2025-01-16 16:11:14 +00001249 const nsecs_t durationNanos = std::chrono::duration_cast<std::chrono::nanoseconds>(
1250 std::chrono::steady_clock::now() - startTime)
1251 .count();
1252 // Provide a callback for Choreographer to start buffer stuffing recovery when blocked
1253 // on buffer release.
1254 std::function<void(const nsecs_t)> callbackCopy = bbq->getWaitForBufferReleaseCallback();
1255 if (callbackCopy) callbackCopy(durationNanos);
1256
Patrick Williams078d7362024-08-27 10:20:39 -05001257 return OK;
1258 }
1259#endif
1260
Brian Lindahlc794b692023-01-31 15:42:47 -07001261private:
1262 const wp<BLASTBufferQueue> mBLASTBufferQueue;
Vishnu Nair89496122020-12-14 17:14:53 -08001263};
1264
1265// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
1266// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
1267// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
1268// we can deadlock.
1269void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
1270 sp<IGraphicBufferConsumer>* outConsumer) {
1271 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
1272 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
1273
Patrick Williams078d7362024-08-27 10:20:39 -05001274#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1275 auto core = sp<BBQBufferQueueCore>::make(this);
1276#else
1277 auto core = sp<BufferQueueCore>::make();
1278#endif
Vishnu Nair89496122020-12-14 17:14:53 -08001279 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
1280
Patrick Williams078d7362024-08-27 10:20:39 -05001281 auto producer = sp<BBQBufferQueueProducer>::make(core, this);
Vishnu Nair89496122020-12-14 17:14:53 -08001282 LOG_ALWAYS_FATAL_IF(producer == nullptr,
1283 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
1284
Patrick Williams078d7362024-08-27 10:20:39 -05001285 auto consumer = sp<BufferQueueConsumer>::make(core);
Vishnu Nair8b30dd12021-01-25 14:16:54 -08001286 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -08001287 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
1288 "BLASTBufferQueue: failed to create BufferQueueConsumer");
1289
1290 *outProducer = producer;
1291 *outConsumer = consumer;
1292}
1293
Brian Lindahlc794b692023-01-31 15:42:47 -07001294void BLASTBufferQueue::resizeFrameEventHistory(size_t newSize) {
1295 // This can be null during creation of the buffer queue, but resizing won't do anything at that
1296 // point in time, so just ignore. This can go away once the class relationships and lifetimes of
1297 // objects are cleaned up with a major refactor of BufferQueue as a whole.
1298 if (mBufferItemConsumer != nullptr) {
1299 std::unique_lock _lock{mMutex};
1300 mBufferItemConsumer->resizeFrameEventHistory(newSize);
1301 }
1302}
1303
chaviw497e81c2021-02-04 17:09:47 -08001304PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
1305 PixelFormat convertedFormat = format;
1306 switch (format) {
1307 case PIXEL_FORMAT_TRANSPARENT:
1308 case PIXEL_FORMAT_TRANSLUCENT:
1309 convertedFormat = PIXEL_FORMAT_RGBA_8888;
1310 break;
1311 case PIXEL_FORMAT_OPAQUE:
1312 convertedFormat = PIXEL_FORMAT_RGBX_8888;
1313 break;
1314 }
1315 return convertedFormat;
1316}
1317
Robert Carr82d07c92021-05-10 11:36:43 -07001318uint32_t BLASTBufferQueue::getLastTransformHint() const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001319 std::lock_guard _lock{mMutex};
Robert Carr82d07c92021-05-10 11:36:43 -07001320 if (mSurfaceControl != nullptr) {
1321 return mSurfaceControl->getTransformHint();
1322 } else {
1323 return 0;
1324 }
1325}
1326
chaviw0b020f82021-08-20 12:00:47 -05001327uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001328 std::lock_guard _lock{mMutex};
chaviw0b020f82021-08-20 12:00:47 -05001329 return mLastAcquiredFrameNumber;
1330}
1331
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001332bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001333 std::lock_guard _lock{mMutex};
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001334 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1335}
1336
Patrick Williamsf1e5df12022-10-17 21:37:42 +00001337void BLASTBufferQueue::setTransactionHangCallback(
1338 std::function<void(const std::string&)> callback) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001339 std::lock_guard _lock{mMutex};
Patrick Williams7c9fa272024-08-30 12:38:43 +00001340 mTransactionHangCallback = std::move(callback);
Robert Carr4c1b6462021-12-21 10:30:50 -08001341}
1342
Vishnu Nairaf15fab2024-07-30 08:59:26 -07001343void BLASTBufferQueue::setApplyToken(sp<IBinder> applyToken) {
1344 std::lock_guard _lock{mMutex};
1345 mApplyToken = std::move(applyToken);
1346}
1347
Melody Hsueee4c9c2025-01-16 16:11:14 +00001348void BLASTBufferQueue::setWaitForBufferReleaseCallback(
1349 std::function<void(const nsecs_t)> callback) {
Melody Hsue59a4df2024-12-10 00:31:59 +00001350 std::lock_guard _lock{mWaitForBufferReleaseMutex};
1351 mWaitForBufferReleaseCallback = std::move(callback);
1352}
1353
Melody Hsueee4c9c2025-01-16 16:11:14 +00001354std::function<void(const nsecs_t)> BLASTBufferQueue::getWaitForBufferReleaseCallback() const {
Melody Hsue59a4df2024-12-10 00:31:59 +00001355 std::lock_guard _lock{mWaitForBufferReleaseMutex};
1356 return mWaitForBufferReleaseCallback;
1357}
1358
Patrick Williams7c9fa272024-08-30 12:38:43 +00001359#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1360
Patrick Williamsa419faa2024-10-29 16:50:27 -05001361void BLASTBufferQueue::updateBufferReleaseProducer() {
1362 // SELinux policy may prevent this process from sending the BufferReleaseChannel's file
1363 // descriptor to SurfaceFlinger, causing the entire transaction to be dropped. We send this
1364 // transaction independently of any other updates to ensure those updates aren't lost.
1365 SurfaceComposerClient::Transaction t;
1366 status_t status = t.setApplyToken(mApplyToken)
1367 .setBufferReleaseChannel(mSurfaceControl, mBufferReleaseProducer)
1368 .apply(false /* synchronous */, true /* oneWay */);
1369 if (status != OK) {
1370 ALOGW("[%s] %s - failed to set buffer release channel on %s", mName.c_str(),
1371 statusToString(status).c_str(), mSurfaceControl->getName().c_str());
1372 }
1373}
1374
Patrick Williamsc16a4a52024-10-26 01:48:01 -05001375void BLASTBufferQueue::drainBufferReleaseConsumer() {
1376 ATRACE_CALL();
1377 while (true) {
1378 ReleaseCallbackId id;
1379 sp<Fence> fence;
1380 uint32_t maxAcquiredBufferCount;
1381 status_t status =
1382 mBufferReleaseConsumer->readReleaseFence(id, fence, maxAcquiredBufferCount);
1383 if (status != OK) {
1384 return;
1385 }
1386 releaseBufferCallback(id, fence, maxAcquiredBufferCount);
1387 }
1388}
1389
Patrick Williams078d7362024-08-27 10:20:39 -05001390BLASTBufferQueue::BufferReleaseReader::BufferReleaseReader(BLASTBufferQueue& bbq) : mBbq{bbq} {
1391 mEpollFd = android::base::unique_fd{epoll_create1(EPOLL_CLOEXEC)};
Patrick Williams7c9fa272024-08-30 12:38:43 +00001392 LOG_ALWAYS_FATAL_IF(!mEpollFd.ok(),
1393 "Failed to create buffer release epoll file descriptor. errno=%d "
1394 "message='%s'",
1395 errno, strerror(errno));
1396
1397 epoll_event registerEndpointFd{};
1398 registerEndpointFd.events = EPOLLIN;
Patrick Williams078d7362024-08-27 10:20:39 -05001399 registerEndpointFd.data.fd = mBbq.mBufferReleaseConsumer->getFd();
1400 status_t status = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mBbq.mBufferReleaseConsumer->getFd(),
1401 &registerEndpointFd);
Patrick Williams7c9fa272024-08-30 12:38:43 +00001402 LOG_ALWAYS_FATAL_IF(status == -1,
1403 "Failed to register buffer release consumer file descriptor with epoll. "
1404 "errno=%d message='%s'",
1405 errno, strerror(errno));
1406
1407 mEventFd = android::base::unique_fd(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK));
1408 LOG_ALWAYS_FATAL_IF(!mEventFd.ok(),
1409 "Failed to create buffer release event file descriptor. errno=%d "
1410 "message='%s'",
1411 errno, strerror(errno));
1412
1413 epoll_event registerEventFd{};
1414 registerEventFd.events = EPOLLIN;
1415 registerEventFd.data.fd = mEventFd.get();
1416 status = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mEventFd.get(), &registerEventFd);
1417 LOG_ALWAYS_FATAL_IF(status == -1,
1418 "Failed to register buffer release event file descriptor with epoll. "
1419 "errno=%d message='%s'",
1420 errno, strerror(errno));
1421}
1422
Patrick Williams7c9fa272024-08-30 12:38:43 +00001423status_t BLASTBufferQueue::BufferReleaseReader::readBlocking(ReleaseCallbackId& outId,
1424 sp<Fence>& outFence,
Patrick Williams078d7362024-08-27 10:20:39 -05001425 uint32_t& outMaxAcquiredBufferCount,
1426 nsecs_t timeout) {
1427 // TODO(b/363290953) epoll_wait only has millisecond timeout precision. If timeout is less than
1428 // 1ms, then we round timeout up to 1ms. Otherwise, we round timeout to the nearest
1429 // millisecond. Once epoll_pwait2 can be used in libgui, we can specify timeout with nanosecond
1430 // precision.
1431 int timeoutMs = -1;
1432 if (timeout == 0) {
1433 timeoutMs = 0;
1434 } else if (timeout > 0) {
1435 const int nsPerMs = 1000000;
1436 if (timeout < nsPerMs) {
1437 timeoutMs = 1;
1438 } else {
1439 timeoutMs = static_cast<int>(
1440 std::chrono::round<std::chrono::milliseconds>(std::chrono::nanoseconds{timeout})
1441 .count());
1442 }
1443 }
1444
Patrick Williams7c9fa272024-08-30 12:38:43 +00001445 epoll_event event{};
Patrick Williams078d7362024-08-27 10:20:39 -05001446 int eventCount;
1447 do {
1448 eventCount = epoll_wait(mEpollFd.get(), &event, 1 /*maxevents*/, timeoutMs);
1449 } while (eventCount == -1 && errno != EINTR);
1450
1451 if (eventCount == -1) {
1452 ALOGE("epoll_wait error while waiting for buffer release. errno=%d message='%s'", errno,
1453 strerror(errno));
1454 return UNKNOWN_ERROR;
1455 }
1456
1457 if (eventCount == 0) {
1458 return TIMED_OUT;
Patrick Williams7c9fa272024-08-30 12:38:43 +00001459 }
1460
1461 if (event.data.fd == mEventFd.get()) {
Patrick Williams078d7362024-08-27 10:20:39 -05001462 clearInterrupts();
Patrick Williams7c9fa272024-08-30 12:38:43 +00001463 return WOULD_BLOCK;
1464 }
1465
Patrick Williams078d7362024-08-27 10:20:39 -05001466 return mBbq.mBufferReleaseConsumer->readReleaseFence(outId, outFence,
1467 outMaxAcquiredBufferCount);
Patrick Williams7c9fa272024-08-30 12:38:43 +00001468}
1469
1470void BLASTBufferQueue::BufferReleaseReader::interruptBlockingRead() {
Patrick Williams078d7362024-08-27 10:20:39 -05001471 if (eventfd_write(mEventFd.get(), 1) == -1) {
Patrick Williams7c9fa272024-08-30 12:38:43 +00001472 ALOGE("failed to notify dequeue event. errno=%d message='%s'", errno, strerror(errno));
1473 }
1474}
1475
Patrick Williams078d7362024-08-27 10:20:39 -05001476void BLASTBufferQueue::BufferReleaseReader::clearInterrupts() {
1477 eventfd_t value;
1478 if (eventfd_read(mEventFd.get(), &value) == -1 && errno != EWOULDBLOCK) {
1479 ALOGE("error while reading from eventfd. errno=%d message='%s'", errno, strerror(errno));
1480 }
1481}
1482
Patrick Williams7c9fa272024-08-30 12:38:43 +00001483#endif
1484
Robert Carr78c25dd2019-08-15 14:10:33 -07001485} // namespace android