blob: cf8b13ffa4e327bf13af8fefd2021ee61c3cfd14 [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
liulijuneb489f62022-10-17 22:02:14 +080023#include <cutils/atomic.h>
Robert Carr78c25dd2019-08-15 14:10:33 -070024#include <gui/BLASTBufferQueue.h>
25#include <gui/BufferItemConsumer.h>
Vishnu Nair89496122020-12-14 17:14:53 -080026#include <gui/BufferQueueConsumer.h>
27#include <gui/BufferQueueCore.h>
28#include <gui/BufferQueueProducer.h>
Valerie Hau45e4b3b2019-12-03 10:49:17 -080029#include <gui/GLConsumer.h>
Vishnu Nair89496122020-12-14 17:14:53 -080030#include <gui/IProducerListener.h>
Robert Carr05086b22020-10-13 18:22:51 -070031#include <gui/Surface.h>
chaviw57ae4b22022-02-03 16:51:39 -060032#include <gui/TraceUtils.h>
Vishnu Nair89496122020-12-14 17:14:53 -080033#include <utils/Singleton.h>
Valerie Haua32c5522019-12-09 10:11:08 -080034#include <utils/Trace.h>
35
Ady Abraham0bde6b52021-05-18 13:57:02 -070036#include <private/gui/ComposerService.h>
Huihong Luo02186fb2022-02-23 14:21:54 -080037#include <private/gui/ComposerServiceAIDL.h>
Ady Abraham0bde6b52021-05-18 13:57:02 -070038
Chavi Weingartene0237bb2023-02-06 21:48:32 +000039#include <android-base/thread_annotations.h>
Robert Carr78c25dd2019-08-15 14:10:33 -070040#include <chrono>
41
42using namespace std::chrono_literals;
43
Vishnu Nairdab94092020-09-29 16:09:04 -070044namespace {
chaviw3277faf2021-05-19 16:45:23 -050045inline const char* boolToString(bool b) {
Vishnu Nairdab94092020-09-29 16:09:04 -070046 return b ? "true" : "false";
47}
48} // namespace
49
Robert Carr78c25dd2019-08-15 14:10:33 -070050namespace android {
51
Vishnu Nairdab94092020-09-29 16:09:04 -070052// Macros to include adapter info in log messages
chaviwd7deef72021-10-06 11:53:40 -050053#define BQA_LOGD(x, ...) \
54 ALOGD("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070055#define BQA_LOGV(x, ...) \
56 ALOGV("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairc6f89ee2020-12-11 14:27:32 -080057// enable logs for a single layer
58//#define BQA_LOGV(x, ...) \
59// ALOGV_IF((strstr(mName.c_str(), "SurfaceView") != nullptr), "[%s](f:%u,a:%u) " x, \
60// mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070061#define BQA_LOGE(x, ...) \
62 ALOGE("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
63
chaviw57ae4b22022-02-03 16:51:39 -060064#define BBQ_TRACE(x, ...) \
65 ATRACE_FORMAT("%s - %s(f:%u,a:%u)" x, __FUNCTION__, mName.c_str(), mNumFrameAvailable, \
66 mNumAcquired, ##__VA_ARGS__)
67
Chavi Weingartene0237bb2023-02-06 21:48:32 +000068#define UNIQUE_LOCK_WITH_ASSERTION(mutex) \
69 std::unique_lock _lock{mutex}; \
70 base::ScopedLockAssertion assumeLocked(mutex);
71
Valerie Hau871d6352020-01-29 08:44:02 -080072void BLASTBufferItemConsumer::onDisconnect() {
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000073 Mutex::Autolock lock(mMutex);
74 mPreviouslyConnected = mCurrentlyConnected;
75 mCurrentlyConnected = false;
76 if (mPreviouslyConnected) {
77 mDisconnectEvents.push(mCurrentFrameNumber);
Valerie Hau871d6352020-01-29 08:44:02 -080078 }
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000079 mFrameEventHistory.onDisconnect();
Valerie Hau871d6352020-01-29 08:44:02 -080080}
81
82void BLASTBufferItemConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
83 FrameEventHistoryDelta* outDelta) {
Hongguang Chen621ec582021-02-16 15:42:35 -080084 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080085 if (newTimestamps) {
86 // BufferQueueProducer only adds a new timestamp on
87 // queueBuffer
88 mCurrentFrameNumber = newTimestamps->frameNumber;
89 mFrameEventHistory.addQueue(*newTimestamps);
90 }
91 if (outDelta) {
92 // frame event histories will be processed
93 // only after the producer connects and requests
94 // deltas for the first time. Forward this intent
95 // to SF-side to turn event processing back on
96 mPreviouslyConnected = mCurrentlyConnected;
97 mCurrentlyConnected = true;
98 mFrameEventHistory.getAndResetDelta(outDelta);
99 }
100}
101
102void BLASTBufferItemConsumer::updateFrameTimestamps(uint64_t frameNumber, nsecs_t refreshStartTime,
103 const sp<Fence>& glDoneFence,
104 const sp<Fence>& presentFence,
105 const sp<Fence>& prevReleaseFence,
106 CompositorTiming compositorTiming,
107 nsecs_t latchTime, nsecs_t dequeueReadyTime) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800108 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800109
110 // if the producer is not connected, don't bother updating,
111 // the next producer that connects won't access this frame event
112 if (!mCurrentlyConnected) return;
113 std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
114 std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
115 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
116
117 mFrameEventHistory.addLatch(frameNumber, latchTime);
118 mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
119 mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
120 mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
121 compositorTiming);
122}
123
124void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
125 bool disconnect = false;
Hongguang Chen621ec582021-02-16 15:42:35 -0800126 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800127 while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
128 disconnect = true;
129 mDisconnectEvents.pop();
130 }
131 if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
132}
133
Hongguang Chen621ec582021-02-16 15:42:35 -0800134void BLASTBufferItemConsumer::onSidebandStreamChanged() {
Ady Abrahamdbca1352021-12-15 11:58:56 -0800135 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
136 if (bbq != nullptr) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800137 sp<NativeHandle> stream = getSidebandStream();
Ady Abrahamdbca1352021-12-15 11:58:56 -0800138 bbq->setSidebandStream(stream);
Hongguang Chen621ec582021-02-16 15:42:35 -0800139 }
140}
141
Vishnu Naird2aaab12022-02-10 14:49:09 -0800142BLASTBufferQueue::BLASTBufferQueue(const std::string& name, bool updateDestinationFrame)
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800143 : mSurfaceControl(nullptr),
144 mSize(1, 1),
Vishnu Nairea0de002020-11-17 17:42:37 -0800145 mRequestedSize(mSize),
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800146 mFormat(PIXEL_FORMAT_RGBA_8888),
Tianhao Yao4861b102022-02-03 20:18:35 +0000147 mTransactionReadyCallback(nullptr),
Vishnu Naird2aaab12022-02-10 14:49:09 -0800148 mSyncTransaction(nullptr),
149 mUpdateDestinationFrame(updateDestinationFrame) {
Vishnu Nair89496122020-12-14 17:14:53 -0800150 createBufferQueue(&mProducer, &mConsumer);
Valerie Hau0889c622020-02-19 15:04:47 -0800151 // since the adapter is in the client process, set dequeue timeout
152 // explicitly so that dequeueBuffer will block
153 mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
Valerie Hau65b8e872020-02-13 09:45:14 -0800154
Vishnu Nairdebd1cb2021-03-16 10:06:01 -0700155 // safe default, most producers are expected to override this
156 mProducer->setMaxDequeuedBufferCount(2);
Vishnu Nair1618c672021-02-05 13:08:26 -0800157 mBufferItemConsumer = new BLASTBufferItemConsumer(mConsumer,
158 GraphicBuffer::USAGE_HW_COMPOSER |
159 GraphicBuffer::USAGE_HW_TEXTURE,
Ady Abrahamdbca1352021-12-15 11:58:56 -0800160 1, false, this);
liulijuneb489f62022-10-17 22:02:14 +0800161 static std::atomic<uint32_t> nextId = 0;
162 mProducerId = nextId++;
163 mName = name + "#" + std::to_string(mProducerId);
164 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(mProducerId);
165 mQueuedBufferTrace = "QueuedBuffer - " + mName + "BLAST#" + std::to_string(mProducerId);
Vishnu Nairdab94092020-09-29 16:09:04 -0700166 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700167 mBufferItemConsumer->setFrameAvailableListener(this);
Robert Carr9f133d72020-04-01 15:51:46 -0700168
Huihong Luo02186fb2022-02-23 14:21:54 -0800169 ComposerServiceAIDL::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);
Ady Abraham0bde6b52021-05-18 13:57:02 -0700170 mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
chaviw69058fb2021-09-27 09:37:30 -0500171 mCurrentMaxAcquiredBufferCount = mMaxAcquiredBuffers;
Valerie Haua32c5522019-12-09 10:11:08 -0800172 mNumAcquired = 0;
173 mNumFrameAvailable = 0;
Robert Carr4c1b6462021-12-21 10:30:50 -0800174
175 TransactionCompletedListener::getInstance()->addQueueStallListener(
Patrick Williamsf1e5df12022-10-17 21:37:42 +0000176 [&](const std::string& reason) {
177 std::function<void(const std::string&)> callbackCopy;
178 {
179 std::unique_lock _lock{mMutex};
180 callbackCopy = mTransactionHangCallback;
181 }
182 if (callbackCopy) callbackCopy(reason);
183 },
184 this);
Robert Carr4c1b6462021-12-21 10:30:50 -0800185
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800186 BQA_LOGV("BLASTBufferQueue created");
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800187}
188
189BLASTBufferQueue::BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface,
190 int width, int height, int32_t format)
191 : BLASTBufferQueue(name) {
192 update(surface, width, height, format);
Robert Carr78c25dd2019-08-15 14:10:33 -0700193}
194
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800195BLASTBufferQueue::~BLASTBufferQueue() {
Robert Carr4c1b6462021-12-21 10:30:50 -0800196 TransactionCompletedListener::getInstance()->removeQueueStallListener(this);
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800197 if (mPendingTransactions.empty()) {
198 return;
199 }
200 BQA_LOGE("Applying pending transactions on dtor %d",
201 static_cast<uint32_t>(mPendingTransactions.size()));
202 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800203 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
Robert Carr79dc06a2022-02-22 15:28:59 -0800204 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
205 t.setApplyToken(mApplyToken).apply(false, true);
chaviw3b4bdcf2022-03-17 09:27:03 -0500206
207 if (mTransactionReadyCallback) {
208 mTransactionReadyCallback(mSyncTransaction);
209 }
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800210}
211
chaviw565ee542021-01-14 10:21:23 -0800212void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Naird2aaab12022-02-10 14:49:09 -0800213 int32_t format) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800214 LOG_ALWAYS_FATAL_IF(surface == nullptr, "BLASTBufferQueue: mSurfaceControl must not be NULL");
215
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000216 std::lock_guard _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800217 if (mFormat != format) {
218 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800219 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800220 }
221
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800222 const bool surfaceControlChanged = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairab066512022-01-04 22:28:00 +0000223 if (surfaceControlChanged && mSurfaceControl != nullptr) {
224 BQA_LOGD("Updating SurfaceControl without recreating BBQ");
225 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800226 bool applyTransaction = false;
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800227
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700228 // Always update the native object even though they might have the same layer handle, so we can
229 // get the updated transform hint from WM.
230 mSurfaceControl = surface;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800231 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800232 if (surfaceControlChanged) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800233 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
234 layer_state_t::eEnableBackpressure);
235 applyTransaction = true;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800236 }
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800237 mTransformHint = mSurfaceControl->getTransformHint();
238 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700239 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
240 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800241
Vishnu Nairea0de002020-11-17 17:42:37 -0800242 ui::Size newSize(width, height);
243 if (mRequestedSize != newSize) {
244 mRequestedSize.set(newSize);
245 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000246 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800247 // If the buffer supports scaling, update the frame immediately since the client may
248 // want to scale the existing buffer to the new size.
249 mSize = mRequestedSize;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800250 if (mUpdateDestinationFrame) {
251 t.setDestinationFrame(mSurfaceControl, Rect(newSize));
252 applyTransaction = true;
253 }
Vishnu Nair53c936c2020-12-03 11:46:37 -0800254 }
Robert Carrfc416512020-04-02 12:32:44 -0700255 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800256 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800257 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
258 t.setApplyToken(mApplyToken).apply(false, true);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800259 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700260}
261
chaviwd7deef72021-10-06 11:53:40 -0500262static std::optional<SurfaceControlStats> findMatchingStat(
263 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
264 for (auto stat : stats) {
265 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
266 return stat;
267 }
268 }
269 return std::nullopt;
270}
271
272static void transactionCommittedCallbackThunk(void* context, nsecs_t latchTime,
273 const sp<Fence>& presentFence,
274 const std::vector<SurfaceControlStats>& stats) {
275 if (context == nullptr) {
276 return;
277 }
278 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
279 bq->transactionCommittedCallback(latchTime, presentFence, stats);
280}
281
282void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
283 const sp<Fence>& /*presentFence*/,
284 const std::vector<SurfaceControlStats>& stats) {
285 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000286 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600287 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500288 BQA_LOGV("transactionCommittedCallback");
289 if (!mSurfaceControlsWithPendingCallback.empty()) {
290 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
291 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
292 if (stat) {
293 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
294
295 // We need to check if we were waiting for a transaction callback in order to
296 // process any pending buffers and unblock. It's possible to get transaction
chaviwc1cf4022022-06-03 13:32:33 -0500297 // callbacks for previous requests so we need to ensure that there are no pending
298 // frame numbers that were in a sync. We remove the frame from mSyncedFrameNumbers
299 // set and then check if it's empty. If there are no more pending syncs, we can
300 // proceed with flushing the shadow queue.
301 // We also want to check if mSyncTransaction is null because it's possible another
chaviwd7deef72021-10-06 11:53:40 -0500302 // sync request came in while waiting, but it hasn't started processing yet. In that
303 // case, we don't actually want to flush the frames in between since they will get
304 // processed and merged with the sync transaction and released earlier than if they
305 // were sent to SF
chaviwc1cf4022022-06-03 13:32:33 -0500306 mSyncedFrameNumbers.erase(currFrameNumber);
307 if (mSyncedFrameNumbers.empty() && mSyncTransaction == nullptr) {
chaviwd7deef72021-10-06 11:53:40 -0500308 flushShadowQueue();
309 }
310 } else {
chaviw768bfa02021-11-01 09:50:57 -0500311 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviwd7deef72021-10-06 11:53:40 -0500312 }
313 } else {
314 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
315 "empty.");
316 }
chaviwd7deef72021-10-06 11:53:40 -0500317 decStrong((void*)transactionCommittedCallbackThunk);
318 }
319}
320
Robert Carr78c25dd2019-08-15 14:10:33 -0700321static void transactionCallbackThunk(void* context, nsecs_t latchTime,
322 const sp<Fence>& presentFence,
323 const std::vector<SurfaceControlStats>& stats) {
324 if (context == nullptr) {
325 return;
326 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800327 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700328 bq->transactionCallback(latchTime, presentFence, stats);
329}
330
331void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
332 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700333 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000334 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600335 BBQ_TRACE();
chaviw71c2cc42020-10-23 16:42:02 -0700336 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700337
chaviw42026162021-04-16 15:46:12 -0500338 if (!mSurfaceControlsWithPendingCallback.empty()) {
339 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
340 mSurfaceControlsWithPendingCallback.pop();
chaviwd7deef72021-10-06 11:53:40 -0500341 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
342 if (statsOptional) {
343 SurfaceControlStats stat = *statsOptional;
Vishnu Nair71fcf912022-10-18 09:14:20 -0700344 if (stat.transformHint) {
345 mTransformHint = *stat.transformHint;
346 mBufferItemConsumer->setTransformHint(mTransformHint);
347 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
348 }
Vishnu Nairde66dc72021-06-17 17:54:41 -0700349 // Update frametime stamps if the frame was latched and presented, indicated by a
350 // valid latch time.
351 if (stat.latchTime > 0) {
352 mBufferItemConsumer
353 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
354 stat.frameEventStats.refreshStartTime,
355 stat.frameEventStats.gpuCompositionDoneFence,
356 stat.presentFence, stat.previousReleaseFence,
357 stat.frameEventStats.compositorTiming,
358 stat.latchTime,
359 stat.frameEventStats.dequeueReadyTime);
360 }
Robert Carr405e2f62021-12-31 16:59:34 -0800361 auto currFrameNumber = stat.frameEventStats.frameNumber;
362 std::vector<ReleaseCallbackId> staleReleases;
363 for (const auto& [key, value]: mSubmitted) {
364 if (currFrameNumber > key.framenumber) {
365 staleReleases.push_back(key);
366 }
367 }
368 for (const auto& staleRelease : staleReleases) {
Robert Carr405e2f62021-12-31 16:59:34 -0800369 releaseBufferCallbackLocked(staleRelease,
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700370 stat.previousReleaseFence
371 ? stat.previousReleaseFence
372 : Fence::NO_FENCE,
373 stat.currentMaxAcquiredBufferCount,
374 true /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800375 }
chaviwd7deef72021-10-06 11:53:40 -0500376 } else {
chaviw768bfa02021-11-01 09:50:57 -0500377 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500378 }
379 } else {
380 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
381 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800382 }
chaviw71c2cc42020-10-23 16:42:02 -0700383
chaviw71c2cc42020-10-23 16:42:02 -0700384 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700385 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700386}
387
Vishnu Nair1506b182021-02-22 14:35:15 -0800388// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
389// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
390// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
391// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700392static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
chaviw69058fb2021-09-27 09:37:30 -0500393 const sp<Fence>& releaseFence,
394 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800395 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800396 if (blastBufferQueue) {
chaviw69058fb2021-09-27 09:37:30 -0500397 blastBufferQueue->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700398 } else {
399 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800400 }
401}
402
chaviwd7deef72021-10-06 11:53:40 -0500403void BLASTBufferQueue::flushShadowQueue() {
404 BQA_LOGV("flushShadowQueue");
405 int numFramesToFlush = mNumFrameAvailable;
406 while (numFramesToFlush > 0) {
407 acquireNextBufferLocked(std::nullopt);
408 numFramesToFlush--;
409 }
410}
411
chaviw69058fb2021-09-27 09:37:30 -0500412void BLASTBufferQueue::releaseBufferCallback(
413 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
414 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000415 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600416 BBQ_TRACE();
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700417 releaseBufferCallbackLocked(id, releaseFence, currentMaxAcquiredBufferCount,
418 false /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800419}
420
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700421void BLASTBufferQueue::releaseBufferCallbackLocked(
422 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
423 std::optional<uint32_t> currentMaxAcquiredBufferCount, bool fakeRelease) {
Robert Carr405e2f62021-12-31 16:59:34 -0800424 ATRACE_CALL();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700425 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800426
Ady Abraham899dcdb2021-06-15 16:56:21 -0700427 // Calculate how many buffers we need to hold before we release them back
428 // to the buffer queue. This will prevent higher latency when we are running
429 // on a lower refresh rate than the max supported. We only do that for EGL
430 // clients as others don't care about latency
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000431 const auto it = mSubmitted.find(id);
432 const bool isEGL = it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
Ady Abraham899dcdb2021-06-15 16:56:21 -0700433
chaviw69058fb2021-09-27 09:37:30 -0500434 if (currentMaxAcquiredBufferCount) {
435 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
436 }
437
liulijunf90df632022-11-14 14:24:48 +0800438 const uint32_t numPendingBuffersToHold =
439 isEGL ? std::max(0, mMaxAcquiredBuffers - (int32_t)mCurrentMaxAcquiredBufferCount) : 0;
Robert Carr405e2f62021-12-31 16:59:34 -0800440
441 auto rb = ReleasedBuffer{id, releaseFence};
442 if (std::find(mPendingRelease.begin(), mPendingRelease.end(), rb) == mPendingRelease.end()) {
443 mPendingRelease.emplace_back(rb);
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700444 if (fakeRelease) {
445 BQA_LOGE("Faking releaseBufferCallback from transactionCompleteCallback %" PRIu64,
446 id.framenumber);
447 BBQ_TRACE("FakeReleaseCallback");
448 }
Robert Carr405e2f62021-12-31 16:59:34 -0800449 }
Ady Abraham899dcdb2021-06-15 16:56:21 -0700450
451 // Release all buffers that are beyond the ones that we need to hold
452 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500453 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700454 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500455 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwc1cf4022022-06-03 13:32:33 -0500456 // Don't process the transactions here if mSyncedFrameNumbers is not empty. That means
457 // are still transactions that have sync buffers in them that have not been applied or
458 // dropped. Instead, let onFrameAvailable handle processing them since it will merge with
459 // the syncTransaction.
460 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500461 acquireNextBufferLocked(std::nullopt);
462 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800463 }
464
Ady Abraham899dcdb2021-06-15 16:56:21 -0700465 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700466 ATRACE_INT(mQueuedBufferTrace.c_str(),
467 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800468 mCallbackCV.notify_all();
469}
470
chaviw0acd33a2021-11-02 11:55:37 -0500471void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
472 const sp<Fence>& releaseFence) {
473 auto it = mSubmitted.find(callbackId);
474 if (it == mSubmitted.end()) {
475 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
476 callbackId.to_string().c_str());
477 return;
478 }
479 mNumAcquired--;
chaviw57ae4b22022-02-03 16:51:39 -0600480 BBQ_TRACE("frame=%" PRIu64, callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500481 BQA_LOGV("released %s", callbackId.to_string().c_str());
482 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
483 mSubmitted.erase(it);
chaviwc1cf4022022-06-03 13:32:33 -0500484 // Remove the frame number from mSyncedFrameNumbers since we can get a release callback
485 // without getting a transaction committed if the buffer was dropped.
486 mSyncedFrameNumbers.erase(callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500487}
488
Chavi Weingarten70670e62023-02-22 17:36:40 +0000489static ui::Size getBufferSize(const BufferItem& item) {
490 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
491 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
492
493 // Take the buffer's orientation into account
494 if (item.mTransform & ui::Transform::ROT_90) {
495 std::swap(bufWidth, bufHeight);
496 }
497 return ui::Size(bufWidth, bufHeight);
498}
499
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000500status_t BLASTBufferQueue::acquireNextBufferLocked(
chaviwd7deef72021-10-06 11:53:40 -0500501 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800502 // Check if we have frames available and we have not acquired the maximum number of buffers.
503 // Even with this check, the consumer can fail to acquire an additional buffer if the consumer
504 // has already acquired (mMaxAcquiredBuffers + 1) and the new buffer is not droppable. In this
505 // case mBufferItemConsumer->acquireBuffer will return with NO_BUFFER_AVAILABLE.
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000506 if (mNumFrameAvailable == 0) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800507 BQA_LOGV("Can't acquire next buffer. No available frames");
508 return BufferQueue::NO_BUFFER_AVAILABLE;
509 }
510
511 if (mNumAcquired >= (mMaxAcquiredBuffers + 2)) {
512 BQA_LOGV("Can't acquire next buffer. Already acquired max frames %d max:%d + 2",
513 mNumAcquired, mMaxAcquiredBuffers);
514 return BufferQueue::NO_BUFFER_AVAILABLE;
Valerie Haud3b90d22019-11-06 09:37:31 -0800515 }
516
Valerie Haua32c5522019-12-09 10:11:08 -0800517 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700518 BQA_LOGE("ERROR : surface control is null");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000519 return NAME_NOT_FOUND;
Valerie Haud3b90d22019-11-06 09:37:31 -0800520 }
521
Robert Carr78c25dd2019-08-15 14:10:33 -0700522 SurfaceComposerClient::Transaction localTransaction;
523 bool applyTransaction = true;
524 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500525 if (transaction) {
526 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700527 applyTransaction = false;
528 }
529
Valerie Haua32c5522019-12-09 10:11:08 -0800530 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800531
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800532 status_t status =
533 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800534 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
535 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000536 return status;
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800537 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700538 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000539 return status;
Robert Carr78c25dd2019-08-15 14:10:33 -0700540 }
chaviw57ae4b22022-02-03 16:51:39 -0600541
Valerie Haua32c5522019-12-09 10:11:08 -0800542 auto buffer = bufferItem.mGraphicBuffer;
543 mNumFrameAvailable--;
chaviw57ae4b22022-02-03 16:51:39 -0600544 BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800545
546 if (buffer == nullptr) {
547 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700548 BQA_LOGE("Buffer was empty");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000549 return BAD_VALUE;
Valerie Haua32c5522019-12-09 10:11:08 -0800550 }
551
Vishnu Nair670b3f72020-09-29 17:52:18 -0700552 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700553 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800554 "buffer{size=%dx%d transform=%d}",
555 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
556 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
557 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000558 return acquireNextBufferLocked(transaction);
Vishnu Nair670b3f72020-09-29 17:52:18 -0700559 }
560
Valerie Haua32c5522019-12-09 10:11:08 -0800561 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700562 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
563 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
564 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700565
Valerie Hau871d6352020-01-29 08:44:02 -0800566 bool needsDisconnect = false;
567 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
568
569 // if producer disconnected before, notify SurfaceFlinger
570 if (needsDisconnect) {
571 t->notifyProducerDisconnect(mSurfaceControl);
572 }
573
Robert Carr78c25dd2019-08-15 14:10:33 -0700574 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
575 incStrong((void*)transactionCallbackThunk);
576
Chavi Weingarten70670e62023-02-22 17:36:40 +0000577 // Only update mSize for destination bounds if the incoming buffer matches the requested size.
578 // Otherwise, it could cause stretching since the destination bounds will update before the
579 // buffer with the new size is acquired.
580 if (mRequestedSize == getBufferSize(bufferItem)) {
581 mSize = mRequestedSize;
582 }
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700583 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000584 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
585 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700586 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800587
Vishnu Nair1506b182021-02-22 14:35:15 -0800588 auto releaseBufferCallback =
589 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
chaviw69058fb2021-09-27 09:37:30 -0500590 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
chaviwba4320c2021-09-15 15:20:53 -0500591 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
liulijuneb489f62022-10-17 22:02:14 +0800592 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, mProducerId,
593 releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500594 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
595 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
596 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700597 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviwf2dace72021-11-17 17:36:50 -0600598
chaviw42026162021-04-16 15:46:12 -0500599 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700600
Vishnu Naird2aaab12022-02-10 14:49:09 -0800601 if (mUpdateDestinationFrame) {
602 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
603 } else {
604 const bool ignoreDestinationFrame =
605 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
606 t->setFlags(mSurfaceControl,
607 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
608 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700609 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700610 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800611 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800612 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800613 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800614 if (!bufferItem.mIsAutoTimestamp) {
615 t->setDesiredPresentTime(bufferItem.mTimestamp);
616 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700617
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800618 // Drop stale frame timeline infos
619 while (!mPendingFrameTimelines.empty() &&
620 mPendingFrameTimelines.front().first < bufferItem.mFrameNumber) {
621 ATRACE_FORMAT_INSTANT("dropping stale frameNumber: %" PRIu64 " vsyncId: %" PRId64,
622 mPendingFrameTimelines.front().first,
623 mPendingFrameTimelines.front().second.vsyncId);
624 mPendingFrameTimelines.pop();
625 }
626
627 if (!mPendingFrameTimelines.empty() &&
628 mPendingFrameTimelines.front().first == bufferItem.mFrameNumber) {
629 ATRACE_FORMAT_INSTANT("Transaction::setFrameTimelineInfo frameNumber: %" PRIu64
630 " vsyncId: %" PRId64,
631 bufferItem.mFrameNumber,
632 mPendingFrameTimelines.front().second.vsyncId);
633 t->setFrameTimelineInfo(mPendingFrameTimelines.front().second);
634 mPendingFrameTimelines.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100635 }
636
Vishnu Nairadf632b2021-01-07 14:05:08 -0800637 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000638 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800639 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
640 if (dequeueTime != mDequeueTimestamps.end()) {
641 Parcel p;
642 p.writeInt64(dequeueTime->second);
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800643 t->setMetadata(mSurfaceControl, gui::METADATA_DEQUEUE_TIME, p);
Vishnu Nairadf632b2021-01-07 14:05:08 -0800644 mDequeueTimestamps.erase(dequeueTime);
645 }
646 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800647
chaviw6a195272021-09-03 16:14:25 -0500648 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700649 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800650 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
651 t->setApplyToken(mApplyToken).apply(false, true);
652 mAppliedLastTransaction = true;
653 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
654 } else {
655 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
656 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700657 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700658
chaviwd7deef72021-10-06 11:53:40 -0500659 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800660 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700661 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500662 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800663 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700664 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700665 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000666 return OK;
Robert Carr78c25dd2019-08-15 14:10:33 -0700667}
668
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800669Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
670 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800671 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800672 }
673 return item.mCrop;
674}
675
chaviwd7deef72021-10-06 11:53:40 -0500676void BLASTBufferQueue::acquireAndReleaseBuffer() {
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000677 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500678 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500679 status_t status =
680 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
681 if (status != OK) {
682 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
683 statusToString(status).c_str());
684 return;
685 }
chaviwd7deef72021-10-06 11:53:40 -0500686 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500687 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500688}
689
Vishnu Nairaef1de92020-10-22 12:15:53 -0700690void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000691 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
692 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
chaviwc1cf4022022-06-03 13:32:33 -0500693
Tianhao Yao4861b102022-02-03 20:18:35 +0000694 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000695 UNIQUE_LOCK_WITH_ASSERTION(mMutex);
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000696 BBQ_TRACE();
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000697 bool waitForTransactionCallback = !mSyncedFrameNumbers.empty();
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800698
Tianhao Yao4861b102022-02-03 20:18:35 +0000699 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
700 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800701
Tianhao Yao4861b102022-02-03 20:18:35 +0000702 if (syncTransactionSet) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000703 // If we are going to re-use the same mSyncTransaction, release the buffer that may
704 // already be set in the Transaction. This is to allow us a free slot early to continue
705 // processing a new buffer.
706 if (!mAcquireSingleBuffer) {
707 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
708 if (bufferData) {
709 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
710 bufferData->frameNumber);
711 releaseBuffer(bufferData->generateReleaseCallbackId(),
712 bufferData->acquireFence);
Tianhao Yao4861b102022-02-03 20:18:35 +0000713 }
714 }
chaviw0acd33a2021-11-02 11:55:37 -0500715
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000716 if (waitForTransactionCallback) {
717 // We are waiting on a previous sync's transaction callback so allow another sync
718 // transaction to proceed.
719 //
720 // We need to first flush out the transactions that were in between the two syncs.
721 // We do this by merging them into mSyncTransaction so any buffer merging will get
722 // a release callback invoked.
723 while (mNumFrameAvailable > 0) {
724 // flush out the shadow queue
725 acquireAndReleaseBuffer();
726 }
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800727 } else {
728 // Make sure the frame available count is 0 before proceeding with a sync to ensure
729 // the correct frame is used for the sync. The only way mNumFrameAvailable would be
730 // greater than 0 is if we already ran out of buffers previously. This means we
731 // need to flush the buffers before proceeding with the sync.
732 while (mNumFrameAvailable > 0) {
733 BQA_LOGD("waiting until no queued buffers");
734 mCallbackCV.wait(_lock);
735 }
chaviwd7deef72021-10-06 11:53:40 -0500736 }
737 }
738
Tianhao Yao4861b102022-02-03 20:18:35 +0000739 // add to shadow queue
740 mNumFrameAvailable++;
chaviwc1cf4022022-06-03 13:32:33 -0500741 if (waitForTransactionCallback && mNumFrameAvailable >= 2) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000742 acquireAndReleaseBuffer();
743 }
744 ATRACE_INT(mQueuedBufferTrace.c_str(),
745 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
746
747 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
748 item.mFrameNumber, boolToString(syncTransactionSet));
749
750 if (syncTransactionSet) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800751 // Add to mSyncedFrameNumbers before waiting in case any buffers are released
752 // while waiting for a free buffer. The release and commit callback will try to
753 // acquire buffers if there are any available, but we don't want it to acquire
754 // in the case where a sync transaction wants the buffer.
755 mSyncedFrameNumbers.emplace(item.mFrameNumber);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000756 // If there's no available buffer and we're in a sync transaction, we need to wait
757 // instead of returning since we guarantee a buffer will be acquired for the sync.
758 while (acquireNextBufferLocked(mSyncTransaction) == BufferQueue::NO_BUFFER_AVAILABLE) {
759 BQA_LOGD("waiting for available buffer");
760 mCallbackCV.wait(_lock);
761 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000762
763 // Only need a commit callback when syncing to ensure the buffer that's synced has been
764 // sent to SF
765 incStrong((void*)transactionCommittedCallbackThunk);
766 mSyncTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,
767 static_cast<void*>(this));
Tianhao Yao4861b102022-02-03 20:18:35 +0000768 if (mAcquireSingleBuffer) {
769 prevCallback = mTransactionReadyCallback;
770 prevTransaction = mSyncTransaction;
771 mTransactionReadyCallback = nullptr;
772 mSyncTransaction = nullptr;
773 }
chaviwc1cf4022022-06-03 13:32:33 -0500774 } else if (!waitForTransactionCallback) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000775 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800776 }
777 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000778 if (prevCallback) {
779 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500780 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800781}
782
Vishnu Nairaef1de92020-10-22 12:15:53 -0700783void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
784 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
785 // Do nothing since we are not storing unacquired buffer items locally.
786}
787
Vishnu Nairadf632b2021-01-07 14:05:08 -0800788void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000789 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800790 mDequeueTimestamps[bufferId] = systemTime();
791};
792
793void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000794 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800795 mDequeueTimestamps.erase(bufferId);
796};
797
Tianhao Yao4861b102022-02-03 20:18:35 +0000798void BLASTBufferQueue::syncNextTransaction(
799 std::function<void(SurfaceComposerClient::Transaction*)> callback,
800 bool acquireSingleBuffer) {
chaviw3b4bdcf2022-03-17 09:27:03 -0500801 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
802 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
803
804 {
805 std::lock_guard _lock{mMutex};
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000806 BBQ_TRACE();
chaviw3b4bdcf2022-03-17 09:27:03 -0500807 // We're about to overwrite the previous call so we should invoke that callback
808 // immediately.
809 if (mTransactionReadyCallback) {
810 prevCallback = mTransactionReadyCallback;
811 prevTransaction = mSyncTransaction;
812 }
813
814 mTransactionReadyCallback = callback;
815 if (callback) {
816 mSyncTransaction = new SurfaceComposerClient::Transaction();
817 } else {
818 mSyncTransaction = nullptr;
819 }
820 mAcquireSingleBuffer = mTransactionReadyCallback ? acquireSingleBuffer : true;
Tianhao Yao4861b102022-02-03 20:18:35 +0000821 }
chaviw3b4bdcf2022-03-17 09:27:03 -0500822
823 if (prevCallback) {
824 prevCallback(prevTransaction);
825 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000826}
827
828void BLASTBufferQueue::stopContinuousSyncTransaction() {
829 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
830 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
831 {
832 std::lock_guard _lock{mMutex};
833 bool invokeCallback = mTransactionReadyCallback && !mAcquireSingleBuffer;
834 if (invokeCallback) {
835 prevCallback = mTransactionReadyCallback;
836 prevTransaction = mSyncTransaction;
837 }
838 mTransactionReadyCallback = nullptr;
839 mSyncTransaction = nullptr;
840 mAcquireSingleBuffer = true;
841 }
842 if (prevCallback) {
843 prevCallback(prevTransaction);
844 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700845}
846
Vishnu Nairea0de002020-11-17 17:42:37 -0800847bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700848 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
849 // Only reject buffers if scaling mode is freeze.
850 return false;
851 }
852
Chavi Weingarten70670e62023-02-22 17:36:40 +0000853 ui::Size bufferSize = getBufferSize(item);
Vishnu Nairea0de002020-11-17 17:42:37 -0800854 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800855 return false;
856 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700857
Vishnu Nair670b3f72020-09-29 17:52:18 -0700858 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800859 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700860}
Vishnu Nairbf255772020-10-16 10:54:41 -0700861
Robert Carr05086b22020-10-13 18:22:51 -0700862class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700863private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700864 std::mutex mMutex;
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000865 sp<BLASTBufferQueue> mBbq GUARDED_BY(mMutex);
866 bool mDestroyed GUARDED_BY(mMutex) = false;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700867
Robert Carr05086b22020-10-13 18:22:51 -0700868public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700869 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
870 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
871 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700872
Robert Carr05086b22020-10-13 18:22:51 -0700873 void allocateBuffers() override {
874 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
875 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
876 auto gbp = getIGraphicBufferProducer();
877 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
878 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
879 gbp->allocateBuffers(reqWidth, reqHeight,
880 reqFormat, reqUsage);
881
882 }).detach();
883 }
Robert Carr9c006e02020-10-14 13:41:57 -0700884
Marin Shalamanovc5986772021-03-16 16:09:49 +0100885 status_t setFrameRate(float frameRate, int8_t compatibility,
886 int8_t changeFrameRateStrategy) override {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000887 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700888 if (mDestroyed) {
889 return DEAD_OBJECT;
890 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100891 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
892 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700893 return BAD_VALUE;
894 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100895 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700896 }
Robert Carr9b611b72020-10-19 12:00:23 -0700897
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800898 status_t setFrameTimelineInfo(uint64_t frameNumber,
899 const FrameTimelineInfo& frameTimelineInfo) override {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000900 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700901 if (mDestroyed) {
902 return DEAD_OBJECT;
903 }
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800904 return mBbq->setFrameTimelineInfo(frameNumber, frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700905 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700906
907 void destroy() override {
908 Surface::destroy();
909
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000910 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700911 mDestroyed = true;
912 mBbq = nullptr;
913 }
Robert Carr05086b22020-10-13 18:22:51 -0700914};
915
Robert Carr9c006e02020-10-14 13:41:57 -0700916// TODO: Can we coalesce this with frame updates? Need to confirm
917// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200918status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
919 bool shouldBeSeamless) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000920 std::lock_guard _lock{mMutex};
Robert Carr9c006e02020-10-14 13:41:57 -0700921 SurfaceComposerClient::Transaction t;
922
Marin Shalamanov46084422020-10-13 12:33:42 +0200923 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700924}
925
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800926status_t BLASTBufferQueue::setFrameTimelineInfo(uint64_t frameNumber,
927 const FrameTimelineInfo& frameTimelineInfo) {
928 ATRACE_FORMAT("%s(%s) frameNumber: %" PRIu64 " vsyncId: %" PRId64, __func__, mName.c_str(),
929 frameNumber, frameTimelineInfo.vsyncId);
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000930 std::lock_guard _lock{mMutex};
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800931 mPendingFrameTimelines.push({frameNumber, frameTimelineInfo});
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100932 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700933}
934
Hongguang Chen621ec582021-02-16 15:42:35 -0800935void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000936 std::lock_guard _lock{mMutex};
Hongguang Chen621ec582021-02-16 15:42:35 -0800937 SurfaceComposerClient::Transaction t;
938
939 t.setSidebandStream(mSurfaceControl, stream).apply();
940}
941
Vishnu Nair992496b2020-10-22 17:27:21 -0700942sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000943 std::lock_guard _lock{mMutex};
Vishnu Nair992496b2020-10-22 17:27:21 -0700944 sp<IBinder> scHandle = nullptr;
945 if (includeSurfaceControlHandle && mSurfaceControl) {
946 scHandle = mSurfaceControl->getHandle();
947 }
948 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700949}
950
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800951void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
952 uint64_t frameNumber) {
953 std::lock_guard _lock{mMutex};
954 if (mLastAcquiredFrameNumber >= frameNumber) {
955 // Apply the transaction since we have already acquired the desired frame.
956 t->apply();
957 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500958 mPendingTransactions.emplace_back(frameNumber, *t);
959 // Clear the transaction so it can't be applied elsewhere.
960 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800961 }
962}
963
chaviw6a195272021-09-03 16:14:25 -0500964void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
965 std::lock_guard _lock{mMutex};
966
967 SurfaceComposerClient::Transaction t;
968 mergePendingTransactions(&t, frameNumber);
Robert Carr79dc06a2022-02-22 15:28:59 -0800969 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
970 t.setApplyToken(mApplyToken).apply(false, true);
chaviw6a195272021-09-03 16:14:25 -0500971}
972
973void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
974 uint64_t frameNumber) {
975 auto mergeTransaction =
976 [&t, currentFrameNumber = frameNumber](
977 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
978 auto& [targetFrameNumber, transaction] = pendingTransaction;
979 if (currentFrameNumber < targetFrameNumber) {
980 return false;
981 }
982 t->merge(std::move(transaction));
983 return true;
984 };
985
986 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
987 mPendingTransactions.end(), mergeTransaction),
988 mPendingTransactions.end());
989}
990
chaviwd84085a2022-02-08 11:07:04 -0600991SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
992 uint64_t frameNumber) {
993 std::lock_guard _lock{mMutex};
994 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
995 mergePendingTransactions(t, frameNumber);
996 return t;
997}
998
Vishnu Nair89496122020-12-14 17:14:53 -0800999// Maintains a single worker thread per process that services a list of runnables.
1000class AsyncWorker : public Singleton<AsyncWorker> {
1001private:
1002 std::thread mThread;
1003 bool mDone = false;
1004 std::deque<std::function<void()>> mRunnables;
1005 std::mutex mMutex;
1006 std::condition_variable mCv;
1007 void run() {
1008 std::unique_lock<std::mutex> lock(mMutex);
1009 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -08001010 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001011 std::deque<std::function<void()>> runnables = std::move(mRunnables);
1012 mRunnables.clear();
1013 lock.unlock();
1014 // Run outside the lock since the runnable might trigger another
1015 // post to the async worker.
1016 execute(runnables);
1017 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -08001018 }
Wonsik Kim567533e2021-05-04 19:31:29 -07001019 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -08001020 }
1021 }
1022
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001023 void execute(std::deque<std::function<void()>>& runnables) {
1024 while (!runnables.empty()) {
1025 std::function<void()> runnable = runnables.front();
1026 runnables.pop_front();
1027 runnable();
1028 }
1029 }
1030
Vishnu Nair89496122020-12-14 17:14:53 -08001031public:
1032 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
1033
1034 ~AsyncWorker() {
1035 mDone = true;
1036 mCv.notify_all();
1037 if (mThread.joinable()) {
1038 mThread.join();
1039 }
1040 }
1041
1042 void post(std::function<void()> runnable) {
1043 std::unique_lock<std::mutex> lock(mMutex);
1044 mRunnables.emplace_back(std::move(runnable));
1045 mCv.notify_one();
1046 }
1047};
1048ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
1049
1050// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
1051class AsyncProducerListener : public BnProducerListener {
1052private:
1053 const sp<IProducerListener> mListener;
1054
1055public:
1056 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
1057
1058 void onBufferReleased() override {
1059 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
1060 }
1061
1062 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
1063 AsyncWorker::getInstance().post(
1064 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
1065 }
1066};
1067
1068// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
1069// can be non-blocking when the producer is in the client process.
1070class BBQBufferQueueProducer : public BufferQueueProducer {
1071public:
1072 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
1073 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
1074
1075 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
1076 QueueBufferOutput* output) override {
1077 if (!listener) {
1078 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
1079 }
1080
1081 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
1082 producerControlledByApp, output);
1083 }
Vishnu Nair17dde612020-12-28 11:39:59 -08001084
1085 int query(int what, int* value) override {
1086 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
1087 *value = 1;
1088 return NO_ERROR;
1089 }
1090 return BufferQueueProducer::query(what, value);
1091 }
Vishnu Nair89496122020-12-14 17:14:53 -08001092};
1093
1094// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
1095// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
1096// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
1097// we can deadlock.
1098void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
1099 sp<IGraphicBufferConsumer>* outConsumer) {
1100 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
1101 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
1102
1103 sp<BufferQueueCore> core(new BufferQueueCore());
1104 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
1105
1106 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
1107 LOG_ALWAYS_FATAL_IF(producer == nullptr,
1108 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
1109
Vishnu Nair8b30dd12021-01-25 14:16:54 -08001110 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
1111 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -08001112 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
1113 "BLASTBufferQueue: failed to create BufferQueueConsumer");
1114
1115 *outProducer = producer;
1116 *outConsumer = consumer;
1117}
1118
chaviw497e81c2021-02-04 17:09:47 -08001119PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
1120 PixelFormat convertedFormat = format;
1121 switch (format) {
1122 case PIXEL_FORMAT_TRANSPARENT:
1123 case PIXEL_FORMAT_TRANSLUCENT:
1124 convertedFormat = PIXEL_FORMAT_RGBA_8888;
1125 break;
1126 case PIXEL_FORMAT_OPAQUE:
1127 convertedFormat = PIXEL_FORMAT_RGBX_8888;
1128 break;
1129 }
1130 return convertedFormat;
1131}
1132
Robert Carr82d07c92021-05-10 11:36:43 -07001133uint32_t BLASTBufferQueue::getLastTransformHint() const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001134 std::lock_guard _lock{mMutex};
Robert Carr82d07c92021-05-10 11:36:43 -07001135 if (mSurfaceControl != nullptr) {
1136 return mSurfaceControl->getTransformHint();
1137 } else {
1138 return 0;
1139 }
1140}
1141
chaviw0b020f82021-08-20 12:00:47 -05001142uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001143 std::lock_guard _lock{mMutex};
chaviw0b020f82021-08-20 12:00:47 -05001144 return mLastAcquiredFrameNumber;
1145}
1146
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001147bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001148 std::lock_guard _lock{mMutex};
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001149 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1150}
1151
Patrick Williamsf1e5df12022-10-17 21:37:42 +00001152void BLASTBufferQueue::setTransactionHangCallback(
1153 std::function<void(const std::string&)> callback) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001154 std::lock_guard _lock{mMutex};
Robert Carr4c1b6462021-12-21 10:30:50 -08001155 mTransactionHangCallback = callback;
1156}
1157
Robert Carr78c25dd2019-08-15 14:10:33 -07001158} // namespace android