blob: 0848fac2936ad760ad4fef7272574fbb5993f843 [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)
Priyanka Advani (xWF)f73db7a2025-02-19 17:35:16 -0800200 mBufferItemConsumer = new BLASTBufferItemConsumer(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
Priyanka Advani (xWF)f73db7a2025-02-19 17:35:16 -0800205 mBufferItemConsumer = new BLASTBufferItemConsumer(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();
Priyanka Advani (xWF)f73db7a2025-02-19 17:35:16 -0800644 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900645
646 nsecs_t dequeueTime = -1;
647 {
648 std::lock_guard _lock{mTimestampMutex};
649 auto dequeueTimeIt = mDequeueTimestamps.find(buffer->getId());
650 if (dequeueTimeIt != mDequeueTimestamps.end()) {
651 dequeueTime = dequeueTimeIt->second;
652 mDequeueTimestamps.erase(dequeueTimeIt);
653 }
654 }
655
liulijuneb489f62022-10-17 22:02:14 +0800656 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, mProducerId,
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900657 releaseBufferCallback, dequeueTime);
John Reck137069e2020-12-10 22:07:37 -0500658 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
659 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
660 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Patrick Williams5312ec12024-08-23 16:11:10 -0500661 t->addTransactionCompletedCallback(makeTransactionCallbackThunk(), nullptr);
chaviwf2dace72021-11-17 17:36:50 -0600662
chaviw42026162021-04-16 15:46:12 -0500663 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700664
Vishnu Naird2aaab12022-02-10 14:49:09 -0800665 if (mUpdateDestinationFrame) {
666 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
667 } else {
668 const bool ignoreDestinationFrame =
669 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
670 t->setFlags(mSurfaceControl,
671 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
672 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700673 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700674 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800675 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800676 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800677 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800678 if (!bufferItem.mIsAutoTimestamp) {
679 t->setDesiredPresentTime(bufferItem.mTimestamp);
680 }
Brian Lindahl628cff42024-10-30 11:50:28 -0600681 if (com_android_graphics_libgui_flags_apply_picture_profiles() &&
682 bufferItem.mPictureProfileHandle.has_value()) {
683 t->setPictureProfileHandle(mSurfaceControl, *bufferItem.mPictureProfileHandle);
684 // The current picture profile must be maintained in case the BBQ gets its
685 // SurfaceControl switched out.
686 mPictureProfileHandle = bufferItem.mPictureProfileHandle;
687 // Clear out the picture profile if the requestor has asked for it to be cleared
688 if (mPictureProfileHandle == PictureProfileHandle::NONE) {
689 mPictureProfileHandle = std::nullopt;
690 }
691 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700692
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800693 // Drop stale frame timeline infos
694 while (!mPendingFrameTimelines.empty() &&
695 mPendingFrameTimelines.front().first < bufferItem.mFrameNumber) {
696 ATRACE_FORMAT_INSTANT("dropping stale frameNumber: %" PRIu64 " vsyncId: %" PRId64,
697 mPendingFrameTimelines.front().first,
698 mPendingFrameTimelines.front().second.vsyncId);
699 mPendingFrameTimelines.pop();
700 }
701
702 if (!mPendingFrameTimelines.empty() &&
703 mPendingFrameTimelines.front().first == bufferItem.mFrameNumber) {
704 ATRACE_FORMAT_INSTANT("Transaction::setFrameTimelineInfo frameNumber: %" PRIu64
705 " vsyncId: %" PRId64,
706 bufferItem.mFrameNumber,
707 mPendingFrameTimelines.front().second.vsyncId);
708 t->setFrameTimelineInfo(mPendingFrameTimelines.front().second);
709 mPendingFrameTimelines.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100710 }
711
chaviw6a195272021-09-03 16:14:25 -0500712 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700713 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800714 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
715 t->setApplyToken(mApplyToken).apply(false, true);
716 mAppliedLastTransaction = true;
717 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
718 } else {
719 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
720 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700721 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700722
chaviwd7deef72021-10-06 11:53:40 -0500723 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800724 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700725 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500726 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800727 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700728 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700729 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000730 return OK;
Robert Carr78c25dd2019-08-15 14:10:33 -0700731}
732
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800733Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
734 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800735 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800736 }
737 return item.mCrop;
738}
739
chaviwd7deef72021-10-06 11:53:40 -0500740void BLASTBufferQueue::acquireAndReleaseBuffer() {
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000741 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500742 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500743 status_t status =
744 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
745 if (status != OK) {
746 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
747 statusToString(status).c_str());
748 return;
749 }
chaviwd7deef72021-10-06 11:53:40 -0500750 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500751 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500752}
753
Vishnu Nairaef1de92020-10-22 12:15:53 -0700754void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000755 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
756 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
chaviwc1cf4022022-06-03 13:32:33 -0500757
Tianhao Yao4861b102022-02-03 20:18:35 +0000758 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000759 UNIQUE_LOCK_WITH_ASSERTION(mMutex);
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000760 BBQ_TRACE();
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000761 bool waitForTransactionCallback = !mSyncedFrameNumbers.empty();
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800762
Tianhao Yao4861b102022-02-03 20:18:35 +0000763 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
764 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800765
Tianhao Yao4861b102022-02-03 20:18:35 +0000766 if (syncTransactionSet) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000767 // If we are going to re-use the same mSyncTransaction, release the buffer that may
768 // already be set in the Transaction. This is to allow us a free slot early to continue
769 // processing a new buffer.
770 if (!mAcquireSingleBuffer) {
771 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
772 if (bufferData) {
773 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
774 bufferData->frameNumber);
775 releaseBuffer(bufferData->generateReleaseCallbackId(),
776 bufferData->acquireFence);
Tianhao Yao4861b102022-02-03 20:18:35 +0000777 }
778 }
chaviw0acd33a2021-11-02 11:55:37 -0500779
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000780 if (waitForTransactionCallback) {
781 // We are waiting on a previous sync's transaction callback so allow another sync
782 // transaction to proceed.
783 //
784 // We need to first flush out the transactions that were in between the two syncs.
785 // We do this by merging them into mSyncTransaction so any buffer merging will get
786 // a release callback invoked.
787 while (mNumFrameAvailable > 0) {
788 // flush out the shadow queue
789 acquireAndReleaseBuffer();
790 }
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800791 } else {
792 // Make sure the frame available count is 0 before proceeding with a sync to ensure
793 // the correct frame is used for the sync. The only way mNumFrameAvailable would be
794 // greater than 0 is if we already ran out of buffers previously. This means we
795 // need to flush the buffers before proceeding with the sync.
796 while (mNumFrameAvailable > 0) {
797 BQA_LOGD("waiting until no queued buffers");
798 mCallbackCV.wait(_lock);
799 }
chaviwd7deef72021-10-06 11:53:40 -0500800 }
801 }
802
Tianhao Yao4861b102022-02-03 20:18:35 +0000803 // add to shadow queue
804 mNumFrameAvailable++;
chaviwc1cf4022022-06-03 13:32:33 -0500805 if (waitForTransactionCallback && mNumFrameAvailable >= 2) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000806 acquireAndReleaseBuffer();
807 }
808 ATRACE_INT(mQueuedBufferTrace.c_str(),
809 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
810
811 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
812 item.mFrameNumber, boolToString(syncTransactionSet));
813
814 if (syncTransactionSet) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800815 // Add to mSyncedFrameNumbers before waiting in case any buffers are released
816 // while waiting for a free buffer. The release and commit callback will try to
817 // acquire buffers if there are any available, but we don't want it to acquire
818 // in the case where a sync transaction wants the buffer.
819 mSyncedFrameNumbers.emplace(item.mFrameNumber);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000820 // If there's no available buffer and we're in a sync transaction, we need to wait
821 // instead of returning since we guarantee a buffer will be acquired for the sync.
822 while (acquireNextBufferLocked(mSyncTransaction) == BufferQueue::NO_BUFFER_AVAILABLE) {
823 BQA_LOGD("waiting for available buffer");
824 mCallbackCV.wait(_lock);
825 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000826
827 // Only need a commit callback when syncing to ensure the buffer that's synced has been
828 // sent to SF
Patrick Williams5312ec12024-08-23 16:11:10 -0500829 mSyncTransaction
830 ->addTransactionCommittedCallback(makeTransactionCommittedCallbackThunk(),
831 nullptr);
Tianhao Yao4861b102022-02-03 20:18:35 +0000832 if (mAcquireSingleBuffer) {
833 prevCallback = mTransactionReadyCallback;
834 prevTransaction = mSyncTransaction;
835 mTransactionReadyCallback = nullptr;
836 mSyncTransaction = nullptr;
837 }
chaviwc1cf4022022-06-03 13:32:33 -0500838 } else if (!waitForTransactionCallback) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000839 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800840 }
841 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000842 if (prevCallback) {
843 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500844 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800845}
846
Vishnu Nairaef1de92020-10-22 12:15:53 -0700847void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
848 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
849 // Do nothing since we are not storing unacquired buffer items locally.
850}
851
Vishnu Nairadf632b2021-01-07 14:05:08 -0800852void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000853 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800854 mDequeueTimestamps[bufferId] = systemTime();
Patrick Williams4b9507d2024-07-25 09:55:52 -0500855};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800856
857void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
Patrick Williams3ced5382024-08-21 15:39:32 -0500858 std::lock_guard _lock{mTimestampMutex};
859 mDequeueTimestamps.erase(bufferId);
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500860}
Vishnu Nairadf632b2021-01-07 14:05:08 -0800861
Chavi Weingartenc398c012023-04-12 17:26:02 +0000862bool BLASTBufferQueue::syncNextTransaction(
Tianhao Yao4861b102022-02-03 20:18:35 +0000863 std::function<void(SurfaceComposerClient::Transaction*)> callback,
864 bool acquireSingleBuffer) {
Chavi Weingartenc398c012023-04-12 17:26:02 +0000865 LOG_ALWAYS_FATAL_IF(!callback,
866 "BLASTBufferQueue: callback passed in to syncNextTransaction must not be "
867 "NULL");
chaviw3b4bdcf2022-03-17 09:27:03 -0500868
Chavi Weingartenc398c012023-04-12 17:26:02 +0000869 std::lock_guard _lock{mMutex};
870 BBQ_TRACE();
871 if (mTransactionReadyCallback) {
872 ALOGW("Attempting to overwrite transaction callback in syncNextTransaction");
873 return false;
Tianhao Yao4861b102022-02-03 20:18:35 +0000874 }
chaviw3b4bdcf2022-03-17 09:27:03 -0500875
Chavi Weingartenc398c012023-04-12 17:26:02 +0000876 mTransactionReadyCallback = callback;
877 mSyncTransaction = new SurfaceComposerClient::Transaction();
878 mAcquireSingleBuffer = acquireSingleBuffer;
879 return true;
Tianhao Yao4861b102022-02-03 20:18:35 +0000880}
881
882void BLASTBufferQueue::stopContinuousSyncTransaction() {
883 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
884 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
885 {
886 std::lock_guard _lock{mMutex};
Chavi Weingartenc398c012023-04-12 17:26:02 +0000887 if (mAcquireSingleBuffer || !mTransactionReadyCallback) {
888 ALOGW("Attempting to stop continuous sync when none are active");
889 return;
Tianhao Yao4861b102022-02-03 20:18:35 +0000890 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000891
892 prevCallback = mTransactionReadyCallback;
893 prevTransaction = mSyncTransaction;
894
Tianhao Yao4861b102022-02-03 20:18:35 +0000895 mTransactionReadyCallback = nullptr;
896 mSyncTransaction = nullptr;
897 mAcquireSingleBuffer = true;
898 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000899
Tianhao Yao4861b102022-02-03 20:18:35 +0000900 if (prevCallback) {
901 prevCallback(prevTransaction);
902 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700903}
904
Chavi Weingartenc398c012023-04-12 17:26:02 +0000905void BLASTBufferQueue::clearSyncTransaction() {
906 std::lock_guard _lock{mMutex};
907 if (!mAcquireSingleBuffer) {
908 ALOGW("Attempting to clear sync transaction when none are active");
909 return;
910 }
911
912 mTransactionReadyCallback = nullptr;
913 mSyncTransaction = nullptr;
914}
915
Vishnu Nairea0de002020-11-17 17:42:37 -0800916bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700917 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
918 // Only reject buffers if scaling mode is freeze.
919 return false;
920 }
921
Chavi Weingarten70670e62023-02-22 17:36:40 +0000922 ui::Size bufferSize = getBufferSize(item);
Vishnu Nairea0de002020-11-17 17:42:37 -0800923 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800924 return false;
925 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700926
Vishnu Nair670b3f72020-09-29 17:52:18 -0700927 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800928 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700929}
Vishnu Nairbf255772020-10-16 10:54:41 -0700930
Robert Carr05086b22020-10-13 18:22:51 -0700931class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700932private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700933 std::mutex mMutex;
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000934 sp<BLASTBufferQueue> mBbq GUARDED_BY(mMutex);
935 bool mDestroyed GUARDED_BY(mMutex) = false;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700936
Robert Carr05086b22020-10-13 18:22:51 -0700937public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700938 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
939 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
940 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700941
Robert Carr05086b22020-10-13 18:22:51 -0700942 void allocateBuffers() override {
943 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
944 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
945 auto gbp = getIGraphicBufferProducer();
946 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
947 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
948 gbp->allocateBuffers(reqWidth, reqHeight,
949 reqFormat, reqUsage);
950
951 }).detach();
952 }
Robert Carr9c006e02020-10-14 13:41:57 -0700953
Marin Shalamanovc5986772021-03-16 16:09:49 +0100954 status_t setFrameRate(float frameRate, int8_t compatibility,
955 int8_t changeFrameRateStrategy) override {
Ady Abraham6cdd3fd2023-09-07 18:45:58 -0700956 if (flags::bq_setframerate()) {
957 return Surface::setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
958 }
959
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000960 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700961 if (mDestroyed) {
962 return DEAD_OBJECT;
963 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100964 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
965 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700966 return BAD_VALUE;
967 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100968 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700969 }
Robert Carr9b611b72020-10-19 12:00:23 -0700970
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800971 status_t setFrameTimelineInfo(uint64_t frameNumber,
972 const FrameTimelineInfo& frameTimelineInfo) override {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000973 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700974 if (mDestroyed) {
975 return DEAD_OBJECT;
976 }
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800977 return mBbq->setFrameTimelineInfo(frameNumber, frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700978 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700979
980 void destroy() override {
981 Surface::destroy();
982
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000983 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700984 mDestroyed = true;
985 mBbq = nullptr;
986 }
Robert Carr05086b22020-10-13 18:22:51 -0700987};
988
Robert Carr9c006e02020-10-14 13:41:57 -0700989// TODO: Can we coalesce this with frame updates? Need to confirm
990// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200991status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
992 bool shouldBeSeamless) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000993 std::lock_guard _lock{mMutex};
Robert Carr9c006e02020-10-14 13:41:57 -0700994 SurfaceComposerClient::Transaction t;
995
Marin Shalamanov46084422020-10-13 12:33:42 +0200996 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700997}
998
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800999status_t BLASTBufferQueue::setFrameTimelineInfo(uint64_t frameNumber,
1000 const FrameTimelineInfo& frameTimelineInfo) {
1001 ATRACE_FORMAT("%s(%s) frameNumber: %" PRIu64 " vsyncId: %" PRId64, __func__, mName.c_str(),
1002 frameNumber, frameTimelineInfo.vsyncId);
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001003 std::lock_guard _lock{mMutex};
Ady Abrahamd6e409e2023-01-19 16:07:31 -08001004 mPendingFrameTimelines.push({frameNumber, frameTimelineInfo});
Jorim Jaggia3fe67b2020-12-01 00:24:33 +01001005 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -07001006}
1007
Hongguang Chen621ec582021-02-16 15:42:35 -08001008void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001009 std::lock_guard _lock{mMutex};
Hongguang Chen621ec582021-02-16 15:42:35 -08001010 SurfaceComposerClient::Transaction t;
1011
1012 t.setSidebandStream(mSurfaceControl, stream).apply();
1013}
1014
Vishnu Nair992496b2020-10-22 17:27:21 -07001015sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001016 std::lock_guard _lock{mMutex};
Vishnu Nair992496b2020-10-22 17:27:21 -07001017 sp<IBinder> scHandle = nullptr;
1018 if (includeSurfaceControlHandle && mSurfaceControl) {
1019 scHandle = mSurfaceControl->getHandle();
1020 }
Priyanka Advani (xWF)f73db7a2025-02-19 17:35:16 -08001021 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -07001022}
1023
Vishnu Nairc4a40c12020-12-23 09:14:32 -08001024void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
1025 uint64_t frameNumber) {
1026 std::lock_guard _lock{mMutex};
1027 if (mLastAcquiredFrameNumber >= frameNumber) {
1028 // Apply the transaction since we have already acquired the desired frame.
Vishnu Nair7345cbb2024-12-09 20:01:47 +00001029 t->setApplyToken(mApplyToken).apply();
Vishnu Nairc4a40c12020-12-23 09:14:32 -08001030 } else {
chaviwaad6cf52021-03-23 17:27:20 -05001031 mPendingTransactions.emplace_back(frameNumber, *t);
1032 // Clear the transaction so it can't be applied elsewhere.
1033 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -08001034 }
1035}
1036
chaviw6a195272021-09-03 16:14:25 -05001037void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
1038 std::lock_guard _lock{mMutex};
1039
1040 SurfaceComposerClient::Transaction t;
1041 mergePendingTransactions(&t, frameNumber);
Robert Carr79dc06a2022-02-22 15:28:59 -08001042 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
1043 t.setApplyToken(mApplyToken).apply(false, true);
chaviw6a195272021-09-03 16:14:25 -05001044}
1045
1046void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
1047 uint64_t frameNumber) {
1048 auto mergeTransaction =
1049 [&t, currentFrameNumber = frameNumber](
1050 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
1051 auto& [targetFrameNumber, transaction] = pendingTransaction;
1052 if (currentFrameNumber < targetFrameNumber) {
1053 return false;
1054 }
1055 t->merge(std::move(transaction));
1056 return true;
1057 };
1058
1059 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
1060 mPendingTransactions.end(), mergeTransaction),
1061 mPendingTransactions.end());
1062}
1063
chaviwd84085a2022-02-08 11:07:04 -06001064SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
1065 uint64_t frameNumber) {
1066 std::lock_guard _lock{mMutex};
1067 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
1068 mergePendingTransactions(t, frameNumber);
1069 return t;
1070}
1071
Vishnu Nair89496122020-12-14 17:14:53 -08001072// Maintains a single worker thread per process that services a list of runnables.
1073class AsyncWorker : public Singleton<AsyncWorker> {
1074private:
1075 std::thread mThread;
1076 bool mDone = false;
1077 std::deque<std::function<void()>> mRunnables;
1078 std::mutex mMutex;
1079 std::condition_variable mCv;
1080 void run() {
1081 std::unique_lock<std::mutex> lock(mMutex);
1082 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -08001083 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001084 std::deque<std::function<void()>> runnables = std::move(mRunnables);
1085 mRunnables.clear();
1086 lock.unlock();
1087 // Run outside the lock since the runnable might trigger another
1088 // post to the async worker.
1089 execute(runnables);
1090 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -08001091 }
Wonsik Kim567533e2021-05-04 19:31:29 -07001092 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -08001093 }
1094 }
1095
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001096 void execute(std::deque<std::function<void()>>& runnables) {
1097 while (!runnables.empty()) {
1098 std::function<void()> runnable = runnables.front();
1099 runnables.pop_front();
1100 runnable();
1101 }
1102 }
1103
Vishnu Nair89496122020-12-14 17:14:53 -08001104public:
1105 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
1106
1107 ~AsyncWorker() {
1108 mDone = true;
1109 mCv.notify_all();
1110 if (mThread.joinable()) {
1111 mThread.join();
1112 }
1113 }
1114
1115 void post(std::function<void()> runnable) {
1116 std::unique_lock<std::mutex> lock(mMutex);
1117 mRunnables.emplace_back(std::move(runnable));
1118 mCv.notify_one();
1119 }
1120};
1121ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
1122
1123// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
1124class AsyncProducerListener : public BnProducerListener {
1125private:
1126 const sp<IProducerListener> mListener;
1127
1128public:
1129 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
1130
1131 void onBufferReleased() override {
1132 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
1133 }
1134
1135 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
1136 AsyncWorker::getInstance().post(
1137 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
1138 }
Sungtak Lee7c935092024-09-16 16:55:04 +00001139
1140 void onBufferDetached(int slot) override {
1141 AsyncWorker::getInstance().post(
1142 [listener = mListener, slot = slot]() { listener->onBufferDetached(slot); });
1143 }
1144
1145#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_CONSUMER_ATTACH_CALLBACK)
1146 void onBufferAttached() override {
1147 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferAttached(); });
1148 }
1149#endif
Vishnu Nair89496122020-12-14 17:14:53 -08001150};
1151
Patrick Williams078d7362024-08-27 10:20:39 -05001152#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1153class BBQBufferQueueCore : public BufferQueueCore {
1154public:
1155 explicit BBQBufferQueueCore(const wp<BLASTBufferQueue>& bbq) : mBLASTBufferQueue{bbq} {}
1156
1157 void notifyBufferReleased() const override {
1158 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1159 if (!bbq) {
1160 return;
1161 }
1162 bbq->mBufferReleaseReader->interruptBlockingRead();
1163 }
1164
1165private:
1166 wp<BLASTBufferQueue> mBLASTBufferQueue;
1167};
1168#endif
1169
Vishnu Nair89496122020-12-14 17:14:53 -08001170// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
1171// can be non-blocking when the producer is in the client process.
1172class BBQBufferQueueProducer : public BufferQueueProducer {
1173public:
Patrick Williamsca81c052024-08-15 12:38:34 -05001174 BBQBufferQueueProducer(const sp<BufferQueueCore>& core, const wp<BLASTBufferQueue>& bbq)
Brian Lindahlc794b692023-01-31 15:42:47 -07001175 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/),
Patrick Williamsca81c052024-08-15 12:38:34 -05001176 mBLASTBufferQueue(bbq) {}
Vishnu Nair89496122020-12-14 17:14:53 -08001177
1178 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
1179 QueueBufferOutput* output) override {
1180 if (!listener) {
1181 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
1182 }
1183
Priyanka Advani (xWF)f73db7a2025-02-19 17:35:16 -08001184 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
Vishnu Nair89496122020-12-14 17:14:53 -08001185 producerControlledByApp, output);
1186 }
Vishnu Nair17dde612020-12-28 11:39:59 -08001187
Brian Lindahlc794b692023-01-31 15:42:47 -07001188 // We want to resize the frame history when changing the size of the buffer queue
1189 status_t setMaxDequeuedBufferCount(int maxDequeuedBufferCount) override {
1190 int maxBufferCount;
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001191 if (status_t status = BufferQueueProducer::setMaxDequeuedBufferCount(maxDequeuedBufferCount,
1192 &maxBufferCount);
1193 status != OK) {
1194 return status;
Brian Lindahlc794b692023-01-31 15:42:47 -07001195 }
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001196
1197 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1198 if (!bbq) {
1199 return OK;
1200 }
1201
1202 // if we can't determine the max buffer count, then just skip growing the history size
1203 size_t newFrameHistorySize = maxBufferCount + 2; // +2 because triple buffer rendering
1204 // optimize away resizing the frame history unless it will grow
1205 if (newFrameHistorySize > FrameEventHistory::INITIAL_MAX_FRAME_HISTORY) {
1206 ALOGV("increasing frame history size to %zu", newFrameHistorySize);
1207 bbq->resizeFrameEventHistory(newFrameHistorySize);
1208 }
1209
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001210 return OK;
Brian Lindahlc794b692023-01-31 15:42:47 -07001211 }
1212
Vishnu Nair17dde612020-12-28 11:39:59 -08001213 int query(int what, int* value) override {
1214 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
1215 *value = 1;
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001216 return OK;
Vishnu Nair17dde612020-12-28 11:39:59 -08001217 }
1218 return BufferQueueProducer::query(what, value);
1219 }
Brian Lindahlc794b692023-01-31 15:42:47 -07001220
Patrick Williams078d7362024-08-27 10:20:39 -05001221#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1222 status_t waitForBufferRelease(std::unique_lock<std::mutex>& bufferQueueLock,
1223 nsecs_t timeout) const override {
Melody Hsueee4c9c2025-01-16 16:11:14 +00001224 const auto startTime = std::chrono::steady_clock::now();
Patrick Williams078d7362024-08-27 10:20:39 -05001225 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1226 if (!bbq) {
1227 return OK;
1228 }
1229
1230 // BufferQueue has already checked if we have a free buffer. If there's an unread interrupt,
1231 // we want to ignore it. This must be done before unlocking the BufferQueue lock to ensure
1232 // we don't miss an interrupt.
1233 bbq->mBufferReleaseReader->clearInterrupts();
Patrick Williamsc16a4a52024-10-26 01:48:01 -05001234 UnlockGuard unlockGuard{bufferQueueLock};
Patrick Williams078d7362024-08-27 10:20:39 -05001235
1236 ATRACE_FORMAT("waiting for free buffer");
1237 ReleaseCallbackId id;
1238 sp<Fence> fence;
1239 uint32_t maxAcquiredBufferCount;
1240 status_t status =
1241 bbq->mBufferReleaseReader->readBlocking(id, fence, maxAcquiredBufferCount, timeout);
1242 if (status == TIMED_OUT) {
1243 return TIMED_OUT;
1244 } else if (status != OK) {
1245 // Waiting was interrupted or an error occurred. BufferQueueProducer will check if we
1246 // have a free buffer and call this method again if not.
1247 return OK;
1248 }
1249
1250 bbq->releaseBufferCallback(id, fence, maxAcquiredBufferCount);
Melody Hsueee4c9c2025-01-16 16:11:14 +00001251 const nsecs_t durationNanos = std::chrono::duration_cast<std::chrono::nanoseconds>(
1252 std::chrono::steady_clock::now() - startTime)
1253 .count();
1254 // Provide a callback for Choreographer to start buffer stuffing recovery when blocked
1255 // on buffer release.
1256 std::function<void(const nsecs_t)> callbackCopy = bbq->getWaitForBufferReleaseCallback();
1257 if (callbackCopy) callbackCopy(durationNanos);
1258
Patrick Williams078d7362024-08-27 10:20:39 -05001259 return OK;
1260 }
1261#endif
1262
Brian Lindahlc794b692023-01-31 15:42:47 -07001263private:
1264 const wp<BLASTBufferQueue> mBLASTBufferQueue;
Vishnu Nair89496122020-12-14 17:14:53 -08001265};
1266
1267// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
1268// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
1269// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
1270// we can deadlock.
1271void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
1272 sp<IGraphicBufferConsumer>* outConsumer) {
1273 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
1274 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
1275
Patrick Williams078d7362024-08-27 10:20:39 -05001276#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1277 auto core = sp<BBQBufferQueueCore>::make(this);
1278#else
1279 auto core = sp<BufferQueueCore>::make();
1280#endif
Vishnu Nair89496122020-12-14 17:14:53 -08001281 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
1282
Patrick Williams078d7362024-08-27 10:20:39 -05001283 auto producer = sp<BBQBufferQueueProducer>::make(core, this);
Vishnu Nair89496122020-12-14 17:14:53 -08001284 LOG_ALWAYS_FATAL_IF(producer == nullptr,
1285 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
1286
Patrick Williams078d7362024-08-27 10:20:39 -05001287 auto consumer = sp<BufferQueueConsumer>::make(core);
Vishnu Nair8b30dd12021-01-25 14:16:54 -08001288 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -08001289 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
1290 "BLASTBufferQueue: failed to create BufferQueueConsumer");
1291
1292 *outProducer = producer;
1293 *outConsumer = consumer;
1294}
1295
Brian Lindahlc794b692023-01-31 15:42:47 -07001296void BLASTBufferQueue::resizeFrameEventHistory(size_t newSize) {
1297 // This can be null during creation of the buffer queue, but resizing won't do anything at that
1298 // point in time, so just ignore. This can go away once the class relationships and lifetimes of
1299 // objects are cleaned up with a major refactor of BufferQueue as a whole.
1300 if (mBufferItemConsumer != nullptr) {
1301 std::unique_lock _lock{mMutex};
1302 mBufferItemConsumer->resizeFrameEventHistory(newSize);
1303 }
1304}
1305
chaviw497e81c2021-02-04 17:09:47 -08001306PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
1307 PixelFormat convertedFormat = format;
1308 switch (format) {
1309 case PIXEL_FORMAT_TRANSPARENT:
1310 case PIXEL_FORMAT_TRANSLUCENT:
1311 convertedFormat = PIXEL_FORMAT_RGBA_8888;
1312 break;
1313 case PIXEL_FORMAT_OPAQUE:
1314 convertedFormat = PIXEL_FORMAT_RGBX_8888;
1315 break;
1316 }
1317 return convertedFormat;
1318}
1319
Robert Carr82d07c92021-05-10 11:36:43 -07001320uint32_t BLASTBufferQueue::getLastTransformHint() const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001321 std::lock_guard _lock{mMutex};
Robert Carr82d07c92021-05-10 11:36:43 -07001322 if (mSurfaceControl != nullptr) {
1323 return mSurfaceControl->getTransformHint();
1324 } else {
1325 return 0;
1326 }
1327}
1328
chaviw0b020f82021-08-20 12:00:47 -05001329uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001330 std::lock_guard _lock{mMutex};
chaviw0b020f82021-08-20 12:00:47 -05001331 return mLastAcquiredFrameNumber;
1332}
1333
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001334bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001335 std::lock_guard _lock{mMutex};
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001336 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1337}
1338
Patrick Williamsf1e5df12022-10-17 21:37:42 +00001339void BLASTBufferQueue::setTransactionHangCallback(
1340 std::function<void(const std::string&)> callback) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001341 std::lock_guard _lock{mMutex};
Patrick Williams7c9fa272024-08-30 12:38:43 +00001342 mTransactionHangCallback = std::move(callback);
Robert Carr4c1b6462021-12-21 10:30:50 -08001343}
1344
Vishnu Nairaf15fab2024-07-30 08:59:26 -07001345void BLASTBufferQueue::setApplyToken(sp<IBinder> applyToken) {
1346 std::lock_guard _lock{mMutex};
1347 mApplyToken = std::move(applyToken);
1348}
1349
Melody Hsueee4c9c2025-01-16 16:11:14 +00001350void BLASTBufferQueue::setWaitForBufferReleaseCallback(
1351 std::function<void(const nsecs_t)> callback) {
Melody Hsue59a4df2024-12-10 00:31:59 +00001352 std::lock_guard _lock{mWaitForBufferReleaseMutex};
1353 mWaitForBufferReleaseCallback = std::move(callback);
1354}
1355
Melody Hsueee4c9c2025-01-16 16:11:14 +00001356std::function<void(const nsecs_t)> BLASTBufferQueue::getWaitForBufferReleaseCallback() const {
Melody Hsue59a4df2024-12-10 00:31:59 +00001357 std::lock_guard _lock{mWaitForBufferReleaseMutex};
1358 return mWaitForBufferReleaseCallback;
1359}
1360
Patrick Williams7c9fa272024-08-30 12:38:43 +00001361#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1362
Patrick Williamsa419faa2024-10-29 16:50:27 -05001363void BLASTBufferQueue::updateBufferReleaseProducer() {
1364 // SELinux policy may prevent this process from sending the BufferReleaseChannel's file
1365 // descriptor to SurfaceFlinger, causing the entire transaction to be dropped. We send this
1366 // transaction independently of any other updates to ensure those updates aren't lost.
1367 SurfaceComposerClient::Transaction t;
1368 status_t status = t.setApplyToken(mApplyToken)
1369 .setBufferReleaseChannel(mSurfaceControl, mBufferReleaseProducer)
1370 .apply(false /* synchronous */, true /* oneWay */);
1371 if (status != OK) {
1372 ALOGW("[%s] %s - failed to set buffer release channel on %s", mName.c_str(),
1373 statusToString(status).c_str(), mSurfaceControl->getName().c_str());
1374 }
1375}
1376
Patrick Williamsc16a4a52024-10-26 01:48:01 -05001377void BLASTBufferQueue::drainBufferReleaseConsumer() {
1378 ATRACE_CALL();
1379 while (true) {
1380 ReleaseCallbackId id;
1381 sp<Fence> fence;
1382 uint32_t maxAcquiredBufferCount;
1383 status_t status =
1384 mBufferReleaseConsumer->readReleaseFence(id, fence, maxAcquiredBufferCount);
1385 if (status != OK) {
1386 return;
1387 }
1388 releaseBufferCallback(id, fence, maxAcquiredBufferCount);
1389 }
1390}
1391
Patrick Williams078d7362024-08-27 10:20:39 -05001392BLASTBufferQueue::BufferReleaseReader::BufferReleaseReader(BLASTBufferQueue& bbq) : mBbq{bbq} {
1393 mEpollFd = android::base::unique_fd{epoll_create1(EPOLL_CLOEXEC)};
Patrick Williams7c9fa272024-08-30 12:38:43 +00001394 LOG_ALWAYS_FATAL_IF(!mEpollFd.ok(),
1395 "Failed to create buffer release epoll file descriptor. errno=%d "
1396 "message='%s'",
1397 errno, strerror(errno));
1398
1399 epoll_event registerEndpointFd{};
1400 registerEndpointFd.events = EPOLLIN;
Patrick Williams078d7362024-08-27 10:20:39 -05001401 registerEndpointFd.data.fd = mBbq.mBufferReleaseConsumer->getFd();
1402 status_t status = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mBbq.mBufferReleaseConsumer->getFd(),
1403 &registerEndpointFd);
Patrick Williams7c9fa272024-08-30 12:38:43 +00001404 LOG_ALWAYS_FATAL_IF(status == -1,
1405 "Failed to register buffer release consumer file descriptor with epoll. "
1406 "errno=%d message='%s'",
1407 errno, strerror(errno));
1408
1409 mEventFd = android::base::unique_fd(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK));
1410 LOG_ALWAYS_FATAL_IF(!mEventFd.ok(),
1411 "Failed to create buffer release event file descriptor. errno=%d "
1412 "message='%s'",
1413 errno, strerror(errno));
1414
1415 epoll_event registerEventFd{};
1416 registerEventFd.events = EPOLLIN;
1417 registerEventFd.data.fd = mEventFd.get();
1418 status = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mEventFd.get(), &registerEventFd);
1419 LOG_ALWAYS_FATAL_IF(status == -1,
1420 "Failed to register buffer release event file descriptor with epoll. "
1421 "errno=%d message='%s'",
1422 errno, strerror(errno));
1423}
1424
Patrick Williams7c9fa272024-08-30 12:38:43 +00001425status_t BLASTBufferQueue::BufferReleaseReader::readBlocking(ReleaseCallbackId& outId,
1426 sp<Fence>& outFence,
Patrick Williams078d7362024-08-27 10:20:39 -05001427 uint32_t& outMaxAcquiredBufferCount,
1428 nsecs_t timeout) {
1429 // TODO(b/363290953) epoll_wait only has millisecond timeout precision. If timeout is less than
1430 // 1ms, then we round timeout up to 1ms. Otherwise, we round timeout to the nearest
1431 // millisecond. Once epoll_pwait2 can be used in libgui, we can specify timeout with nanosecond
1432 // precision.
1433 int timeoutMs = -1;
1434 if (timeout == 0) {
1435 timeoutMs = 0;
1436 } else if (timeout > 0) {
1437 const int nsPerMs = 1000000;
1438 if (timeout < nsPerMs) {
1439 timeoutMs = 1;
1440 } else {
1441 timeoutMs = static_cast<int>(
1442 std::chrono::round<std::chrono::milliseconds>(std::chrono::nanoseconds{timeout})
1443 .count());
1444 }
1445 }
1446
Patrick Williams7c9fa272024-08-30 12:38:43 +00001447 epoll_event event{};
Patrick Williams078d7362024-08-27 10:20:39 -05001448 int eventCount;
1449 do {
1450 eventCount = epoll_wait(mEpollFd.get(), &event, 1 /*maxevents*/, timeoutMs);
1451 } while (eventCount == -1 && errno != EINTR);
1452
1453 if (eventCount == -1) {
1454 ALOGE("epoll_wait error while waiting for buffer release. errno=%d message='%s'", errno,
1455 strerror(errno));
1456 return UNKNOWN_ERROR;
1457 }
1458
1459 if (eventCount == 0) {
1460 return TIMED_OUT;
Patrick Williams7c9fa272024-08-30 12:38:43 +00001461 }
1462
1463 if (event.data.fd == mEventFd.get()) {
Patrick Williams078d7362024-08-27 10:20:39 -05001464 clearInterrupts();
Patrick Williams7c9fa272024-08-30 12:38:43 +00001465 return WOULD_BLOCK;
1466 }
1467
Patrick Williams078d7362024-08-27 10:20:39 -05001468 return mBbq.mBufferReleaseConsumer->readReleaseFence(outId, outFence,
1469 outMaxAcquiredBufferCount);
Patrick Williams7c9fa272024-08-30 12:38:43 +00001470}
1471
1472void BLASTBufferQueue::BufferReleaseReader::interruptBlockingRead() {
Patrick Williams078d7362024-08-27 10:20:39 -05001473 if (eventfd_write(mEventFd.get(), 1) == -1) {
Patrick Williams7c9fa272024-08-30 12:38:43 +00001474 ALOGE("failed to notify dequeue event. errno=%d message='%s'", errno, strerror(errno));
1475 }
1476}
1477
Patrick Williams078d7362024-08-27 10:20:39 -05001478void BLASTBufferQueue::BufferReleaseReader::clearInterrupts() {
1479 eventfd_t value;
1480 if (eventfd_read(mEventFd.get(), &value) == -1 && errno != EWOULDBLOCK) {
1481 ALOGE("error while reading from eventfd. errno=%d message='%s'", errno, strerror(errno));
1482 }
1483}
1484
Patrick Williams7c9fa272024-08-30 12:38:43 +00001485#endif
1486
Robert Carr78c25dd2019-08-15 14:10:33 -07001487} // namespace android