blob: 9d82c143f5df50f27ef23ee7258949081facae68 [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 Weingarten3a8f19b2022-12-27 22:00:24 +0000489status_t BLASTBufferQueue::acquireNextBufferLocked(
chaviwd7deef72021-10-06 11:53:40 -0500490 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800491 // Check if we have frames available and we have not acquired the maximum number of buffers.
492 // Even with this check, the consumer can fail to acquire an additional buffer if the consumer
493 // has already acquired (mMaxAcquiredBuffers + 1) and the new buffer is not droppable. In this
494 // case mBufferItemConsumer->acquireBuffer will return with NO_BUFFER_AVAILABLE.
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000495 if (mNumFrameAvailable == 0) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800496 BQA_LOGV("Can't acquire next buffer. No available frames");
497 return BufferQueue::NO_BUFFER_AVAILABLE;
498 }
499
500 if (mNumAcquired >= (mMaxAcquiredBuffers + 2)) {
501 BQA_LOGV("Can't acquire next buffer. Already acquired max frames %d max:%d + 2",
502 mNumAcquired, mMaxAcquiredBuffers);
503 return BufferQueue::NO_BUFFER_AVAILABLE;
Valerie Haud3b90d22019-11-06 09:37:31 -0800504 }
505
Valerie Haua32c5522019-12-09 10:11:08 -0800506 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700507 BQA_LOGE("ERROR : surface control is null");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000508 return NAME_NOT_FOUND;
Valerie Haud3b90d22019-11-06 09:37:31 -0800509 }
510
Robert Carr78c25dd2019-08-15 14:10:33 -0700511 SurfaceComposerClient::Transaction localTransaction;
512 bool applyTransaction = true;
513 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500514 if (transaction) {
515 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700516 applyTransaction = false;
517 }
518
Valerie Haua32c5522019-12-09 10:11:08 -0800519 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800520
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800521 status_t status =
522 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800523 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
524 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000525 return status;
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800526 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700527 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000528 return status;
Robert Carr78c25dd2019-08-15 14:10:33 -0700529 }
chaviw57ae4b22022-02-03 16:51:39 -0600530
Valerie Haua32c5522019-12-09 10:11:08 -0800531 auto buffer = bufferItem.mGraphicBuffer;
532 mNumFrameAvailable--;
chaviw57ae4b22022-02-03 16:51:39 -0600533 BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800534
535 if (buffer == nullptr) {
536 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700537 BQA_LOGE("Buffer was empty");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000538 return BAD_VALUE;
Valerie Haua32c5522019-12-09 10:11:08 -0800539 }
540
Vishnu Nair670b3f72020-09-29 17:52:18 -0700541 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700542 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800543 "buffer{size=%dx%d transform=%d}",
544 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
545 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
546 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000547 return acquireNextBufferLocked(transaction);
Vishnu Nair670b3f72020-09-29 17:52:18 -0700548 }
549
Valerie Haua32c5522019-12-09 10:11:08 -0800550 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700551 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
552 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
553 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700554
Valerie Hau871d6352020-01-29 08:44:02 -0800555 bool needsDisconnect = false;
556 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
557
558 // if producer disconnected before, notify SurfaceFlinger
559 if (needsDisconnect) {
560 t->notifyProducerDisconnect(mSurfaceControl);
561 }
562
Robert Carr78c25dd2019-08-15 14:10:33 -0700563 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
564 incStrong((void*)transactionCallbackThunk);
565
Vishnu Nair932f6ae2021-09-29 17:33:10 -0700566 mSize = mRequestedSize;
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700567 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000568 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
569 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700570 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800571
Vishnu Nair1506b182021-02-22 14:35:15 -0800572 auto releaseBufferCallback =
573 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
chaviw69058fb2021-09-27 09:37:30 -0500574 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
chaviwba4320c2021-09-15 15:20:53 -0500575 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
liulijuneb489f62022-10-17 22:02:14 +0800576 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, mProducerId,
577 releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500578 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
579 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
580 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700581 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviwf2dace72021-11-17 17:36:50 -0600582
chaviw42026162021-04-16 15:46:12 -0500583 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700584
Vishnu Naird2aaab12022-02-10 14:49:09 -0800585 if (mUpdateDestinationFrame) {
586 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
587 } else {
588 const bool ignoreDestinationFrame =
589 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
590 t->setFlags(mSurfaceControl,
591 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
592 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700593 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700594 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800595 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800596 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800597 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800598 if (!bufferItem.mIsAutoTimestamp) {
599 t->setDesiredPresentTime(bufferItem.mTimestamp);
600 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700601
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800602 // Drop stale frame timeline infos
603 while (!mPendingFrameTimelines.empty() &&
604 mPendingFrameTimelines.front().first < bufferItem.mFrameNumber) {
605 ATRACE_FORMAT_INSTANT("dropping stale frameNumber: %" PRIu64 " vsyncId: %" PRId64,
606 mPendingFrameTimelines.front().first,
607 mPendingFrameTimelines.front().second.vsyncId);
608 mPendingFrameTimelines.pop();
609 }
610
611 if (!mPendingFrameTimelines.empty() &&
612 mPendingFrameTimelines.front().first == bufferItem.mFrameNumber) {
613 ATRACE_FORMAT_INSTANT("Transaction::setFrameTimelineInfo frameNumber: %" PRIu64
614 " vsyncId: %" PRId64,
615 bufferItem.mFrameNumber,
616 mPendingFrameTimelines.front().second.vsyncId);
617 t->setFrameTimelineInfo(mPendingFrameTimelines.front().second);
618 mPendingFrameTimelines.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100619 }
620
Vishnu Nairadf632b2021-01-07 14:05:08 -0800621 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000622 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800623 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
624 if (dequeueTime != mDequeueTimestamps.end()) {
625 Parcel p;
626 p.writeInt64(dequeueTime->second);
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800627 t->setMetadata(mSurfaceControl, gui::METADATA_DEQUEUE_TIME, p);
Vishnu Nairadf632b2021-01-07 14:05:08 -0800628 mDequeueTimestamps.erase(dequeueTime);
629 }
630 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800631
chaviw6a195272021-09-03 16:14:25 -0500632 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700633 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800634 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
635 t->setApplyToken(mApplyToken).apply(false, true);
636 mAppliedLastTransaction = true;
637 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
638 } else {
639 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
640 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700641 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700642
chaviwd7deef72021-10-06 11:53:40 -0500643 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800644 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700645 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500646 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800647 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700648 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700649 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000650 return OK;
Robert Carr78c25dd2019-08-15 14:10:33 -0700651}
652
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800653Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
654 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800655 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800656 }
657 return item.mCrop;
658}
659
chaviwd7deef72021-10-06 11:53:40 -0500660void BLASTBufferQueue::acquireAndReleaseBuffer() {
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000661 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500662 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500663 status_t status =
664 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
665 if (status != OK) {
666 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
667 statusToString(status).c_str());
668 return;
669 }
chaviwd7deef72021-10-06 11:53:40 -0500670 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500671 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500672}
673
Vishnu Nairaef1de92020-10-22 12:15:53 -0700674void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000675 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
676 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
chaviwc1cf4022022-06-03 13:32:33 -0500677
Tianhao Yao4861b102022-02-03 20:18:35 +0000678 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000679 UNIQUE_LOCK_WITH_ASSERTION(mMutex);
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000680 BBQ_TRACE();
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000681 bool waitForTransactionCallback = !mSyncedFrameNumbers.empty();
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800682
Tianhao Yao4861b102022-02-03 20:18:35 +0000683 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
684 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800685
Tianhao Yao4861b102022-02-03 20:18:35 +0000686 if (syncTransactionSet) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000687 // If we are going to re-use the same mSyncTransaction, release the buffer that may
688 // already be set in the Transaction. This is to allow us a free slot early to continue
689 // processing a new buffer.
690 if (!mAcquireSingleBuffer) {
691 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
692 if (bufferData) {
693 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
694 bufferData->frameNumber);
695 releaseBuffer(bufferData->generateReleaseCallbackId(),
696 bufferData->acquireFence);
Tianhao Yao4861b102022-02-03 20:18:35 +0000697 }
698 }
chaviw0acd33a2021-11-02 11:55:37 -0500699
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000700 if (waitForTransactionCallback) {
701 // We are waiting on a previous sync's transaction callback so allow another sync
702 // transaction to proceed.
703 //
704 // We need to first flush out the transactions that were in between the two syncs.
705 // We do this by merging them into mSyncTransaction so any buffer merging will get
706 // a release callback invoked.
707 while (mNumFrameAvailable > 0) {
708 // flush out the shadow queue
709 acquireAndReleaseBuffer();
710 }
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800711 } else {
712 // Make sure the frame available count is 0 before proceeding with a sync to ensure
713 // the correct frame is used for the sync. The only way mNumFrameAvailable would be
714 // greater than 0 is if we already ran out of buffers previously. This means we
715 // need to flush the buffers before proceeding with the sync.
716 while (mNumFrameAvailable > 0) {
717 BQA_LOGD("waiting until no queued buffers");
718 mCallbackCV.wait(_lock);
719 }
chaviwd7deef72021-10-06 11:53:40 -0500720 }
721 }
722
Tianhao Yao4861b102022-02-03 20:18:35 +0000723 // add to shadow queue
724 mNumFrameAvailable++;
chaviwc1cf4022022-06-03 13:32:33 -0500725 if (waitForTransactionCallback && mNumFrameAvailable >= 2) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000726 acquireAndReleaseBuffer();
727 }
728 ATRACE_INT(mQueuedBufferTrace.c_str(),
729 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
730
731 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
732 item.mFrameNumber, boolToString(syncTransactionSet));
733
734 if (syncTransactionSet) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800735 // Add to mSyncedFrameNumbers before waiting in case any buffers are released
736 // while waiting for a free buffer. The release and commit callback will try to
737 // acquire buffers if there are any available, but we don't want it to acquire
738 // in the case where a sync transaction wants the buffer.
739 mSyncedFrameNumbers.emplace(item.mFrameNumber);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000740 // If there's no available buffer and we're in a sync transaction, we need to wait
741 // instead of returning since we guarantee a buffer will be acquired for the sync.
742 while (acquireNextBufferLocked(mSyncTransaction) == BufferQueue::NO_BUFFER_AVAILABLE) {
743 BQA_LOGD("waiting for available buffer");
744 mCallbackCV.wait(_lock);
745 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000746
747 // Only need a commit callback when syncing to ensure the buffer that's synced has been
748 // sent to SF
749 incStrong((void*)transactionCommittedCallbackThunk);
750 mSyncTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,
751 static_cast<void*>(this));
Tianhao Yao4861b102022-02-03 20:18:35 +0000752 if (mAcquireSingleBuffer) {
753 prevCallback = mTransactionReadyCallback;
754 prevTransaction = mSyncTransaction;
755 mTransactionReadyCallback = nullptr;
756 mSyncTransaction = nullptr;
757 }
chaviwc1cf4022022-06-03 13:32:33 -0500758 } else if (!waitForTransactionCallback) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000759 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800760 }
761 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000762 if (prevCallback) {
763 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500764 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800765}
766
Vishnu Nairaef1de92020-10-22 12:15:53 -0700767void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
768 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
769 // Do nothing since we are not storing unacquired buffer items locally.
770}
771
Vishnu Nairadf632b2021-01-07 14:05:08 -0800772void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000773 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800774 mDequeueTimestamps[bufferId] = systemTime();
775};
776
777void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000778 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800779 mDequeueTimestamps.erase(bufferId);
780};
781
Tianhao Yao4861b102022-02-03 20:18:35 +0000782void BLASTBufferQueue::syncNextTransaction(
783 std::function<void(SurfaceComposerClient::Transaction*)> callback,
784 bool acquireSingleBuffer) {
chaviw3b4bdcf2022-03-17 09:27:03 -0500785 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
786 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
787
788 {
789 std::lock_guard _lock{mMutex};
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000790 BBQ_TRACE();
chaviw3b4bdcf2022-03-17 09:27:03 -0500791 // We're about to overwrite the previous call so we should invoke that callback
792 // immediately.
793 if (mTransactionReadyCallback) {
794 prevCallback = mTransactionReadyCallback;
795 prevTransaction = mSyncTransaction;
796 }
797
798 mTransactionReadyCallback = callback;
799 if (callback) {
800 mSyncTransaction = new SurfaceComposerClient::Transaction();
801 } else {
802 mSyncTransaction = nullptr;
803 }
804 mAcquireSingleBuffer = mTransactionReadyCallback ? acquireSingleBuffer : true;
Tianhao Yao4861b102022-02-03 20:18:35 +0000805 }
chaviw3b4bdcf2022-03-17 09:27:03 -0500806
807 if (prevCallback) {
808 prevCallback(prevTransaction);
809 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000810}
811
812void BLASTBufferQueue::stopContinuousSyncTransaction() {
813 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
814 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
815 {
816 std::lock_guard _lock{mMutex};
817 bool invokeCallback = mTransactionReadyCallback && !mAcquireSingleBuffer;
818 if (invokeCallback) {
819 prevCallback = mTransactionReadyCallback;
820 prevTransaction = mSyncTransaction;
821 }
822 mTransactionReadyCallback = nullptr;
823 mSyncTransaction = nullptr;
824 mAcquireSingleBuffer = true;
825 }
826 if (prevCallback) {
827 prevCallback(prevTransaction);
828 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700829}
830
Vishnu Nairea0de002020-11-17 17:42:37 -0800831bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700832 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
833 // Only reject buffers if scaling mode is freeze.
834 return false;
835 }
836
Vishnu Naire1a42322020-10-02 17:42:04 -0700837 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
838 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
839
840 // Take the buffer's orientation into account
841 if (item.mTransform & ui::Transform::ROT_90) {
842 std::swap(bufWidth, bufHeight);
843 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800844 ui::Size bufferSize(bufWidth, bufHeight);
845 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800846 return false;
847 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700848
Vishnu Nair670b3f72020-09-29 17:52:18 -0700849 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800850 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700851}
Vishnu Nairbf255772020-10-16 10:54:41 -0700852
Robert Carr05086b22020-10-13 18:22:51 -0700853class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700854private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700855 std::mutex mMutex;
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000856 sp<BLASTBufferQueue> mBbq GUARDED_BY(mMutex);
857 bool mDestroyed GUARDED_BY(mMutex) = false;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700858
Robert Carr05086b22020-10-13 18:22:51 -0700859public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700860 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
861 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
862 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700863
Robert Carr05086b22020-10-13 18:22:51 -0700864 void allocateBuffers() override {
865 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
866 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
867 auto gbp = getIGraphicBufferProducer();
868 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
869 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
870 gbp->allocateBuffers(reqWidth, reqHeight,
871 reqFormat, reqUsage);
872
873 }).detach();
874 }
Robert Carr9c006e02020-10-14 13:41:57 -0700875
Marin Shalamanovc5986772021-03-16 16:09:49 +0100876 status_t setFrameRate(float frameRate, int8_t compatibility,
877 int8_t changeFrameRateStrategy) override {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000878 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700879 if (mDestroyed) {
880 return DEAD_OBJECT;
881 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100882 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
883 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700884 return BAD_VALUE;
885 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100886 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700887 }
Robert Carr9b611b72020-10-19 12:00:23 -0700888
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800889 status_t setFrameTimelineInfo(uint64_t frameNumber,
890 const FrameTimelineInfo& frameTimelineInfo) override {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000891 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700892 if (mDestroyed) {
893 return DEAD_OBJECT;
894 }
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800895 return mBbq->setFrameTimelineInfo(frameNumber, frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700896 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700897
898 void destroy() override {
899 Surface::destroy();
900
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000901 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700902 mDestroyed = true;
903 mBbq = nullptr;
904 }
Robert Carr05086b22020-10-13 18:22:51 -0700905};
906
Robert Carr9c006e02020-10-14 13:41:57 -0700907// TODO: Can we coalesce this with frame updates? Need to confirm
908// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200909status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
910 bool shouldBeSeamless) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000911 std::lock_guard _lock{mMutex};
Robert Carr9c006e02020-10-14 13:41:57 -0700912 SurfaceComposerClient::Transaction t;
913
Marin Shalamanov46084422020-10-13 12:33:42 +0200914 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700915}
916
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800917status_t BLASTBufferQueue::setFrameTimelineInfo(uint64_t frameNumber,
918 const FrameTimelineInfo& frameTimelineInfo) {
919 ATRACE_FORMAT("%s(%s) frameNumber: %" PRIu64 " vsyncId: %" PRId64, __func__, mName.c_str(),
920 frameNumber, frameTimelineInfo.vsyncId);
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000921 std::lock_guard _lock{mMutex};
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800922 mPendingFrameTimelines.push({frameNumber, frameTimelineInfo});
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100923 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700924}
925
Hongguang Chen621ec582021-02-16 15:42:35 -0800926void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000927 std::lock_guard _lock{mMutex};
Hongguang Chen621ec582021-02-16 15:42:35 -0800928 SurfaceComposerClient::Transaction t;
929
930 t.setSidebandStream(mSurfaceControl, stream).apply();
931}
932
Vishnu Nair992496b2020-10-22 17:27:21 -0700933sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000934 std::lock_guard _lock{mMutex};
Vishnu Nair992496b2020-10-22 17:27:21 -0700935 sp<IBinder> scHandle = nullptr;
936 if (includeSurfaceControlHandle && mSurfaceControl) {
937 scHandle = mSurfaceControl->getHandle();
938 }
939 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700940}
941
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800942void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
943 uint64_t frameNumber) {
944 std::lock_guard _lock{mMutex};
945 if (mLastAcquiredFrameNumber >= frameNumber) {
946 // Apply the transaction since we have already acquired the desired frame.
947 t->apply();
948 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500949 mPendingTransactions.emplace_back(frameNumber, *t);
950 // Clear the transaction so it can't be applied elsewhere.
951 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800952 }
953}
954
chaviw6a195272021-09-03 16:14:25 -0500955void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
956 std::lock_guard _lock{mMutex};
957
958 SurfaceComposerClient::Transaction t;
959 mergePendingTransactions(&t, frameNumber);
Robert Carr79dc06a2022-02-22 15:28:59 -0800960 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
961 t.setApplyToken(mApplyToken).apply(false, true);
chaviw6a195272021-09-03 16:14:25 -0500962}
963
964void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
965 uint64_t frameNumber) {
966 auto mergeTransaction =
967 [&t, currentFrameNumber = frameNumber](
968 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
969 auto& [targetFrameNumber, transaction] = pendingTransaction;
970 if (currentFrameNumber < targetFrameNumber) {
971 return false;
972 }
973 t->merge(std::move(transaction));
974 return true;
975 };
976
977 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
978 mPendingTransactions.end(), mergeTransaction),
979 mPendingTransactions.end());
980}
981
chaviwd84085a2022-02-08 11:07:04 -0600982SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
983 uint64_t frameNumber) {
984 std::lock_guard _lock{mMutex};
985 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
986 mergePendingTransactions(t, frameNumber);
987 return t;
988}
989
Vishnu Nair89496122020-12-14 17:14:53 -0800990// Maintains a single worker thread per process that services a list of runnables.
991class AsyncWorker : public Singleton<AsyncWorker> {
992private:
993 std::thread mThread;
994 bool mDone = false;
995 std::deque<std::function<void()>> mRunnables;
996 std::mutex mMutex;
997 std::condition_variable mCv;
998 void run() {
999 std::unique_lock<std::mutex> lock(mMutex);
1000 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -08001001 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001002 std::deque<std::function<void()>> runnables = std::move(mRunnables);
1003 mRunnables.clear();
1004 lock.unlock();
1005 // Run outside the lock since the runnable might trigger another
1006 // post to the async worker.
1007 execute(runnables);
1008 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -08001009 }
Wonsik Kim567533e2021-05-04 19:31:29 -07001010 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -08001011 }
1012 }
1013
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001014 void execute(std::deque<std::function<void()>>& runnables) {
1015 while (!runnables.empty()) {
1016 std::function<void()> runnable = runnables.front();
1017 runnables.pop_front();
1018 runnable();
1019 }
1020 }
1021
Vishnu Nair89496122020-12-14 17:14:53 -08001022public:
1023 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
1024
1025 ~AsyncWorker() {
1026 mDone = true;
1027 mCv.notify_all();
1028 if (mThread.joinable()) {
1029 mThread.join();
1030 }
1031 }
1032
1033 void post(std::function<void()> runnable) {
1034 std::unique_lock<std::mutex> lock(mMutex);
1035 mRunnables.emplace_back(std::move(runnable));
1036 mCv.notify_one();
1037 }
1038};
1039ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
1040
1041// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
1042class AsyncProducerListener : public BnProducerListener {
1043private:
1044 const sp<IProducerListener> mListener;
1045
1046public:
1047 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
1048
1049 void onBufferReleased() override {
1050 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
1051 }
1052
1053 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
1054 AsyncWorker::getInstance().post(
1055 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
1056 }
1057};
1058
1059// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
1060// can be non-blocking when the producer is in the client process.
1061class BBQBufferQueueProducer : public BufferQueueProducer {
1062public:
1063 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
1064 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
1065
1066 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
1067 QueueBufferOutput* output) override {
1068 if (!listener) {
1069 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
1070 }
1071
1072 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
1073 producerControlledByApp, output);
1074 }
Vishnu Nair17dde612020-12-28 11:39:59 -08001075
1076 int query(int what, int* value) override {
1077 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
1078 *value = 1;
1079 return NO_ERROR;
1080 }
1081 return BufferQueueProducer::query(what, value);
1082 }
Vishnu Nair89496122020-12-14 17:14:53 -08001083};
1084
1085// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
1086// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
1087// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
1088// we can deadlock.
1089void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
1090 sp<IGraphicBufferConsumer>* outConsumer) {
1091 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
1092 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
1093
1094 sp<BufferQueueCore> core(new BufferQueueCore());
1095 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
1096
1097 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
1098 LOG_ALWAYS_FATAL_IF(producer == nullptr,
1099 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
1100
Vishnu Nair8b30dd12021-01-25 14:16:54 -08001101 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
1102 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -08001103 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
1104 "BLASTBufferQueue: failed to create BufferQueueConsumer");
1105
1106 *outProducer = producer;
1107 *outConsumer = consumer;
1108}
1109
chaviw497e81c2021-02-04 17:09:47 -08001110PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
1111 PixelFormat convertedFormat = format;
1112 switch (format) {
1113 case PIXEL_FORMAT_TRANSPARENT:
1114 case PIXEL_FORMAT_TRANSLUCENT:
1115 convertedFormat = PIXEL_FORMAT_RGBA_8888;
1116 break;
1117 case PIXEL_FORMAT_OPAQUE:
1118 convertedFormat = PIXEL_FORMAT_RGBX_8888;
1119 break;
1120 }
1121 return convertedFormat;
1122}
1123
Robert Carr82d07c92021-05-10 11:36:43 -07001124uint32_t BLASTBufferQueue::getLastTransformHint() const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001125 std::lock_guard _lock{mMutex};
Robert Carr82d07c92021-05-10 11:36:43 -07001126 if (mSurfaceControl != nullptr) {
1127 return mSurfaceControl->getTransformHint();
1128 } else {
1129 return 0;
1130 }
1131}
1132
chaviw0b020f82021-08-20 12:00:47 -05001133uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001134 std::lock_guard _lock{mMutex};
chaviw0b020f82021-08-20 12:00:47 -05001135 return mLastAcquiredFrameNumber;
1136}
1137
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001138bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001139 std::lock_guard _lock{mMutex};
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001140 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1141}
1142
Patrick Williamsf1e5df12022-10-17 21:37:42 +00001143void BLASTBufferQueue::setTransactionHangCallback(
1144 std::function<void(const std::string&)> callback) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001145 std::lock_guard _lock{mMutex};
Robert Carr4c1b6462021-12-21 10:30:50 -08001146 mTransactionHangCallback = callback;
1147}
1148
Robert Carr78c25dd2019-08-15 14:10:33 -07001149} // namespace android