blob: 5b0f21de917d38ca2429ec132080e4ecd15a6542 [file] [log] [blame]
Robert Carr78c25dd2019-08-15 14:10:33 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Valerie Haud3b90d22019-11-06 09:37:31 -080017#undef LOG_TAG
18#define LOG_TAG "BLASTBufferQueue"
19
Valerie Haua32c5522019-12-09 10:11:08 -080020#define ATRACE_TAG ATRACE_TAG_GRAPHICS
Vishnu Naire1a42322020-10-02 17:42:04 -070021//#define LOG_NDEBUG 0
Valerie Haua32c5522019-12-09 10:11:08 -080022
Jim Shargod30823a2024-07-27 02:49:39 +000023#include <com_android_graphics_libgui_flags.h>
liulijuneb489f62022-10-17 22:02:14 +080024#include <cutils/atomic.h>
Patrick Williams7c9fa272024-08-30 12:38:43 +000025#include <ftl/fake_guard.h>
Robert Carr78c25dd2019-08-15 14:10:33 -070026#include <gui/BLASTBufferQueue.h>
27#include <gui/BufferItemConsumer.h>
Vishnu Nair89496122020-12-14 17:14:53 -080028#include <gui/BufferQueueConsumer.h>
29#include <gui/BufferQueueCore.h>
30#include <gui/BufferQueueProducer.h>
Patrick Williams7c9fa272024-08-30 12:38:43 +000031#include <sys/epoll.h>
32#include <sys/eventfd.h>
Ady Abraham107788e2023-10-17 12:31:08 -070033
Ady Abraham6cdd3fd2023-09-07 18:45:58 -070034#include <gui/FrameRateUtils.h>
Valerie Hau45e4b3b2019-12-03 10:49:17 -080035#include <gui/GLConsumer.h>
Vishnu Nair89496122020-12-14 17:14:53 -080036#include <gui/IProducerListener.h>
Robert Carr05086b22020-10-13 18:22:51 -070037#include <gui/Surface.h>
chaviw57ae4b22022-02-03 16:51:39 -060038#include <gui/TraceUtils.h>
Vishnu Nair89496122020-12-14 17:14:53 -080039#include <utils/Singleton.h>
Valerie Haua32c5522019-12-09 10:11:08 -080040#include <utils/Trace.h>
41
Ady Abraham0bde6b52021-05-18 13:57:02 -070042#include <private/gui/ComposerService.h>
Huihong Luo02186fb2022-02-23 14:21:54 -080043#include <private/gui/ComposerServiceAIDL.h>
Ady Abraham0bde6b52021-05-18 13:57:02 -070044
Chavi Weingartene0237bb2023-02-06 21:48:32 +000045#include <android-base/thread_annotations.h>
Robert Carr78c25dd2019-08-15 14:10:33 -070046
Alec Mouri21d94322023-10-17 19:51:39 +000047#include <com_android_graphics_libgui_flags.h>
48
Ady Abraham6cdd3fd2023-09-07 18:45:58 -070049using namespace com::android::graphics::libgui;
Robert Carr78c25dd2019-08-15 14:10:33 -070050using namespace std::chrono_literals;
51
Vishnu Nairdab94092020-09-29 16:09:04 -070052namespace {
Patrick Williams078d7362024-08-27 10:20:39 -050053
54#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
Patrick Williamsc16a4a52024-10-26 01:48:01 -050055template <class Mutex>
56class UnlockGuard {
Patrick Williams078d7362024-08-27 10:20:39 -050057public:
Patrick Williamsc16a4a52024-10-26 01:48:01 -050058 explicit UnlockGuard(Mutex& lock) : mLock{lock} { mLock.unlock(); }
Patrick Williams078d7362024-08-27 10:20:39 -050059
Patrick Williamsc16a4a52024-10-26 01:48:01 -050060 ~UnlockGuard() { mLock.lock(); }
Patrick Williams078d7362024-08-27 10:20:39 -050061
Patrick Williamsc16a4a52024-10-26 01:48:01 -050062 UnlockGuard(const UnlockGuard&) = delete;
63 UnlockGuard& operator=(const UnlockGuard&) = delete;
Patrick Williams078d7362024-08-27 10:20:39 -050064
65private:
Patrick Williamsc16a4a52024-10-26 01:48:01 -050066 Mutex& mLock;
Patrick Williams078d7362024-08-27 10:20:39 -050067};
68#endif
69
chaviw3277faf2021-05-19 16:45:23 -050070inline const char* boolToString(bool b) {
Vishnu Nairdab94092020-09-29 16:09:04 -070071 return b ? "true" : "false";
72}
Patrick Williams078d7362024-08-27 10:20:39 -050073
Vishnu Nairdab94092020-09-29 16:09:04 -070074} // namespace
75
Robert Carr78c25dd2019-08-15 14:10:33 -070076namespace android {
77
Vishnu Nairdab94092020-09-29 16:09:04 -070078// Macros to include adapter info in log messages
chaviwd7deef72021-10-06 11:53:40 -050079#define BQA_LOGD(x, ...) \
80 ALOGD("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070081#define BQA_LOGV(x, ...) \
82 ALOGV("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairc6f89ee2020-12-11 14:27:32 -080083// enable logs for a single layer
84//#define BQA_LOGV(x, ...) \
85// ALOGV_IF((strstr(mName.c_str(), "SurfaceView") != nullptr), "[%s](f:%u,a:%u) " x, \
86// mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070087#define BQA_LOGE(x, ...) \
88 ALOGE("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
89
chaviw57ae4b22022-02-03 16:51:39 -060090#define BBQ_TRACE(x, ...) \
91 ATRACE_FORMAT("%s - %s(f:%u,a:%u)" x, __FUNCTION__, mName.c_str(), mNumFrameAvailable, \
92 mNumAcquired, ##__VA_ARGS__)
93
Chavi Weingartene0237bb2023-02-06 21:48:32 +000094#define UNIQUE_LOCK_WITH_ASSERTION(mutex) \
95 std::unique_lock _lock{mutex}; \
96 base::ScopedLockAssertion assumeLocked(mutex);
97
Valerie Hau871d6352020-01-29 08:44:02 -080098void BLASTBufferItemConsumer::onDisconnect() {
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000099 Mutex::Autolock lock(mMutex);
100 mPreviouslyConnected = mCurrentlyConnected;
101 mCurrentlyConnected = false;
102 if (mPreviouslyConnected) {
103 mDisconnectEvents.push(mCurrentFrameNumber);
Valerie Hau871d6352020-01-29 08:44:02 -0800104 }
Jiakai Zhangc33c63a2021-11-09 11:24:04 +0000105 mFrameEventHistory.onDisconnect();
Valerie Hau871d6352020-01-29 08:44:02 -0800106}
107
108void BLASTBufferItemConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
109 FrameEventHistoryDelta* outDelta) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800110 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800111 if (newTimestamps) {
112 // BufferQueueProducer only adds a new timestamp on
113 // queueBuffer
114 mCurrentFrameNumber = newTimestamps->frameNumber;
115 mFrameEventHistory.addQueue(*newTimestamps);
116 }
117 if (outDelta) {
118 // frame event histories will be processed
119 // only after the producer connects and requests
120 // deltas for the first time. Forward this intent
121 // to SF-side to turn event processing back on
122 mPreviouslyConnected = mCurrentlyConnected;
123 mCurrentlyConnected = true;
124 mFrameEventHistory.getAndResetDelta(outDelta);
125 }
126}
127
Alec Mouri21d94322023-10-17 19:51:39 +0000128void BLASTBufferItemConsumer::updateFrameTimestamps(
129 uint64_t frameNumber, uint64_t previousFrameNumber, nsecs_t refreshStartTime,
130 const sp<Fence>& glDoneFence, const sp<Fence>& presentFence,
131 const sp<Fence>& prevReleaseFence, CompositorTiming compositorTiming, nsecs_t latchTime,
132 nsecs_t dequeueReadyTime) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800133 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800134
135 // if the producer is not connected, don't bother updating,
136 // the next producer that connects won't access this frame event
137 if (!mCurrentlyConnected) return;
138 std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
139 std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
140 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
141
142 mFrameEventHistory.addLatch(frameNumber, latchTime);
Alec Mouri21d94322023-10-17 19:51:39 +0000143 if (flags::frametimestamps_previousrelease()) {
144 if (previousFrameNumber > 0) {
145 mFrameEventHistory.addRelease(previousFrameNumber, dequeueReadyTime,
146 std::move(releaseFenceTime));
147 }
148 } else {
149 mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
150 }
151
Valerie Hau871d6352020-01-29 08:44:02 -0800152 mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
153 mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
154 compositorTiming);
155}
156
157void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
158 bool disconnect = false;
Hongguang Chen621ec582021-02-16 15:42:35 -0800159 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800160 while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
161 disconnect = true;
162 mDisconnectEvents.pop();
163 }
164 if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
165}
166
Hongguang Chen621ec582021-02-16 15:42:35 -0800167void BLASTBufferItemConsumer::onSidebandStreamChanged() {
Ady Abrahamdbca1352021-12-15 11:58:56 -0800168 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
169 if (bbq != nullptr) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800170 sp<NativeHandle> stream = getSidebandStream();
Ady Abrahamdbca1352021-12-15 11:58:56 -0800171 bbq->setSidebandStream(stream);
Hongguang Chen621ec582021-02-16 15:42:35 -0800172 }
173}
174
Ady Abraham107788e2023-10-17 12:31:08 -0700175#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_SETFRAMERATE)
Ady Abraham6cdd3fd2023-09-07 18:45:58 -0700176void BLASTBufferItemConsumer::onSetFrameRate(float frameRate, int8_t compatibility,
177 int8_t changeFrameRateStrategy) {
178 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
179 if (bbq != nullptr) {
180 bbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
181 }
182}
183#endif
184
Brian Lindahlc794b692023-01-31 15:42:47 -0700185void BLASTBufferItemConsumer::resizeFrameEventHistory(size_t newSize) {
186 Mutex::Autolock lock(mMutex);
187 mFrameEventHistory.resize(newSize);
188}
189
Vishnu Naird2aaab12022-02-10 14:49:09 -0800190BLASTBufferQueue::BLASTBufferQueue(const std::string& name, bool updateDestinationFrame)
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800191 : mSurfaceControl(nullptr),
192 mSize(1, 1),
Vishnu Nairea0de002020-11-17 17:42:37 -0800193 mRequestedSize(mSize),
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800194 mFormat(PIXEL_FORMAT_RGBA_8888),
Tianhao Yao4861b102022-02-03 20:18:35 +0000195 mTransactionReadyCallback(nullptr),
Vishnu Naird2aaab12022-02-10 14:49:09 -0800196 mSyncTransaction(nullptr),
197 mUpdateDestinationFrame(updateDestinationFrame) {
Vishnu Nair89496122020-12-14 17:14:53 -0800198 createBufferQueue(&mProducer, &mConsumer);
Jim Shargod30823a2024-07-27 02:49:39 +0000199#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_CONSUMER_BASE_OWNS_BQ)
Anton Ivanov27955ee2025-02-18 14:18:30 -0800200 mBufferItemConsumer = sp<BLASTBufferItemConsumer>::make(mProducer, mConsumer,
201 GraphicBuffer::USAGE_HW_COMPOSER |
202 GraphicBuffer::USAGE_HW_TEXTURE,
203 1, false, this);
Jim Shargod30823a2024-07-27 02:49:39 +0000204#else
Anton Ivanov27955ee2025-02-18 14:18:30 -0800205 mBufferItemConsumer = sp<BLASTBufferItemConsumer>::make(mConsumer,
206 GraphicBuffer::USAGE_HW_COMPOSER |
207 GraphicBuffer::USAGE_HW_TEXTURE,
208 1, false, this);
Jim Shargod30823a2024-07-27 02:49:39 +0000209#endif // COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_CONSUMER_BASE_OWNS_BQ)
210 // since the adapter is in the client process, set dequeue timeout
211 // explicitly so that dequeueBuffer will block
212 mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
213
liulijuneb489f62022-10-17 22:02:14 +0800214 static std::atomic<uint32_t> nextId = 0;
215 mProducerId = nextId++;
216 mName = name + "#" + std::to_string(mProducerId);
217 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(mProducerId);
218 mQueuedBufferTrace = "QueuedBuffer - " + mName + "BLAST#" + std::to_string(mProducerId);
Vishnu Nairdab94092020-09-29 16:09:04 -0700219 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700220 mBufferItemConsumer->setFrameAvailableListener(this);
Robert Carr9f133d72020-04-01 15:51:46 -0700221
Huihong Luo02186fb2022-02-23 14:21:54 -0800222 ComposerServiceAIDL::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);
Ady Abraham0bde6b52021-05-18 13:57:02 -0700223 mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
chaviw69058fb2021-09-27 09:37:30 -0500224 mCurrentMaxAcquiredBufferCount = mMaxAcquiredBuffers;
Robert Carr4c1b6462021-12-21 10:30:50 -0800225
226 TransactionCompletedListener::getInstance()->addQueueStallListener(
Patrick Williamsf1e5df12022-10-17 21:37:42 +0000227 [&](const std::string& reason) {
228 std::function<void(const std::string&)> callbackCopy;
229 {
230 std::unique_lock _lock{mMutex};
231 callbackCopy = mTransactionHangCallback;
232 }
233 if (callbackCopy) callbackCopy(reason);
234 },
235 this);
Robert Carr4c1b6462021-12-21 10:30:50 -0800236
Patrick Williams7c9fa272024-08-30 12:38:43 +0000237#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
Patrick Williams078d7362024-08-27 10:20:39 -0500238 gui::BufferReleaseChannel::open(mName, mBufferReleaseConsumer, mBufferReleaseProducer);
239 mBufferReleaseReader.emplace(*this);
Patrick Williams7c9fa272024-08-30 12:38:43 +0000240#endif
241
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800242 BQA_LOGV("BLASTBufferQueue created");
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800243}
244
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800245BLASTBufferQueue::~BLASTBufferQueue() {
Robert Carr4c1b6462021-12-21 10:30:50 -0800246 TransactionCompletedListener::getInstance()->removeQueueStallListener(this);
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800247 if (mPendingTransactions.empty()) {
248 return;
249 }
250 BQA_LOGE("Applying pending transactions on dtor %d",
251 static_cast<uint32_t>(mPendingTransactions.size()));
252 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800253 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
Robert Carr79dc06a2022-02-22 15:28:59 -0800254 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
255 t.setApplyToken(mApplyToken).apply(false, true);
chaviw3b4bdcf2022-03-17 09:27:03 -0500256
257 if (mTransactionReadyCallback) {
258 mTransactionReadyCallback(mSyncTransaction);
259 }
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800260}
261
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500262void BLASTBufferQueue::onFirstRef() {
263 // safe default, most producers are expected to override this
264 mProducer->setMaxDequeuedBufferCount(2);
265}
266
chaviw565ee542021-01-14 10:21:23 -0800267void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Naird2aaab12022-02-10 14:49:09 -0800268 int32_t format) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800269 LOG_ALWAYS_FATAL_IF(surface == nullptr, "BLASTBufferQueue: mSurfaceControl must not be NULL");
270
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000271 std::lock_guard _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800272 if (mFormat != format) {
273 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800274 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800275 }
276
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800277 const bool surfaceControlChanged = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairab066512022-01-04 22:28:00 +0000278 if (surfaceControlChanged && mSurfaceControl != nullptr) {
279 BQA_LOGD("Updating SurfaceControl without recreating BBQ");
280 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800281
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700282 // Always update the native object even though they might have the same layer handle, so we can
283 // get the updated transform hint from WM.
284 mSurfaceControl = surface;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800285 SurfaceComposerClient::Transaction t;
Brian Lindahl628cff42024-10-30 11:50:28 -0600286 bool applyTransaction = false;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800287 if (surfaceControlChanged) {
Patrick Williamsc16a4a52024-10-26 01:48:01 -0500288#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
Patrick Williamsa419faa2024-10-29 16:50:27 -0500289 updateBufferReleaseProducer();
Patrick Williamsc16a4a52024-10-26 01:48:01 -0500290#endif
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800291 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
292 layer_state_t::eEnableBackpressure);
Brian Lindahl628cff42024-10-30 11:50:28 -0600293 // Migrate the picture profile handle to the new surface control.
294 if (com_android_graphics_libgui_flags_apply_picture_profiles() &&
295 mPictureProfileHandle.has_value()) {
296 t.setPictureProfileHandle(mSurfaceControl, *mPictureProfileHandle);
297 }
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800298 applyTransaction = true;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800299 }
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800300 mTransformHint = mSurfaceControl->getTransformHint();
301 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700302 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
303 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800304
Vishnu Nairea0de002020-11-17 17:42:37 -0800305 ui::Size newSize(width, height);
306 if (mRequestedSize != newSize) {
307 mRequestedSize.set(newSize);
308 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000309 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800310 // If the buffer supports scaling, update the frame immediately since the client may
311 // want to scale the existing buffer to the new size.
312 mSize = mRequestedSize;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800313 if (mUpdateDestinationFrame) {
314 t.setDestinationFrame(mSurfaceControl, Rect(newSize));
315 applyTransaction = true;
316 }
Vishnu Nair53c936c2020-12-03 11:46:37 -0800317 }
Robert Carrfc416512020-04-02 12:32:44 -0700318 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800319 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800320 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
Patrick Williamsc16a4a52024-10-26 01:48:01 -0500321 t.setApplyToken(mApplyToken).apply(false /* synchronous */, true /* oneWay */);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800322 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700323}
324
chaviwd7deef72021-10-06 11:53:40 -0500325static std::optional<SurfaceControlStats> findMatchingStat(
326 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
327 for (auto stat : stats) {
328 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
329 return stat;
330 }
331 }
332 return std::nullopt;
333}
334
Patrick Williams5312ec12024-08-23 16:11:10 -0500335TransactionCompletedCallbackTakesContext BLASTBufferQueue::makeTransactionCommittedCallbackThunk() {
336 return [bbq = sp<BLASTBufferQueue>::fromExisting(
337 this)](void* /*context*/, nsecs_t latchTime, const sp<Fence>& presentFence,
338 const std::vector<SurfaceControlStats>& stats) {
339 bbq->transactionCommittedCallback(latchTime, presentFence, stats);
340 };
chaviwd7deef72021-10-06 11:53:40 -0500341}
342
343void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
344 const sp<Fence>& /*presentFence*/,
345 const std::vector<SurfaceControlStats>& stats) {
346 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000347 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600348 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500349 BQA_LOGV("transactionCommittedCallback");
350 if (!mSurfaceControlsWithPendingCallback.empty()) {
351 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
352 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
353 if (stat) {
354 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
355
356 // We need to check if we were waiting for a transaction callback in order to
357 // process any pending buffers and unblock. It's possible to get transaction
chaviwc1cf4022022-06-03 13:32:33 -0500358 // callbacks for previous requests so we need to ensure that there are no pending
359 // frame numbers that were in a sync. We remove the frame from mSyncedFrameNumbers
360 // set and then check if it's empty. If there are no more pending syncs, we can
361 // proceed with flushing the shadow queue.
chaviwc1cf4022022-06-03 13:32:33 -0500362 mSyncedFrameNumbers.erase(currFrameNumber);
Chavi Weingartend48797b2023-08-04 13:11:39 +0000363 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500364 flushShadowQueue();
365 }
366 } else {
chaviw768bfa02021-11-01 09:50:57 -0500367 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviwd7deef72021-10-06 11:53:40 -0500368 }
369 } else {
370 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
371 "empty.");
372 }
chaviwd7deef72021-10-06 11:53:40 -0500373 }
374}
375
Patrick Williams5312ec12024-08-23 16:11:10 -0500376TransactionCompletedCallbackTakesContext BLASTBufferQueue::makeTransactionCallbackThunk() {
377 return [bbq = sp<BLASTBufferQueue>::fromExisting(
378 this)](void* /*context*/, nsecs_t latchTime, const sp<Fence>& presentFence,
379 const std::vector<SurfaceControlStats>& stats) {
380 bbq->transactionCallback(latchTime, presentFence, stats);
381 };
Robert Carr78c25dd2019-08-15 14:10:33 -0700382}
383
384void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
385 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700386 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000387 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600388 BBQ_TRACE();
chaviw71c2cc42020-10-23 16:42:02 -0700389 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700390
chaviw42026162021-04-16 15:46:12 -0500391 if (!mSurfaceControlsWithPendingCallback.empty()) {
392 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
393 mSurfaceControlsWithPendingCallback.pop();
chaviwd7deef72021-10-06 11:53:40 -0500394 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
395 if (statsOptional) {
396 SurfaceControlStats stat = *statsOptional;
Vishnu Nair71fcf912022-10-18 09:14:20 -0700397 if (stat.transformHint) {
398 mTransformHint = *stat.transformHint;
399 mBufferItemConsumer->setTransformHint(mTransformHint);
400 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
401 }
Vishnu Nairde66dc72021-06-17 17:54:41 -0700402 // Update frametime stamps if the frame was latched and presented, indicated by a
403 // valid latch time.
404 if (stat.latchTime > 0) {
405 mBufferItemConsumer
406 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
Alec Mouri21d94322023-10-17 19:51:39 +0000407 stat.frameEventStats.previousFrameNumber,
Vishnu Nairde66dc72021-06-17 17:54:41 -0700408 stat.frameEventStats.refreshStartTime,
409 stat.frameEventStats.gpuCompositionDoneFence,
410 stat.presentFence, stat.previousReleaseFence,
411 stat.frameEventStats.compositorTiming,
412 stat.latchTime,
413 stat.frameEventStats.dequeueReadyTime);
414 }
Robert Carr405e2f62021-12-31 16:59:34 -0800415 auto currFrameNumber = stat.frameEventStats.frameNumber;
Anton Ivanov7016de52025-02-05 17:39:41 -0800416 // Release stale buffers.
417 for (const auto& [key, _] : mSubmitted) {
418 if (currFrameNumber <= key.framenumber) {
419 continue; // not stale.
Robert Carr405e2f62021-12-31 16:59:34 -0800420 }
Anton Ivanov7016de52025-02-05 17:39:41 -0800421 releaseBufferCallbackLocked(key,
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700422 stat.previousReleaseFence
423 ? stat.previousReleaseFence
424 : Fence::NO_FENCE,
425 stat.currentMaxAcquiredBufferCount,
426 true /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800427 }
chaviwd7deef72021-10-06 11:53:40 -0500428 } else {
chaviw768bfa02021-11-01 09:50:57 -0500429 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500430 }
431 } else {
432 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
433 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800434 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700435 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700436}
437
Patrick Williams7c9fa272024-08-30 12:38:43 +0000438void BLASTBufferQueue::flushShadowQueue() {
439 BQA_LOGV("flushShadowQueue");
Shuangxi Xianga576ccd2025-02-12 03:39:54 -0800440 int32_t numFramesToFlush = mNumFrameAvailable;
Patrick Williams7c9fa272024-08-30 12:38:43 +0000441 while (numFramesToFlush > 0) {
442 acquireNextBufferLocked(std::nullopt);
443 numFramesToFlush--;
444 }
445}
446
Vishnu Nair1506b182021-02-22 14:35:15 -0800447// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
448// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
449// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
450// Otherwise, this is a no-op.
Patrick Williams5312ec12024-08-23 16:11:10 -0500451ReleaseBufferCallback BLASTBufferQueue::makeReleaseBufferCallbackThunk() {
452 return [weakBbq = wp<BLASTBufferQueue>::fromExisting(
453 this)](const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
454 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
455 sp<BLASTBufferQueue> bbq = weakBbq.promote();
456 if (!bbq) {
457 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
458 return;
459 }
460 bbq->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
Patrick Williamsc16a4a52024-10-26 01:48:01 -0500461#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
462 bbq->drainBufferReleaseConsumer();
463#endif
Patrick Williams5312ec12024-08-23 16:11:10 -0500464 };
Vishnu Nair1506b182021-02-22 14:35:15 -0800465}
466
chaviw69058fb2021-09-27 09:37:30 -0500467void BLASTBufferQueue::releaseBufferCallback(
468 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
469 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000470 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600471 BBQ_TRACE();
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700472 releaseBufferCallbackLocked(id, releaseFence, currentMaxAcquiredBufferCount,
473 false /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800474}
475
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700476void BLASTBufferQueue::releaseBufferCallbackLocked(
477 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
478 std::optional<uint32_t> currentMaxAcquiredBufferCount, bool fakeRelease) {
Robert Carr405e2f62021-12-31 16:59:34 -0800479 ATRACE_CALL();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700480 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800481
Ady Abraham899dcdb2021-06-15 16:56:21 -0700482 // Calculate how many buffers we need to hold before we release them back
483 // to the buffer queue. This will prevent higher latency when we are running
484 // on a lower refresh rate than the max supported. We only do that for EGL
485 // clients as others don't care about latency
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000486 const auto it = mSubmitted.find(id);
487 const bool isEGL = it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
Ady Abraham899dcdb2021-06-15 16:56:21 -0700488
chaviw69058fb2021-09-27 09:37:30 -0500489 if (currentMaxAcquiredBufferCount) {
490 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
491 }
492
liulijunf90df632022-11-14 14:24:48 +0800493 const uint32_t numPendingBuffersToHold =
494 isEGL ? std::max(0, mMaxAcquiredBuffers - (int32_t)mCurrentMaxAcquiredBufferCount) : 0;
Robert Carr405e2f62021-12-31 16:59:34 -0800495
496 auto rb = ReleasedBuffer{id, releaseFence};
497 if (std::find(mPendingRelease.begin(), mPendingRelease.end(), rb) == mPendingRelease.end()) {
498 mPendingRelease.emplace_back(rb);
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700499 if (fakeRelease) {
500 BQA_LOGE("Faking releaseBufferCallback from transactionCompleteCallback %" PRIu64,
501 id.framenumber);
502 BBQ_TRACE("FakeReleaseCallback");
503 }
Robert Carr405e2f62021-12-31 16:59:34 -0800504 }
Ady Abraham899dcdb2021-06-15 16:56:21 -0700505
506 // Release all buffers that are beyond the ones that we need to hold
507 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500508 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700509 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500510 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwc1cf4022022-06-03 13:32:33 -0500511 // Don't process the transactions here if mSyncedFrameNumbers is not empty. That means
512 // are still transactions that have sync buffers in them that have not been applied or
513 // dropped. Instead, let onFrameAvailable handle processing them since it will merge with
514 // the syncTransaction.
515 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500516 acquireNextBufferLocked(std::nullopt);
517 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800518 }
519
Ady Abraham899dcdb2021-06-15 16:56:21 -0700520 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700521 ATRACE_INT(mQueuedBufferTrace.c_str(),
522 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800523 mCallbackCV.notify_all();
524}
525
chaviw0acd33a2021-11-02 11:55:37 -0500526void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
527 const sp<Fence>& releaseFence) {
528 auto it = mSubmitted.find(callbackId);
529 if (it == mSubmitted.end()) {
chaviw0acd33a2021-11-02 11:55:37 -0500530 return;
531 }
532 mNumAcquired--;
chaviw57ae4b22022-02-03 16:51:39 -0600533 BBQ_TRACE("frame=%" PRIu64, callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500534 BQA_LOGV("released %s", callbackId.to_string().c_str());
535 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
536 mSubmitted.erase(it);
chaviwc1cf4022022-06-03 13:32:33 -0500537 // Remove the frame number from mSyncedFrameNumbers since we can get a release callback
538 // without getting a transaction committed if the buffer was dropped.
539 mSyncedFrameNumbers.erase(callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500540}
541
Chavi Weingarten70670e62023-02-22 17:36:40 +0000542static ui::Size getBufferSize(const BufferItem& item) {
543 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
544 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
545
546 // Take the buffer's orientation into account
547 if (item.mTransform & ui::Transform::ROT_90) {
548 std::swap(bufWidth, bufHeight);
549 }
550 return ui::Size(bufWidth, bufHeight);
551}
552
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000553status_t BLASTBufferQueue::acquireNextBufferLocked(
chaviwd7deef72021-10-06 11:53:40 -0500554 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800555 // Check if we have frames available and we have not acquired the maximum number of buffers.
556 // Even with this check, the consumer can fail to acquire an additional buffer if the consumer
557 // has already acquired (mMaxAcquiredBuffers + 1) and the new buffer is not droppable. In this
558 // case mBufferItemConsumer->acquireBuffer will return with NO_BUFFER_AVAILABLE.
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000559 if (mNumFrameAvailable == 0) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800560 BQA_LOGV("Can't acquire next buffer. No available frames");
561 return BufferQueue::NO_BUFFER_AVAILABLE;
562 }
563
564 if (mNumAcquired >= (mMaxAcquiredBuffers + 2)) {
565 BQA_LOGV("Can't acquire next buffer. Already acquired max frames %d max:%d + 2",
566 mNumAcquired, mMaxAcquiredBuffers);
567 return BufferQueue::NO_BUFFER_AVAILABLE;
Valerie Haud3b90d22019-11-06 09:37:31 -0800568 }
569
Valerie Haua32c5522019-12-09 10:11:08 -0800570 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700571 BQA_LOGE("ERROR : surface control is null");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000572 return NAME_NOT_FOUND;
Valerie Haud3b90d22019-11-06 09:37:31 -0800573 }
574
Robert Carr78c25dd2019-08-15 14:10:33 -0700575 SurfaceComposerClient::Transaction localTransaction;
576 bool applyTransaction = true;
577 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500578 if (transaction) {
579 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700580 applyTransaction = false;
581 }
582
Patrick Williams3ced5382024-08-21 15:39:32 -0500583 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800584
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800585 status_t status =
586 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800587 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
588 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000589 return status;
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800590 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700591 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000592 return status;
Robert Carr78c25dd2019-08-15 14:10:33 -0700593 }
chaviw57ae4b22022-02-03 16:51:39 -0600594
Valerie Haua32c5522019-12-09 10:11:08 -0800595 auto buffer = bufferItem.mGraphicBuffer;
596 mNumFrameAvailable--;
chaviw57ae4b22022-02-03 16:51:39 -0600597 BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800598
599 if (buffer == nullptr) {
600 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700601 BQA_LOGE("Buffer was empty");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000602 return BAD_VALUE;
Valerie Haua32c5522019-12-09 10:11:08 -0800603 }
604
Vishnu Nair670b3f72020-09-29 17:52:18 -0700605 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700606 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800607 "buffer{size=%dx%d transform=%d}",
608 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
609 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
610 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000611 return acquireNextBufferLocked(transaction);
Vishnu Nair670b3f72020-09-29 17:52:18 -0700612 }
613
Valerie Haua32c5522019-12-09 10:11:08 -0800614 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700615 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
616 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
Anton Ivanov7016de52025-02-05 17:39:41 -0800617 mSubmitted.emplace_or_replace(releaseCallbackId, bufferItem);
Robert Carr78c25dd2019-08-15 14:10:33 -0700618
Valerie Hau871d6352020-01-29 08:44:02 -0800619 bool needsDisconnect = false;
620 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
621
622 // if producer disconnected before, notify SurfaceFlinger
623 if (needsDisconnect) {
624 t->notifyProducerDisconnect(mSurfaceControl);
625 }
626
Chavi Weingarten70670e62023-02-22 17:36:40 +0000627 // Only update mSize for destination bounds if the incoming buffer matches the requested size.
628 // Otherwise, it could cause stretching since the destination bounds will update before the
629 // buffer with the new size is acquired.
Vishnu Nair5b5f6932023-04-12 16:28:19 -0700630 if (mRequestedSize == getBufferSize(bufferItem) ||
631 bufferItem.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Chavi Weingarten70670e62023-02-22 17:36:40 +0000632 mSize = mRequestedSize;
633 }
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700634 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000635 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
636 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700637 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800638
Patrick Williams5312ec12024-08-23 16:11:10 -0500639 auto releaseBufferCallback = makeReleaseBufferCallbackThunk();
Anton Ivanov8ed86592025-02-20 11:52:50 -0800640 sp<Fence> fence =
641 bufferItem.mFence ? sp<Fence>::make(bufferItem.mFence->dup()) : Fence::NO_FENCE;
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900642
643 nsecs_t dequeueTime = -1;
644 {
645 std::lock_guard _lock{mTimestampMutex};
646 auto dequeueTimeIt = mDequeueTimestamps.find(buffer->getId());
647 if (dequeueTimeIt != mDequeueTimestamps.end()) {
648 dequeueTime = dequeueTimeIt->second;
649 mDequeueTimestamps.erase(dequeueTimeIt);
650 }
651 }
652
liulijuneb489f62022-10-17 22:02:14 +0800653 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, mProducerId,
Nergi Rahardi39f510f2024-05-23 15:16:54 +0900654 releaseBufferCallback, dequeueTime);
John Reck137069e2020-12-10 22:07:37 -0500655 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
656 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
657 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Patrick Williams5312ec12024-08-23 16:11:10 -0500658 t->addTransactionCompletedCallback(makeTransactionCallbackThunk(), nullptr);
chaviwf2dace72021-11-17 17:36:50 -0600659
chaviw42026162021-04-16 15:46:12 -0500660 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700661
Vishnu Naird2aaab12022-02-10 14:49:09 -0800662 if (mUpdateDestinationFrame) {
663 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
664 } else {
665 const bool ignoreDestinationFrame =
666 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
667 t->setFlags(mSurfaceControl,
668 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
669 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700670 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700671 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800672 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800673 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800674 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800675 if (!bufferItem.mIsAutoTimestamp) {
676 t->setDesiredPresentTime(bufferItem.mTimestamp);
677 }
Brian Lindahl628cff42024-10-30 11:50:28 -0600678 if (com_android_graphics_libgui_flags_apply_picture_profiles() &&
679 bufferItem.mPictureProfileHandle.has_value()) {
680 t->setPictureProfileHandle(mSurfaceControl, *bufferItem.mPictureProfileHandle);
681 // The current picture profile must be maintained in case the BBQ gets its
682 // SurfaceControl switched out.
683 mPictureProfileHandle = bufferItem.mPictureProfileHandle;
684 // Clear out the picture profile if the requestor has asked for it to be cleared
685 if (mPictureProfileHandle == PictureProfileHandle::NONE) {
686 mPictureProfileHandle = std::nullopt;
687 }
688 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700689
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800690 // Drop stale frame timeline infos
691 while (!mPendingFrameTimelines.empty() &&
692 mPendingFrameTimelines.front().first < bufferItem.mFrameNumber) {
693 ATRACE_FORMAT_INSTANT("dropping stale frameNumber: %" PRIu64 " vsyncId: %" PRId64,
694 mPendingFrameTimelines.front().first,
695 mPendingFrameTimelines.front().second.vsyncId);
696 mPendingFrameTimelines.pop();
697 }
698
699 if (!mPendingFrameTimelines.empty() &&
700 mPendingFrameTimelines.front().first == bufferItem.mFrameNumber) {
701 ATRACE_FORMAT_INSTANT("Transaction::setFrameTimelineInfo frameNumber: %" PRIu64
702 " vsyncId: %" PRId64,
703 bufferItem.mFrameNumber,
704 mPendingFrameTimelines.front().second.vsyncId);
705 t->setFrameTimelineInfo(mPendingFrameTimelines.front().second);
706 mPendingFrameTimelines.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100707 }
708
chaviw6a195272021-09-03 16:14:25 -0500709 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700710 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800711 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
712 t->setApplyToken(mApplyToken).apply(false, true);
713 mAppliedLastTransaction = true;
714 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
715 } else {
716 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
717 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700718 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700719
chaviwd7deef72021-10-06 11:53:40 -0500720 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800721 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700722 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500723 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800724 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700725 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700726 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000727 return OK;
Robert Carr78c25dd2019-08-15 14:10:33 -0700728}
729
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800730Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
731 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800732 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800733 }
734 return item.mCrop;
735}
736
chaviwd7deef72021-10-06 11:53:40 -0500737void BLASTBufferQueue::acquireAndReleaseBuffer() {
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000738 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500739 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500740 status_t status =
741 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
742 if (status != OK) {
743 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
744 statusToString(status).c_str());
745 return;
746 }
chaviwd7deef72021-10-06 11:53:40 -0500747 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500748 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500749}
750
Vishnu Nairaef1de92020-10-22 12:15:53 -0700751void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000752 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
753 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
chaviwc1cf4022022-06-03 13:32:33 -0500754
Tianhao Yao4861b102022-02-03 20:18:35 +0000755 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000756 UNIQUE_LOCK_WITH_ASSERTION(mMutex);
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000757 BBQ_TRACE();
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000758 bool waitForTransactionCallback = !mSyncedFrameNumbers.empty();
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800759
Tianhao Yao4861b102022-02-03 20:18:35 +0000760 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
761 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800762
Tianhao Yao4861b102022-02-03 20:18:35 +0000763 if (syncTransactionSet) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000764 // If we are going to re-use the same mSyncTransaction, release the buffer that may
765 // already be set in the Transaction. This is to allow us a free slot early to continue
766 // processing a new buffer.
767 if (!mAcquireSingleBuffer) {
768 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
769 if (bufferData) {
770 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
771 bufferData->frameNumber);
772 releaseBuffer(bufferData->generateReleaseCallbackId(),
773 bufferData->acquireFence);
Tianhao Yao4861b102022-02-03 20:18:35 +0000774 }
775 }
chaviw0acd33a2021-11-02 11:55:37 -0500776
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000777 if (waitForTransactionCallback) {
778 // We are waiting on a previous sync's transaction callback so allow another sync
779 // transaction to proceed.
780 //
781 // We need to first flush out the transactions that were in between the two syncs.
782 // We do this by merging them into mSyncTransaction so any buffer merging will get
783 // a release callback invoked.
784 while (mNumFrameAvailable > 0) {
785 // flush out the shadow queue
786 acquireAndReleaseBuffer();
787 }
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800788 } else {
789 // Make sure the frame available count is 0 before proceeding with a sync to ensure
790 // the correct frame is used for the sync. The only way mNumFrameAvailable would be
791 // greater than 0 is if we already ran out of buffers previously. This means we
792 // need to flush the buffers before proceeding with the sync.
793 while (mNumFrameAvailable > 0) {
794 BQA_LOGD("waiting until no queued buffers");
795 mCallbackCV.wait(_lock);
796 }
chaviwd7deef72021-10-06 11:53:40 -0500797 }
798 }
799
Tianhao Yao4861b102022-02-03 20:18:35 +0000800 // add to shadow queue
801 mNumFrameAvailable++;
chaviwc1cf4022022-06-03 13:32:33 -0500802 if (waitForTransactionCallback && mNumFrameAvailable >= 2) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000803 acquireAndReleaseBuffer();
804 }
805 ATRACE_INT(mQueuedBufferTrace.c_str(),
806 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
807
808 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
809 item.mFrameNumber, boolToString(syncTransactionSet));
810
811 if (syncTransactionSet) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800812 // Add to mSyncedFrameNumbers before waiting in case any buffers are released
813 // while waiting for a free buffer. The release and commit callback will try to
814 // acquire buffers if there are any available, but we don't want it to acquire
815 // in the case where a sync transaction wants the buffer.
816 mSyncedFrameNumbers.emplace(item.mFrameNumber);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000817 // If there's no available buffer and we're in a sync transaction, we need to wait
818 // instead of returning since we guarantee a buffer will be acquired for the sync.
819 while (acquireNextBufferLocked(mSyncTransaction) == BufferQueue::NO_BUFFER_AVAILABLE) {
820 BQA_LOGD("waiting for available buffer");
821 mCallbackCV.wait(_lock);
822 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000823
824 // Only need a commit callback when syncing to ensure the buffer that's synced has been
825 // sent to SF
Patrick Williams5312ec12024-08-23 16:11:10 -0500826 mSyncTransaction
827 ->addTransactionCommittedCallback(makeTransactionCommittedCallbackThunk(),
828 nullptr);
Tianhao Yao4861b102022-02-03 20:18:35 +0000829 if (mAcquireSingleBuffer) {
830 prevCallback = mTransactionReadyCallback;
831 prevTransaction = mSyncTransaction;
832 mTransactionReadyCallback = nullptr;
833 mSyncTransaction = nullptr;
834 }
chaviwc1cf4022022-06-03 13:32:33 -0500835 } else if (!waitForTransactionCallback) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000836 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800837 }
838 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000839 if (prevCallback) {
840 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500841 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800842}
843
Vishnu Nairaef1de92020-10-22 12:15:53 -0700844void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
845 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
846 // Do nothing since we are not storing unacquired buffer items locally.
847}
848
Vishnu Nairadf632b2021-01-07 14:05:08 -0800849void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000850 std::lock_guard _lock{mTimestampMutex};
Anton Ivanov7016de52025-02-05 17:39:41 -0800851 mDequeueTimestamps.emplace_or_replace(bufferId, systemTime());
Patrick Williams4b9507d2024-07-25 09:55:52 -0500852};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800853
854void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
Patrick Williams3ced5382024-08-21 15:39:32 -0500855 std::lock_guard _lock{mTimestampMutex};
856 mDequeueTimestamps.erase(bufferId);
Patrick Williamsf5b42de2024-08-01 16:08:51 -0500857}
Vishnu Nairadf632b2021-01-07 14:05:08 -0800858
Chavi Weingartenc398c012023-04-12 17:26:02 +0000859bool BLASTBufferQueue::syncNextTransaction(
Tianhao Yao4861b102022-02-03 20:18:35 +0000860 std::function<void(SurfaceComposerClient::Transaction*)> callback,
861 bool acquireSingleBuffer) {
Chavi Weingartenc398c012023-04-12 17:26:02 +0000862 LOG_ALWAYS_FATAL_IF(!callback,
863 "BLASTBufferQueue: callback passed in to syncNextTransaction must not be "
864 "NULL");
chaviw3b4bdcf2022-03-17 09:27:03 -0500865
Chavi Weingartenc398c012023-04-12 17:26:02 +0000866 std::lock_guard _lock{mMutex};
867 BBQ_TRACE();
868 if (mTransactionReadyCallback) {
869 ALOGW("Attempting to overwrite transaction callback in syncNextTransaction");
870 return false;
Tianhao Yao4861b102022-02-03 20:18:35 +0000871 }
chaviw3b4bdcf2022-03-17 09:27:03 -0500872
Chavi Weingartenc398c012023-04-12 17:26:02 +0000873 mTransactionReadyCallback = callback;
874 mSyncTransaction = new SurfaceComposerClient::Transaction();
875 mAcquireSingleBuffer = acquireSingleBuffer;
876 return true;
Tianhao Yao4861b102022-02-03 20:18:35 +0000877}
878
879void BLASTBufferQueue::stopContinuousSyncTransaction() {
880 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
881 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
882 {
883 std::lock_guard _lock{mMutex};
Chavi Weingartenc398c012023-04-12 17:26:02 +0000884 if (mAcquireSingleBuffer || !mTransactionReadyCallback) {
885 ALOGW("Attempting to stop continuous sync when none are active");
886 return;
Tianhao Yao4861b102022-02-03 20:18:35 +0000887 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000888
889 prevCallback = mTransactionReadyCallback;
890 prevTransaction = mSyncTransaction;
891
Tianhao Yao4861b102022-02-03 20:18:35 +0000892 mTransactionReadyCallback = nullptr;
893 mSyncTransaction = nullptr;
894 mAcquireSingleBuffer = true;
895 }
Chavi Weingartenc398c012023-04-12 17:26:02 +0000896
Tianhao Yao4861b102022-02-03 20:18:35 +0000897 if (prevCallback) {
898 prevCallback(prevTransaction);
899 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700900}
901
Chavi Weingartenc398c012023-04-12 17:26:02 +0000902void BLASTBufferQueue::clearSyncTransaction() {
903 std::lock_guard _lock{mMutex};
904 if (!mAcquireSingleBuffer) {
905 ALOGW("Attempting to clear sync transaction when none are active");
906 return;
907 }
908
909 mTransactionReadyCallback = nullptr;
910 mSyncTransaction = nullptr;
911}
912
Vishnu Nairea0de002020-11-17 17:42:37 -0800913bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700914 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
915 // Only reject buffers if scaling mode is freeze.
916 return false;
917 }
918
Chavi Weingarten70670e62023-02-22 17:36:40 +0000919 ui::Size bufferSize = getBufferSize(item);
Vishnu Nairea0de002020-11-17 17:42:37 -0800920 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800921 return false;
922 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700923
Vishnu Nair670b3f72020-09-29 17:52:18 -0700924 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800925 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700926}
Vishnu Nairbf255772020-10-16 10:54:41 -0700927
Robert Carr05086b22020-10-13 18:22:51 -0700928class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700929private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700930 std::mutex mMutex;
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000931 sp<BLASTBufferQueue> mBbq GUARDED_BY(mMutex);
932 bool mDestroyed GUARDED_BY(mMutex) = false;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700933
Robert Carr05086b22020-10-13 18:22:51 -0700934public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700935 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
936 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
937 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700938
Robert Carr05086b22020-10-13 18:22:51 -0700939 void allocateBuffers() override {
“Shadman25345d82025-03-03 16:13:39 +0000940 ATRACE_CALL();
Robert Carr05086b22020-10-13 18:22:51 -0700941 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
942 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
943 auto gbp = getIGraphicBufferProducer();
“Shadman25345d82025-03-03 16:13:39 +0000944 std::thread allocateThread([reqWidth, reqHeight, gbp = getIGraphicBufferProducer(),
945 reqFormat = mReqFormat, reqUsage = mReqUsage]() {
946 if (com_android_graphics_libgui_flags_allocate_buffer_priority()) {
947 androidSetThreadName("allocateBuffers");
948 pid_t tid = gettid();
949 androidSetThreadPriority(tid, ANDROID_PRIORITY_DISPLAY);
950 }
951
Robert Carr05086b22020-10-13 18:22:51 -0700952 gbp->allocateBuffers(reqWidth, reqHeight,
953 reqFormat, reqUsage);
“Shadman25345d82025-03-03 16:13:39 +0000954 });
955 allocateThread.detach();
Robert Carr05086b22020-10-13 18:22:51 -0700956 }
Robert Carr9c006e02020-10-14 13:41:57 -0700957
Marin Shalamanovc5986772021-03-16 16:09:49 +0100958 status_t setFrameRate(float frameRate, int8_t compatibility,
959 int8_t changeFrameRateStrategy) override {
Ady Abraham6cdd3fd2023-09-07 18:45:58 -0700960 if (flags::bq_setframerate()) {
961 return Surface::setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
962 }
963
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000964 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700965 if (mDestroyed) {
966 return DEAD_OBJECT;
967 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100968 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
969 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700970 return BAD_VALUE;
971 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100972 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700973 }
Robert Carr9b611b72020-10-19 12:00:23 -0700974
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800975 status_t setFrameTimelineInfo(uint64_t frameNumber,
976 const FrameTimelineInfo& frameTimelineInfo) override {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000977 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700978 if (mDestroyed) {
979 return DEAD_OBJECT;
980 }
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800981 return mBbq->setFrameTimelineInfo(frameNumber, frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700982 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700983
984 void destroy() override {
985 Surface::destroy();
986
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000987 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700988 mDestroyed = true;
989 mBbq = nullptr;
990 }
Robert Carr05086b22020-10-13 18:22:51 -0700991};
992
Robert Carr9c006e02020-10-14 13:41:57 -0700993// TODO: Can we coalesce this with frame updates? Need to confirm
994// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200995status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
996 bool shouldBeSeamless) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000997 std::lock_guard _lock{mMutex};
Robert Carr9c006e02020-10-14 13:41:57 -0700998 SurfaceComposerClient::Transaction t;
999
Marin Shalamanov46084422020-10-13 12:33:42 +02001000 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -07001001}
1002
Ady Abrahamd6e409e2023-01-19 16:07:31 -08001003status_t BLASTBufferQueue::setFrameTimelineInfo(uint64_t frameNumber,
1004 const FrameTimelineInfo& frameTimelineInfo) {
1005 ATRACE_FORMAT("%s(%s) frameNumber: %" PRIu64 " vsyncId: %" PRId64, __func__, mName.c_str(),
1006 frameNumber, frameTimelineInfo.vsyncId);
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001007 std::lock_guard _lock{mMutex};
Ady Abrahamd6e409e2023-01-19 16:07:31 -08001008 mPendingFrameTimelines.push({frameNumber, frameTimelineInfo});
Jorim Jaggia3fe67b2020-12-01 00:24:33 +01001009 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -07001010}
1011
Hongguang Chen621ec582021-02-16 15:42:35 -08001012void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001013 std::lock_guard _lock{mMutex};
Hongguang Chen621ec582021-02-16 15:42:35 -08001014 SurfaceComposerClient::Transaction t;
1015
1016 t.setSidebandStream(mSurfaceControl, stream).apply();
1017}
1018
Vishnu Nair992496b2020-10-22 17:27:21 -07001019sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001020 std::lock_guard _lock{mMutex};
Vishnu Nair992496b2020-10-22 17:27:21 -07001021 sp<IBinder> scHandle = nullptr;
1022 if (includeSurfaceControlHandle && mSurfaceControl) {
1023 scHandle = mSurfaceControl->getHandle();
1024 }
Anton Ivanov8ed86592025-02-20 11:52:50 -08001025 return sp<BBQSurface>::make(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -07001026}
1027
Vishnu Nairc4a40c12020-12-23 09:14:32 -08001028void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
1029 uint64_t frameNumber) {
1030 std::lock_guard _lock{mMutex};
1031 if (mLastAcquiredFrameNumber >= frameNumber) {
1032 // Apply the transaction since we have already acquired the desired frame.
Vishnu Nair7345cbb2024-12-09 20:01:47 +00001033 t->setApplyToken(mApplyToken).apply();
Vishnu Nairc4a40c12020-12-23 09:14:32 -08001034 } else {
Anton Ivanovc3130a52025-03-05 23:00:53 -08001035 mPendingTransactions.emplace_back(frameNumber, std::move(*t));
chaviwaad6cf52021-03-23 17:27:20 -05001036 // Clear the transaction so it can't be applied elsewhere.
1037 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -08001038 }
1039}
1040
chaviw6a195272021-09-03 16:14:25 -05001041void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
1042 std::lock_guard _lock{mMutex};
1043
1044 SurfaceComposerClient::Transaction t;
1045 mergePendingTransactions(&t, frameNumber);
Robert Carr79dc06a2022-02-22 15:28:59 -08001046 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
1047 t.setApplyToken(mApplyToken).apply(false, true);
chaviw6a195272021-09-03 16:14:25 -05001048}
1049
1050void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
1051 uint64_t frameNumber) {
1052 auto mergeTransaction =
Anton Ivanovc3130a52025-03-05 23:00:53 -08001053 [t, currentFrameNumber = frameNumber](
1054 std::pair<uint64_t, SurfaceComposerClient::Transaction>& pendingTransaction) {
chaviw6a195272021-09-03 16:14:25 -05001055 auto& [targetFrameNumber, transaction] = pendingTransaction;
1056 if (currentFrameNumber < targetFrameNumber) {
1057 return false;
1058 }
1059 t->merge(std::move(transaction));
1060 return true;
1061 };
1062
1063 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
1064 mPendingTransactions.end(), mergeTransaction),
1065 mPendingTransactions.end());
1066}
1067
chaviwd84085a2022-02-08 11:07:04 -06001068SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
1069 uint64_t frameNumber) {
1070 std::lock_guard _lock{mMutex};
1071 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
1072 mergePendingTransactions(t, frameNumber);
1073 return t;
1074}
1075
Vishnu Nair89496122020-12-14 17:14:53 -08001076// Maintains a single worker thread per process that services a list of runnables.
1077class AsyncWorker : public Singleton<AsyncWorker> {
1078private:
1079 std::thread mThread;
1080 bool mDone = false;
1081 std::deque<std::function<void()>> mRunnables;
1082 std::mutex mMutex;
1083 std::condition_variable mCv;
1084 void run() {
1085 std::unique_lock<std::mutex> lock(mMutex);
1086 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -08001087 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001088 std::deque<std::function<void()>> runnables = std::move(mRunnables);
1089 mRunnables.clear();
1090 lock.unlock();
1091 // Run outside the lock since the runnable might trigger another
1092 // post to the async worker.
1093 execute(runnables);
1094 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -08001095 }
Wonsik Kim567533e2021-05-04 19:31:29 -07001096 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -08001097 }
1098 }
1099
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001100 void execute(std::deque<std::function<void()>>& runnables) {
1101 while (!runnables.empty()) {
1102 std::function<void()> runnable = runnables.front();
1103 runnables.pop_front();
1104 runnable();
1105 }
1106 }
1107
Vishnu Nair89496122020-12-14 17:14:53 -08001108public:
1109 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
1110
1111 ~AsyncWorker() {
1112 mDone = true;
1113 mCv.notify_all();
1114 if (mThread.joinable()) {
1115 mThread.join();
1116 }
1117 }
1118
1119 void post(std::function<void()> runnable) {
1120 std::unique_lock<std::mutex> lock(mMutex);
1121 mRunnables.emplace_back(std::move(runnable));
1122 mCv.notify_one();
1123 }
1124};
1125ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
1126
1127// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
1128class AsyncProducerListener : public BnProducerListener {
1129private:
1130 const sp<IProducerListener> mListener;
Anton Ivanov27955ee2025-02-18 14:18:30 -08001131 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
1132 friend class sp<AsyncProducerListener>;
Vishnu Nair89496122020-12-14 17:14:53 -08001133
1134public:
Vishnu Nair89496122020-12-14 17:14:53 -08001135 void onBufferReleased() override {
1136 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
1137 }
1138
1139 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
1140 AsyncWorker::getInstance().post(
1141 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
1142 }
Sungtak Lee7c935092024-09-16 16:55:04 +00001143
1144 void onBufferDetached(int slot) override {
1145 AsyncWorker::getInstance().post(
1146 [listener = mListener, slot = slot]() { listener->onBufferDetached(slot); });
1147 }
1148
1149#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_CONSUMER_ATTACH_CALLBACK)
1150 void onBufferAttached() override {
1151 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferAttached(); });
1152 }
1153#endif
Vishnu Nair89496122020-12-14 17:14:53 -08001154};
1155
Patrick Williams078d7362024-08-27 10:20:39 -05001156#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1157class BBQBufferQueueCore : public BufferQueueCore {
1158public:
1159 explicit BBQBufferQueueCore(const wp<BLASTBufferQueue>& bbq) : mBLASTBufferQueue{bbq} {}
1160
1161 void notifyBufferReleased() const override {
1162 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1163 if (!bbq) {
1164 return;
1165 }
1166 bbq->mBufferReleaseReader->interruptBlockingRead();
1167 }
1168
1169private:
1170 wp<BLASTBufferQueue> mBLASTBufferQueue;
1171};
1172#endif
1173
Vishnu Nair89496122020-12-14 17:14:53 -08001174// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
1175// can be non-blocking when the producer is in the client process.
1176class BBQBufferQueueProducer : public BufferQueueProducer {
1177public:
Patrick Williamsca81c052024-08-15 12:38:34 -05001178 BBQBufferQueueProducer(const sp<BufferQueueCore>& core, const wp<BLASTBufferQueue>& bbq)
Brian Lindahlc794b692023-01-31 15:42:47 -07001179 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/),
Patrick Williamsca81c052024-08-15 12:38:34 -05001180 mBLASTBufferQueue(bbq) {}
Vishnu Nair89496122020-12-14 17:14:53 -08001181
1182 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
1183 QueueBufferOutput* output) override {
1184 if (!listener) {
1185 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
1186 }
1187
Anton Ivanov27955ee2025-02-18 14:18:30 -08001188 return BufferQueueProducer::connect(sp<AsyncProducerListener>::make(listener), api,
Vishnu Nair89496122020-12-14 17:14:53 -08001189 producerControlledByApp, output);
1190 }
Vishnu Nair17dde612020-12-28 11:39:59 -08001191
Brian Lindahlc794b692023-01-31 15:42:47 -07001192 // We want to resize the frame history when changing the size of the buffer queue
1193 status_t setMaxDequeuedBufferCount(int maxDequeuedBufferCount) override {
1194 int maxBufferCount;
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001195 if (status_t status = BufferQueueProducer::setMaxDequeuedBufferCount(maxDequeuedBufferCount,
1196 &maxBufferCount);
1197 status != OK) {
1198 return status;
Brian Lindahlc794b692023-01-31 15:42:47 -07001199 }
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001200
1201 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1202 if (!bbq) {
1203 return OK;
1204 }
1205
1206 // if we can't determine the max buffer count, then just skip growing the history size
1207 size_t newFrameHistorySize = maxBufferCount + 2; // +2 because triple buffer rendering
1208 // optimize away resizing the frame history unless it will grow
1209 if (newFrameHistorySize > FrameEventHistory::INITIAL_MAX_FRAME_HISTORY) {
1210 ALOGV("increasing frame history size to %zu", newFrameHistorySize);
1211 bbq->resizeFrameEventHistory(newFrameHistorySize);
1212 }
1213
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001214 return OK;
Brian Lindahlc794b692023-01-31 15:42:47 -07001215 }
1216
Vishnu Nair17dde612020-12-28 11:39:59 -08001217 int query(int what, int* value) override {
1218 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
1219 *value = 1;
Patrick Williamsf5b42de2024-08-01 16:08:51 -05001220 return OK;
Vishnu Nair17dde612020-12-28 11:39:59 -08001221 }
1222 return BufferQueueProducer::query(what, value);
1223 }
Brian Lindahlc794b692023-01-31 15:42:47 -07001224
Patrick Williams078d7362024-08-27 10:20:39 -05001225#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1226 status_t waitForBufferRelease(std::unique_lock<std::mutex>& bufferQueueLock,
1227 nsecs_t timeout) const override {
Melody Hsueee4c9c2025-01-16 16:11:14 +00001228 const auto startTime = std::chrono::steady_clock::now();
Patrick Williams078d7362024-08-27 10:20:39 -05001229 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1230 if (!bbq) {
1231 return OK;
1232 }
1233
1234 // BufferQueue has already checked if we have a free buffer. If there's an unread interrupt,
1235 // we want to ignore it. This must be done before unlocking the BufferQueue lock to ensure
1236 // we don't miss an interrupt.
1237 bbq->mBufferReleaseReader->clearInterrupts();
Patrick Williamsc16a4a52024-10-26 01:48:01 -05001238 UnlockGuard unlockGuard{bufferQueueLock};
Patrick Williams078d7362024-08-27 10:20:39 -05001239
1240 ATRACE_FORMAT("waiting for free buffer");
1241 ReleaseCallbackId id;
1242 sp<Fence> fence;
1243 uint32_t maxAcquiredBufferCount;
1244 status_t status =
1245 bbq->mBufferReleaseReader->readBlocking(id, fence, maxAcquiredBufferCount, timeout);
1246 if (status == TIMED_OUT) {
1247 return TIMED_OUT;
1248 } else if (status != OK) {
1249 // Waiting was interrupted or an error occurred. BufferQueueProducer will check if we
1250 // have a free buffer and call this method again if not.
1251 return OK;
1252 }
1253
1254 bbq->releaseBufferCallback(id, fence, maxAcquiredBufferCount);
Melody Hsueee4c9c2025-01-16 16:11:14 +00001255 const nsecs_t durationNanos = std::chrono::duration_cast<std::chrono::nanoseconds>(
1256 std::chrono::steady_clock::now() - startTime)
1257 .count();
1258 // Provide a callback for Choreographer to start buffer stuffing recovery when blocked
1259 // on buffer release.
1260 std::function<void(const nsecs_t)> callbackCopy = bbq->getWaitForBufferReleaseCallback();
1261 if (callbackCopy) callbackCopy(durationNanos);
1262
Patrick Williams078d7362024-08-27 10:20:39 -05001263 return OK;
1264 }
1265#endif
1266
Brian Lindahlc794b692023-01-31 15:42:47 -07001267private:
1268 const wp<BLASTBufferQueue> mBLASTBufferQueue;
Vishnu Nair89496122020-12-14 17:14:53 -08001269};
1270
1271// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
1272// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
1273// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
1274// we can deadlock.
1275void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
1276 sp<IGraphicBufferConsumer>* outConsumer) {
1277 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
1278 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
1279
Patrick Williams078d7362024-08-27 10:20:39 -05001280#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1281 auto core = sp<BBQBufferQueueCore>::make(this);
1282#else
1283 auto core = sp<BufferQueueCore>::make();
1284#endif
Vishnu Nair89496122020-12-14 17:14:53 -08001285 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
1286
Patrick Williams078d7362024-08-27 10:20:39 -05001287 auto producer = sp<BBQBufferQueueProducer>::make(core, this);
Vishnu Nair89496122020-12-14 17:14:53 -08001288 LOG_ALWAYS_FATAL_IF(producer == nullptr,
1289 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
1290
Patrick Williams078d7362024-08-27 10:20:39 -05001291 auto consumer = sp<BufferQueueConsumer>::make(core);
Vishnu Nair8b30dd12021-01-25 14:16:54 -08001292 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -08001293 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
1294 "BLASTBufferQueue: failed to create BufferQueueConsumer");
1295
1296 *outProducer = producer;
1297 *outConsumer = consumer;
1298}
1299
Brian Lindahlc794b692023-01-31 15:42:47 -07001300void BLASTBufferQueue::resizeFrameEventHistory(size_t newSize) {
1301 // This can be null during creation of the buffer queue, but resizing won't do anything at that
1302 // point in time, so just ignore. This can go away once the class relationships and lifetimes of
1303 // objects are cleaned up with a major refactor of BufferQueue as a whole.
1304 if (mBufferItemConsumer != nullptr) {
1305 std::unique_lock _lock{mMutex};
1306 mBufferItemConsumer->resizeFrameEventHistory(newSize);
1307 }
1308}
1309
chaviw497e81c2021-02-04 17:09:47 -08001310PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
1311 PixelFormat convertedFormat = format;
1312 switch (format) {
1313 case PIXEL_FORMAT_TRANSPARENT:
1314 case PIXEL_FORMAT_TRANSLUCENT:
1315 convertedFormat = PIXEL_FORMAT_RGBA_8888;
1316 break;
1317 case PIXEL_FORMAT_OPAQUE:
1318 convertedFormat = PIXEL_FORMAT_RGBX_8888;
1319 break;
1320 }
1321 return convertedFormat;
1322}
1323
Robert Carr82d07c92021-05-10 11:36:43 -07001324uint32_t BLASTBufferQueue::getLastTransformHint() const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001325 std::lock_guard _lock{mMutex};
Robert Carr82d07c92021-05-10 11:36:43 -07001326 if (mSurfaceControl != nullptr) {
1327 return mSurfaceControl->getTransformHint();
1328 } else {
1329 return 0;
1330 }
1331}
1332
chaviw0b020f82021-08-20 12:00:47 -05001333uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001334 std::lock_guard _lock{mMutex};
chaviw0b020f82021-08-20 12:00:47 -05001335 return mLastAcquiredFrameNumber;
1336}
1337
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001338bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001339 std::lock_guard _lock{mMutex};
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001340 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1341}
1342
Patrick Williamsf1e5df12022-10-17 21:37:42 +00001343void BLASTBufferQueue::setTransactionHangCallback(
1344 std::function<void(const std::string&)> callback) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001345 std::lock_guard _lock{mMutex};
Patrick Williams7c9fa272024-08-30 12:38:43 +00001346 mTransactionHangCallback = std::move(callback);
Robert Carr4c1b6462021-12-21 10:30:50 -08001347}
1348
Vishnu Nairaf15fab2024-07-30 08:59:26 -07001349void BLASTBufferQueue::setApplyToken(sp<IBinder> applyToken) {
1350 std::lock_guard _lock{mMutex};
1351 mApplyToken = std::move(applyToken);
1352}
1353
Melody Hsueee4c9c2025-01-16 16:11:14 +00001354void BLASTBufferQueue::setWaitForBufferReleaseCallback(
1355 std::function<void(const nsecs_t)> callback) {
Melody Hsue59a4df2024-12-10 00:31:59 +00001356 std::lock_guard _lock{mWaitForBufferReleaseMutex};
1357 mWaitForBufferReleaseCallback = std::move(callback);
1358}
1359
Melody Hsueee4c9c2025-01-16 16:11:14 +00001360std::function<void(const nsecs_t)> BLASTBufferQueue::getWaitForBufferReleaseCallback() const {
Melody Hsue59a4df2024-12-10 00:31:59 +00001361 std::lock_guard _lock{mWaitForBufferReleaseMutex};
1362 return mWaitForBufferReleaseCallback;
1363}
1364
Patrick Williams7c9fa272024-08-30 12:38:43 +00001365#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1366
Patrick Williamsa419faa2024-10-29 16:50:27 -05001367void BLASTBufferQueue::updateBufferReleaseProducer() {
1368 // SELinux policy may prevent this process from sending the BufferReleaseChannel's file
1369 // descriptor to SurfaceFlinger, causing the entire transaction to be dropped. We send this
1370 // transaction independently of any other updates to ensure those updates aren't lost.
1371 SurfaceComposerClient::Transaction t;
1372 status_t status = t.setApplyToken(mApplyToken)
1373 .setBufferReleaseChannel(mSurfaceControl, mBufferReleaseProducer)
1374 .apply(false /* synchronous */, true /* oneWay */);
1375 if (status != OK) {
1376 ALOGW("[%s] %s - failed to set buffer release channel on %s", mName.c_str(),
1377 statusToString(status).c_str(), mSurfaceControl->getName().c_str());
1378 }
1379}
1380
Patrick Williamsc16a4a52024-10-26 01:48:01 -05001381void BLASTBufferQueue::drainBufferReleaseConsumer() {
1382 ATRACE_CALL();
1383 while (true) {
1384 ReleaseCallbackId id;
1385 sp<Fence> fence;
1386 uint32_t maxAcquiredBufferCount;
1387 status_t status =
1388 mBufferReleaseConsumer->readReleaseFence(id, fence, maxAcquiredBufferCount);
1389 if (status != OK) {
1390 return;
1391 }
1392 releaseBufferCallback(id, fence, maxAcquiredBufferCount);
1393 }
1394}
1395
Patrick Williams078d7362024-08-27 10:20:39 -05001396BLASTBufferQueue::BufferReleaseReader::BufferReleaseReader(BLASTBufferQueue& bbq) : mBbq{bbq} {
1397 mEpollFd = android::base::unique_fd{epoll_create1(EPOLL_CLOEXEC)};
Patrick Williams7c9fa272024-08-30 12:38:43 +00001398 LOG_ALWAYS_FATAL_IF(!mEpollFd.ok(),
1399 "Failed to create buffer release epoll file descriptor. errno=%d "
1400 "message='%s'",
1401 errno, strerror(errno));
1402
1403 epoll_event registerEndpointFd{};
1404 registerEndpointFd.events = EPOLLIN;
Patrick Williams078d7362024-08-27 10:20:39 -05001405 registerEndpointFd.data.fd = mBbq.mBufferReleaseConsumer->getFd();
1406 status_t status = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mBbq.mBufferReleaseConsumer->getFd(),
1407 &registerEndpointFd);
Patrick Williams7c9fa272024-08-30 12:38:43 +00001408 LOG_ALWAYS_FATAL_IF(status == -1,
1409 "Failed to register buffer release consumer file descriptor with epoll. "
1410 "errno=%d message='%s'",
1411 errno, strerror(errno));
1412
1413 mEventFd = android::base::unique_fd(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK));
1414 LOG_ALWAYS_FATAL_IF(!mEventFd.ok(),
1415 "Failed to create buffer release event file descriptor. errno=%d "
1416 "message='%s'",
1417 errno, strerror(errno));
1418
1419 epoll_event registerEventFd{};
1420 registerEventFd.events = EPOLLIN;
1421 registerEventFd.data.fd = mEventFd.get();
1422 status = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mEventFd.get(), &registerEventFd);
1423 LOG_ALWAYS_FATAL_IF(status == -1,
1424 "Failed to register buffer release event file descriptor with epoll. "
1425 "errno=%d message='%s'",
1426 errno, strerror(errno));
1427}
1428
Patrick Williams7c9fa272024-08-30 12:38:43 +00001429status_t BLASTBufferQueue::BufferReleaseReader::readBlocking(ReleaseCallbackId& outId,
1430 sp<Fence>& outFence,
Patrick Williams078d7362024-08-27 10:20:39 -05001431 uint32_t& outMaxAcquiredBufferCount,
1432 nsecs_t timeout) {
1433 // TODO(b/363290953) epoll_wait only has millisecond timeout precision. If timeout is less than
1434 // 1ms, then we round timeout up to 1ms. Otherwise, we round timeout to the nearest
1435 // millisecond. Once epoll_pwait2 can be used in libgui, we can specify timeout with nanosecond
1436 // precision.
1437 int timeoutMs = -1;
1438 if (timeout == 0) {
1439 timeoutMs = 0;
1440 } else if (timeout > 0) {
1441 const int nsPerMs = 1000000;
1442 if (timeout < nsPerMs) {
1443 timeoutMs = 1;
1444 } else {
1445 timeoutMs = static_cast<int>(
1446 std::chrono::round<std::chrono::milliseconds>(std::chrono::nanoseconds{timeout})
1447 .count());
1448 }
1449 }
1450
Patrick Williams7c9fa272024-08-30 12:38:43 +00001451 epoll_event event{};
Patrick Williams078d7362024-08-27 10:20:39 -05001452 int eventCount;
1453 do {
1454 eventCount = epoll_wait(mEpollFd.get(), &event, 1 /*maxevents*/, timeoutMs);
1455 } while (eventCount == -1 && errno != EINTR);
1456
1457 if (eventCount == -1) {
1458 ALOGE("epoll_wait error while waiting for buffer release. errno=%d message='%s'", errno,
1459 strerror(errno));
1460 return UNKNOWN_ERROR;
1461 }
1462
1463 if (eventCount == 0) {
1464 return TIMED_OUT;
Patrick Williams7c9fa272024-08-30 12:38:43 +00001465 }
1466
1467 if (event.data.fd == mEventFd.get()) {
Patrick Williams078d7362024-08-27 10:20:39 -05001468 clearInterrupts();
Patrick Williams7c9fa272024-08-30 12:38:43 +00001469 return WOULD_BLOCK;
1470 }
1471
Patrick Williams078d7362024-08-27 10:20:39 -05001472 return mBbq.mBufferReleaseConsumer->readReleaseFence(outId, outFence,
1473 outMaxAcquiredBufferCount);
Patrick Williams7c9fa272024-08-30 12:38:43 +00001474}
1475
1476void BLASTBufferQueue::BufferReleaseReader::interruptBlockingRead() {
Patrick Williams078d7362024-08-27 10:20:39 -05001477 if (eventfd_write(mEventFd.get(), 1) == -1) {
Patrick Williams7c9fa272024-08-30 12:38:43 +00001478 ALOGE("failed to notify dequeue event. errno=%d message='%s'", errno, strerror(errno));
1479 }
1480}
1481
Patrick Williams078d7362024-08-27 10:20:39 -05001482void BLASTBufferQueue::BufferReleaseReader::clearInterrupts() {
1483 eventfd_t value;
1484 if (eventfd_read(mEventFd.get(), &value) == -1 && errno != EWOULDBLOCK) {
1485 ALOGE("error while reading from eventfd. errno=%d message='%s'", errno, strerror(errno));
1486 }
1487}
1488
Patrick Williams7c9fa272024-08-30 12:38:43 +00001489#endif
1490
Robert Carr78c25dd2019-08-15 14:10:33 -07001491} // namespace android