blob: 66c0041965ff68f081dc53700f5974c6f13e237e [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
Robert Carr78c25dd2019-08-15 14:10:33 -070023#include <gui/BLASTBufferQueue.h>
24#include <gui/BufferItemConsumer.h>
Vishnu Nair89496122020-12-14 17:14:53 -080025#include <gui/BufferQueueConsumer.h>
26#include <gui/BufferQueueCore.h>
27#include <gui/BufferQueueProducer.h>
Valerie Hau45e4b3b2019-12-03 10:49:17 -080028#include <gui/GLConsumer.h>
Vishnu Nair89496122020-12-14 17:14:53 -080029#include <gui/IProducerListener.h>
Robert Carr05086b22020-10-13 18:22:51 -070030#include <gui/Surface.h>
chaviw57ae4b22022-02-03 16:51:39 -060031#include <gui/TraceUtils.h>
Vishnu Nair89496122020-12-14 17:14:53 -080032#include <utils/Singleton.h>
Valerie Haua32c5522019-12-09 10:11:08 -080033#include <utils/Trace.h>
34
Ady Abraham0bde6b52021-05-18 13:57:02 -070035#include <private/gui/ComposerService.h>
Huihong Luo02186fb2022-02-23 14:21:54 -080036#include <private/gui/ComposerServiceAIDL.h>
Ady Abraham0bde6b52021-05-18 13:57:02 -070037
Chavi Weingartene0237bb2023-02-06 21:48:32 +000038#include <android-base/thread_annotations.h>
Robert Carr78c25dd2019-08-15 14:10:33 -070039#include <chrono>
40
41using namespace std::chrono_literals;
42
Vishnu Nairdab94092020-09-29 16:09:04 -070043namespace {
chaviw3277faf2021-05-19 16:45:23 -050044inline const char* boolToString(bool b) {
Vishnu Nairdab94092020-09-29 16:09:04 -070045 return b ? "true" : "false";
46}
47} // namespace
48
Robert Carr78c25dd2019-08-15 14:10:33 -070049namespace android {
50
Vishnu Nairdab94092020-09-29 16:09:04 -070051// Macros to include adapter info in log messages
chaviwd7deef72021-10-06 11:53:40 -050052#define BQA_LOGD(x, ...) \
53 ALOGD("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070054#define BQA_LOGV(x, ...) \
55 ALOGV("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairc6f89ee2020-12-11 14:27:32 -080056// enable logs for a single layer
57//#define BQA_LOGV(x, ...) \
58// ALOGV_IF((strstr(mName.c_str(), "SurfaceView") != nullptr), "[%s](f:%u,a:%u) " x, \
59// mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070060#define BQA_LOGE(x, ...) \
61 ALOGE("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
62
chaviw57ae4b22022-02-03 16:51:39 -060063#define BBQ_TRACE(x, ...) \
64 ATRACE_FORMAT("%s - %s(f:%u,a:%u)" x, __FUNCTION__, mName.c_str(), mNumFrameAvailable, \
65 mNumAcquired, ##__VA_ARGS__)
66
Chavi Weingartene0237bb2023-02-06 21:48:32 +000067#define UNIQUE_LOCK_WITH_ASSERTION(mutex) \
68 std::unique_lock _lock{mutex}; \
69 base::ScopedLockAssertion assumeLocked(mutex);
70
Valerie Hau871d6352020-01-29 08:44:02 -080071void BLASTBufferItemConsumer::onDisconnect() {
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000072 Mutex::Autolock lock(mMutex);
73 mPreviouslyConnected = mCurrentlyConnected;
74 mCurrentlyConnected = false;
75 if (mPreviouslyConnected) {
76 mDisconnectEvents.push(mCurrentFrameNumber);
Valerie Hau871d6352020-01-29 08:44:02 -080077 }
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000078 mFrameEventHistory.onDisconnect();
Valerie Hau871d6352020-01-29 08:44:02 -080079}
80
81void BLASTBufferItemConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
82 FrameEventHistoryDelta* outDelta) {
Hongguang Chen621ec582021-02-16 15:42:35 -080083 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080084 if (newTimestamps) {
85 // BufferQueueProducer only adds a new timestamp on
86 // queueBuffer
87 mCurrentFrameNumber = newTimestamps->frameNumber;
88 mFrameEventHistory.addQueue(*newTimestamps);
89 }
90 if (outDelta) {
91 // frame event histories will be processed
92 // only after the producer connects and requests
93 // deltas for the first time. Forward this intent
94 // to SF-side to turn event processing back on
95 mPreviouslyConnected = mCurrentlyConnected;
96 mCurrentlyConnected = true;
97 mFrameEventHistory.getAndResetDelta(outDelta);
98 }
99}
100
101void BLASTBufferItemConsumer::updateFrameTimestamps(uint64_t frameNumber, nsecs_t refreshStartTime,
102 const sp<Fence>& glDoneFence,
103 const sp<Fence>& presentFence,
104 const sp<Fence>& prevReleaseFence,
105 CompositorTiming compositorTiming,
106 nsecs_t latchTime, nsecs_t dequeueReadyTime) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800107 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800108
109 // if the producer is not connected, don't bother updating,
110 // the next producer that connects won't access this frame event
111 if (!mCurrentlyConnected) return;
112 std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
113 std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
114 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
115
116 mFrameEventHistory.addLatch(frameNumber, latchTime);
117 mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
118 mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
119 mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
120 compositorTiming);
121}
122
123void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
124 bool disconnect = false;
Hongguang Chen621ec582021-02-16 15:42:35 -0800125 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800126 while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
127 disconnect = true;
128 mDisconnectEvents.pop();
129 }
130 if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
131}
132
Hongguang Chen621ec582021-02-16 15:42:35 -0800133void BLASTBufferItemConsumer::onSidebandStreamChanged() {
Ady Abrahamdbca1352021-12-15 11:58:56 -0800134 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
135 if (bbq != nullptr) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800136 sp<NativeHandle> stream = getSidebandStream();
Ady Abrahamdbca1352021-12-15 11:58:56 -0800137 bbq->setSidebandStream(stream);
Hongguang Chen621ec582021-02-16 15:42:35 -0800138 }
139}
140
Vishnu Naird2aaab12022-02-10 14:49:09 -0800141BLASTBufferQueue::BLASTBufferQueue(const std::string& name, bool updateDestinationFrame)
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800142 : mSurfaceControl(nullptr),
143 mSize(1, 1),
Vishnu Nairea0de002020-11-17 17:42:37 -0800144 mRequestedSize(mSize),
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800145 mFormat(PIXEL_FORMAT_RGBA_8888),
Tianhao Yao4861b102022-02-03 20:18:35 +0000146 mTransactionReadyCallback(nullptr),
Vishnu Naird2aaab12022-02-10 14:49:09 -0800147 mSyncTransaction(nullptr),
148 mUpdateDestinationFrame(updateDestinationFrame) {
Vishnu Nair89496122020-12-14 17:14:53 -0800149 createBufferQueue(&mProducer, &mConsumer);
Valerie Hau0889c622020-02-19 15:04:47 -0800150 // since the adapter is in the client process, set dequeue timeout
151 // explicitly so that dequeueBuffer will block
152 mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
Valerie Hau65b8e872020-02-13 09:45:14 -0800153
Vishnu Nairdebd1cb2021-03-16 10:06:01 -0700154 // safe default, most producers are expected to override this
155 mProducer->setMaxDequeuedBufferCount(2);
Vishnu Nair1618c672021-02-05 13:08:26 -0800156 mBufferItemConsumer = new BLASTBufferItemConsumer(mConsumer,
157 GraphicBuffer::USAGE_HW_COMPOSER |
158 GraphicBuffer::USAGE_HW_TEXTURE,
Ady Abrahamdbca1352021-12-15 11:58:56 -0800159 1, false, this);
Valerie Haua32c5522019-12-09 10:11:08 -0800160 static int32_t id = 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700161 mName = name + "#" + std::to_string(id);
Vishnu Nairdab94092020-09-29 16:09:04 -0700162 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(id);
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700163 mQueuedBufferTrace = "QueuedBuffer - " + mName + "BLAST#" + std::to_string(id);
Valerie Haua32c5522019-12-09 10:11:08 -0800164 id++;
Vishnu Nairdab94092020-09-29 16:09:04 -0700165 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700166 mBufferItemConsumer->setFrameAvailableListener(this);
Robert Carr9f133d72020-04-01 15:51:46 -0700167
Huihong Luo02186fb2022-02-23 14:21:54 -0800168 ComposerServiceAIDL::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);
Ady Abraham0bde6b52021-05-18 13:57:02 -0700169 mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
chaviw69058fb2021-09-27 09:37:30 -0500170 mCurrentMaxAcquiredBufferCount = mMaxAcquiredBuffers;
Valerie Haua32c5522019-12-09 10:11:08 -0800171 mNumAcquired = 0;
172 mNumFrameAvailable = 0;
Robert Carr4c1b6462021-12-21 10:30:50 -0800173
174 TransactionCompletedListener::getInstance()->addQueueStallListener(
Patrick Williamsf1e5df12022-10-17 21:37:42 +0000175 [&](const std::string& reason) {
176 std::function<void(const std::string&)> callbackCopy;
177 {
178 std::unique_lock _lock{mMutex};
179 callbackCopy = mTransactionHangCallback;
180 }
181 if (callbackCopy) callbackCopy(reason);
182 },
183 this);
Robert Carr4c1b6462021-12-21 10:30:50 -0800184
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800185 BQA_LOGV("BLASTBufferQueue created");
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800186}
187
188BLASTBufferQueue::BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface,
189 int width, int height, int32_t format)
190 : BLASTBufferQueue(name) {
191 update(surface, width, height, format);
Robert Carr78c25dd2019-08-15 14:10:33 -0700192}
193
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800194BLASTBufferQueue::~BLASTBufferQueue() {
Robert Carr4c1b6462021-12-21 10:30:50 -0800195 TransactionCompletedListener::getInstance()->removeQueueStallListener(this);
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800196 if (mPendingTransactions.empty()) {
197 return;
198 }
199 BQA_LOGE("Applying pending transactions on dtor %d",
200 static_cast<uint32_t>(mPendingTransactions.size()));
201 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800202 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
Robert Carr79dc06a2022-02-22 15:28:59 -0800203 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
204 t.setApplyToken(mApplyToken).apply(false, true);
chaviw3b4bdcf2022-03-17 09:27:03 -0500205
206 if (mTransactionReadyCallback) {
207 mTransactionReadyCallback(mSyncTransaction);
208 }
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800209}
210
chaviw565ee542021-01-14 10:21:23 -0800211void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Naird2aaab12022-02-10 14:49:09 -0800212 int32_t format) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800213 LOG_ALWAYS_FATAL_IF(surface == nullptr, "BLASTBufferQueue: mSurfaceControl must not be NULL");
214
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000215 std::lock_guard _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800216 if (mFormat != format) {
217 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800218 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800219 }
220
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800221 const bool surfaceControlChanged = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairab066512022-01-04 22:28:00 +0000222 if (surfaceControlChanged && mSurfaceControl != nullptr) {
223 BQA_LOGD("Updating SurfaceControl without recreating BBQ");
224 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800225 bool applyTransaction = false;
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800226
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700227 // Always update the native object even though they might have the same layer handle, so we can
228 // get the updated transform hint from WM.
229 mSurfaceControl = surface;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800230 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800231 if (surfaceControlChanged) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800232 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
233 layer_state_t::eEnableBackpressure);
234 applyTransaction = true;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800235 }
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800236 mTransformHint = mSurfaceControl->getTransformHint();
237 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700238 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
239 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800240
Vishnu Nairea0de002020-11-17 17:42:37 -0800241 ui::Size newSize(width, height);
242 if (mRequestedSize != newSize) {
243 mRequestedSize.set(newSize);
244 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000245 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800246 // If the buffer supports scaling, update the frame immediately since the client may
247 // want to scale the existing buffer to the new size.
248 mSize = mRequestedSize;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800249 if (mUpdateDestinationFrame) {
250 t.setDestinationFrame(mSurfaceControl, Rect(newSize));
251 applyTransaction = true;
252 }
Vishnu Nair53c936c2020-12-03 11:46:37 -0800253 }
Robert Carrfc416512020-04-02 12:32:44 -0700254 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800255 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800256 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
257 t.setApplyToken(mApplyToken).apply(false, true);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800258 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700259}
260
chaviwd7deef72021-10-06 11:53:40 -0500261static std::optional<SurfaceControlStats> findMatchingStat(
262 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
263 for (auto stat : stats) {
264 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
265 return stat;
266 }
267 }
268 return std::nullopt;
269}
270
271static void transactionCommittedCallbackThunk(void* context, nsecs_t latchTime,
272 const sp<Fence>& presentFence,
273 const std::vector<SurfaceControlStats>& stats) {
274 if (context == nullptr) {
275 return;
276 }
277 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
278 bq->transactionCommittedCallback(latchTime, presentFence, stats);
279}
280
281void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
282 const sp<Fence>& /*presentFence*/,
283 const std::vector<SurfaceControlStats>& stats) {
284 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000285 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600286 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500287 BQA_LOGV("transactionCommittedCallback");
288 if (!mSurfaceControlsWithPendingCallback.empty()) {
289 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
290 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
291 if (stat) {
292 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
293
294 // We need to check if we were waiting for a transaction callback in order to
295 // process any pending buffers and unblock. It's possible to get transaction
chaviwc1cf4022022-06-03 13:32:33 -0500296 // callbacks for previous requests so we need to ensure that there are no pending
297 // frame numbers that were in a sync. We remove the frame from mSyncedFrameNumbers
298 // set and then check if it's empty. If there are no more pending syncs, we can
299 // proceed with flushing the shadow queue.
300 // We also want to check if mSyncTransaction is null because it's possible another
chaviwd7deef72021-10-06 11:53:40 -0500301 // sync request came in while waiting, but it hasn't started processing yet. In that
302 // case, we don't actually want to flush the frames in between since they will get
303 // processed and merged with the sync transaction and released earlier than if they
304 // were sent to SF
chaviwc1cf4022022-06-03 13:32:33 -0500305 mSyncedFrameNumbers.erase(currFrameNumber);
306 if (mSyncedFrameNumbers.empty() && mSyncTransaction == nullptr) {
chaviwd7deef72021-10-06 11:53:40 -0500307 flushShadowQueue();
308 }
309 } else {
chaviw768bfa02021-11-01 09:50:57 -0500310 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviwd7deef72021-10-06 11:53:40 -0500311 }
312 } else {
313 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
314 "empty.");
315 }
chaviwd7deef72021-10-06 11:53:40 -0500316 decStrong((void*)transactionCommittedCallbackThunk);
317 }
318}
319
Robert Carr78c25dd2019-08-15 14:10:33 -0700320static void transactionCallbackThunk(void* context, nsecs_t latchTime,
321 const sp<Fence>& presentFence,
322 const std::vector<SurfaceControlStats>& stats) {
323 if (context == nullptr) {
324 return;
325 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800326 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700327 bq->transactionCallback(latchTime, presentFence, stats);
328}
329
330void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
331 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700332 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000333 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600334 BBQ_TRACE();
chaviw71c2cc42020-10-23 16:42:02 -0700335 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700336
chaviw42026162021-04-16 15:46:12 -0500337 if (!mSurfaceControlsWithPendingCallback.empty()) {
338 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
339 mSurfaceControlsWithPendingCallback.pop();
chaviwd7deef72021-10-06 11:53:40 -0500340 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
341 if (statsOptional) {
342 SurfaceControlStats stat = *statsOptional;
Vishnu Nair71fcf912022-10-18 09:14:20 -0700343 if (stat.transformHint) {
344 mTransformHint = *stat.transformHint;
345 mBufferItemConsumer->setTransformHint(mTransformHint);
346 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
347 }
Vishnu Nairde66dc72021-06-17 17:54:41 -0700348 // Update frametime stamps if the frame was latched and presented, indicated by a
349 // valid latch time.
350 if (stat.latchTime > 0) {
351 mBufferItemConsumer
352 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
353 stat.frameEventStats.refreshStartTime,
354 stat.frameEventStats.gpuCompositionDoneFence,
355 stat.presentFence, stat.previousReleaseFence,
356 stat.frameEventStats.compositorTiming,
357 stat.latchTime,
358 stat.frameEventStats.dequeueReadyTime);
359 }
Robert Carr405e2f62021-12-31 16:59:34 -0800360 auto currFrameNumber = stat.frameEventStats.frameNumber;
361 std::vector<ReleaseCallbackId> staleReleases;
362 for (const auto& [key, value]: mSubmitted) {
363 if (currFrameNumber > key.framenumber) {
364 staleReleases.push_back(key);
365 }
366 }
367 for (const auto& staleRelease : staleReleases) {
Robert Carr405e2f62021-12-31 16:59:34 -0800368 releaseBufferCallbackLocked(staleRelease,
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700369 stat.previousReleaseFence
370 ? stat.previousReleaseFence
371 : Fence::NO_FENCE,
372 stat.currentMaxAcquiredBufferCount,
373 true /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800374 }
chaviwd7deef72021-10-06 11:53:40 -0500375 } else {
chaviw768bfa02021-11-01 09:50:57 -0500376 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500377 }
378 } else {
379 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
380 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800381 }
chaviw71c2cc42020-10-23 16:42:02 -0700382
chaviw71c2cc42020-10-23 16:42:02 -0700383 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700384 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700385}
386
Vishnu Nair1506b182021-02-22 14:35:15 -0800387// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
388// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
389// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
390// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700391static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
chaviw69058fb2021-09-27 09:37:30 -0500392 const sp<Fence>& releaseFence,
393 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800394 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800395 if (blastBufferQueue) {
chaviw69058fb2021-09-27 09:37:30 -0500396 blastBufferQueue->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700397 } else {
398 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800399 }
400}
401
chaviwd7deef72021-10-06 11:53:40 -0500402void BLASTBufferQueue::flushShadowQueue() {
403 BQA_LOGV("flushShadowQueue");
404 int numFramesToFlush = mNumFrameAvailable;
405 while (numFramesToFlush > 0) {
406 acquireNextBufferLocked(std::nullopt);
407 numFramesToFlush--;
408 }
409}
410
chaviw69058fb2021-09-27 09:37:30 -0500411void BLASTBufferQueue::releaseBufferCallback(
412 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
413 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000414 std::lock_guard _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600415 BBQ_TRACE();
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700416 releaseBufferCallbackLocked(id, releaseFence, currentMaxAcquiredBufferCount,
417 false /* fakeRelease */);
Robert Carr405e2f62021-12-31 16:59:34 -0800418}
419
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700420void BLASTBufferQueue::releaseBufferCallbackLocked(
421 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
422 std::optional<uint32_t> currentMaxAcquiredBufferCount, bool fakeRelease) {
Robert Carr405e2f62021-12-31 16:59:34 -0800423 ATRACE_CALL();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700424 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800425
Ady Abraham899dcdb2021-06-15 16:56:21 -0700426 // Calculate how many buffers we need to hold before we release them back
427 // to the buffer queue. This will prevent higher latency when we are running
428 // on a lower refresh rate than the max supported. We only do that for EGL
429 // clients as others don't care about latency
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000430 const auto it = mSubmitted.find(id);
431 const bool isEGL = it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
Ady Abraham899dcdb2021-06-15 16:56:21 -0700432
chaviw69058fb2021-09-27 09:37:30 -0500433 if (currentMaxAcquiredBufferCount) {
434 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
435 }
436
liulijunf90df632022-11-14 14:24:48 +0800437 const uint32_t numPendingBuffersToHold =
438 isEGL ? std::max(0, mMaxAcquiredBuffers - (int32_t)mCurrentMaxAcquiredBufferCount) : 0;
Robert Carr405e2f62021-12-31 16:59:34 -0800439
440 auto rb = ReleasedBuffer{id, releaseFence};
441 if (std::find(mPendingRelease.begin(), mPendingRelease.end(), rb) == mPendingRelease.end()) {
442 mPendingRelease.emplace_back(rb);
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700443 if (fakeRelease) {
444 BQA_LOGE("Faking releaseBufferCallback from transactionCompleteCallback %" PRIu64,
445 id.framenumber);
446 BBQ_TRACE("FakeReleaseCallback");
447 }
Robert Carr405e2f62021-12-31 16:59:34 -0800448 }
Ady Abraham899dcdb2021-06-15 16:56:21 -0700449
450 // Release all buffers that are beyond the ones that we need to hold
451 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500452 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700453 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500454 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwc1cf4022022-06-03 13:32:33 -0500455 // Don't process the transactions here if mSyncedFrameNumbers is not empty. That means
456 // are still transactions that have sync buffers in them that have not been applied or
457 // dropped. Instead, let onFrameAvailable handle processing them since it will merge with
458 // the syncTransaction.
459 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500460 acquireNextBufferLocked(std::nullopt);
461 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800462 }
463
Ady Abraham899dcdb2021-06-15 16:56:21 -0700464 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700465 ATRACE_INT(mQueuedBufferTrace.c_str(),
466 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800467 mCallbackCV.notify_all();
468}
469
chaviw0acd33a2021-11-02 11:55:37 -0500470void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
471 const sp<Fence>& releaseFence) {
472 auto it = mSubmitted.find(callbackId);
473 if (it == mSubmitted.end()) {
474 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
475 callbackId.to_string().c_str());
476 return;
477 }
478 mNumAcquired--;
chaviw57ae4b22022-02-03 16:51:39 -0600479 BBQ_TRACE("frame=%" PRIu64, callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500480 BQA_LOGV("released %s", callbackId.to_string().c_str());
481 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
482 mSubmitted.erase(it);
chaviwc1cf4022022-06-03 13:32:33 -0500483 // Remove the frame number from mSyncedFrameNumbers since we can get a release callback
484 // without getting a transaction committed if the buffer was dropped.
485 mSyncedFrameNumbers.erase(callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500486}
487
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000488status_t BLASTBufferQueue::acquireNextBufferLocked(
chaviwd7deef72021-10-06 11:53:40 -0500489 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800490 // Check if we have frames available and we have not acquired the maximum number of buffers.
491 // Even with this check, the consumer can fail to acquire an additional buffer if the consumer
492 // has already acquired (mMaxAcquiredBuffers + 1) and the new buffer is not droppable. In this
493 // case mBufferItemConsumer->acquireBuffer will return with NO_BUFFER_AVAILABLE.
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000494 if (mNumFrameAvailable == 0) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800495 BQA_LOGV("Can't acquire next buffer. No available frames");
496 return BufferQueue::NO_BUFFER_AVAILABLE;
497 }
498
499 if (mNumAcquired >= (mMaxAcquiredBuffers + 2)) {
500 BQA_LOGV("Can't acquire next buffer. Already acquired max frames %d max:%d + 2",
501 mNumAcquired, mMaxAcquiredBuffers);
502 return BufferQueue::NO_BUFFER_AVAILABLE;
Valerie Haud3b90d22019-11-06 09:37:31 -0800503 }
504
Valerie Haua32c5522019-12-09 10:11:08 -0800505 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700506 BQA_LOGE("ERROR : surface control is null");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000507 return NAME_NOT_FOUND;
Valerie Haud3b90d22019-11-06 09:37:31 -0800508 }
509
Robert Carr78c25dd2019-08-15 14:10:33 -0700510 SurfaceComposerClient::Transaction localTransaction;
511 bool applyTransaction = true;
512 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500513 if (transaction) {
514 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700515 applyTransaction = false;
516 }
517
Valerie Haua32c5522019-12-09 10:11:08 -0800518 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800519
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800520 status_t status =
521 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800522 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
523 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000524 return status;
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800525 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700526 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000527 return status;
Robert Carr78c25dd2019-08-15 14:10:33 -0700528 }
chaviw57ae4b22022-02-03 16:51:39 -0600529
Valerie Haua32c5522019-12-09 10:11:08 -0800530 auto buffer = bufferItem.mGraphicBuffer;
531 mNumFrameAvailable--;
chaviw57ae4b22022-02-03 16:51:39 -0600532 BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800533
534 if (buffer == nullptr) {
535 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700536 BQA_LOGE("Buffer was empty");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000537 return BAD_VALUE;
Valerie Haua32c5522019-12-09 10:11:08 -0800538 }
539
Vishnu Nair670b3f72020-09-29 17:52:18 -0700540 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700541 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800542 "buffer{size=%dx%d transform=%d}",
543 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
544 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
545 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000546 return acquireNextBufferLocked(transaction);
Vishnu Nair670b3f72020-09-29 17:52:18 -0700547 }
548
Valerie Haua32c5522019-12-09 10:11:08 -0800549 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700550 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
551 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
552 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700553
Valerie Hau871d6352020-01-29 08:44:02 -0800554 bool needsDisconnect = false;
555 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
556
557 // if producer disconnected before, notify SurfaceFlinger
558 if (needsDisconnect) {
559 t->notifyProducerDisconnect(mSurfaceControl);
560 }
561
Robert Carr78c25dd2019-08-15 14:10:33 -0700562 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
563 incStrong((void*)transactionCallbackThunk);
564
Vishnu Nair932f6ae2021-09-29 17:33:10 -0700565 mSize = mRequestedSize;
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700566 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000567 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
568 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700569 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800570
Vishnu Nair1506b182021-02-22 14:35:15 -0800571 auto releaseBufferCallback =
572 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
chaviw69058fb2021-09-27 09:37:30 -0500573 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
chaviwba4320c2021-09-15 15:20:53 -0500574 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
chaviw8dd181f2022-01-05 18:36:46 -0600575 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500576 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
577 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
578 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700579 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviwf2dace72021-11-17 17:36:50 -0600580
chaviw42026162021-04-16 15:46:12 -0500581 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700582
Vishnu Naird2aaab12022-02-10 14:49:09 -0800583 if (mUpdateDestinationFrame) {
584 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
585 } else {
586 const bool ignoreDestinationFrame =
587 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
588 t->setFlags(mSurfaceControl,
589 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
590 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700591 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700592 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800593 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800594 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800595 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800596 if (!bufferItem.mIsAutoTimestamp) {
597 t->setDesiredPresentTime(bufferItem.mTimestamp);
598 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700599
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800600 // Drop stale frame timeline infos
601 while (!mPendingFrameTimelines.empty() &&
602 mPendingFrameTimelines.front().first < bufferItem.mFrameNumber) {
603 ATRACE_FORMAT_INSTANT("dropping stale frameNumber: %" PRIu64 " vsyncId: %" PRId64,
604 mPendingFrameTimelines.front().first,
605 mPendingFrameTimelines.front().second.vsyncId);
606 mPendingFrameTimelines.pop();
607 }
608
609 if (!mPendingFrameTimelines.empty() &&
610 mPendingFrameTimelines.front().first == bufferItem.mFrameNumber) {
611 ATRACE_FORMAT_INSTANT("Transaction::setFrameTimelineInfo frameNumber: %" PRIu64
612 " vsyncId: %" PRId64,
613 bufferItem.mFrameNumber,
614 mPendingFrameTimelines.front().second.vsyncId);
615 t->setFrameTimelineInfo(mPendingFrameTimelines.front().second);
616 mPendingFrameTimelines.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100617 }
618
Vishnu Nairadf632b2021-01-07 14:05:08 -0800619 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000620 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800621 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
622 if (dequeueTime != mDequeueTimestamps.end()) {
623 Parcel p;
624 p.writeInt64(dequeueTime->second);
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800625 t->setMetadata(mSurfaceControl, gui::METADATA_DEQUEUE_TIME, p);
Vishnu Nairadf632b2021-01-07 14:05:08 -0800626 mDequeueTimestamps.erase(dequeueTime);
627 }
628 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800629
chaviw6a195272021-09-03 16:14:25 -0500630 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700631 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800632 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
633 t->setApplyToken(mApplyToken).apply(false, true);
634 mAppliedLastTransaction = true;
635 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
636 } else {
637 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
638 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700639 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700640
chaviwd7deef72021-10-06 11:53:40 -0500641 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800642 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700643 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500644 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800645 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700646 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700647 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000648 return OK;
Robert Carr78c25dd2019-08-15 14:10:33 -0700649}
650
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800651Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
652 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800653 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800654 }
655 return item.mCrop;
656}
657
chaviwd7deef72021-10-06 11:53:40 -0500658void BLASTBufferQueue::acquireAndReleaseBuffer() {
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000659 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500660 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500661 status_t status =
662 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
663 if (status != OK) {
664 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
665 statusToString(status).c_str());
666 return;
667 }
chaviwd7deef72021-10-06 11:53:40 -0500668 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500669 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500670}
671
Vishnu Nairaef1de92020-10-22 12:15:53 -0700672void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000673 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
674 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
chaviwc1cf4022022-06-03 13:32:33 -0500675
Tianhao Yao4861b102022-02-03 20:18:35 +0000676 {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000677 UNIQUE_LOCK_WITH_ASSERTION(mMutex);
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000678 BBQ_TRACE();
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000679 bool waitForTransactionCallback = !mSyncedFrameNumbers.empty();
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800680
Tianhao Yao4861b102022-02-03 20:18:35 +0000681 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
682 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800683
Tianhao Yao4861b102022-02-03 20:18:35 +0000684 if (syncTransactionSet) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000685 // If we are going to re-use the same mSyncTransaction, release the buffer that may
686 // already be set in the Transaction. This is to allow us a free slot early to continue
687 // processing a new buffer.
688 if (!mAcquireSingleBuffer) {
689 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
690 if (bufferData) {
691 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
692 bufferData->frameNumber);
693 releaseBuffer(bufferData->generateReleaseCallbackId(),
694 bufferData->acquireFence);
Tianhao Yao4861b102022-02-03 20:18:35 +0000695 }
696 }
chaviw0acd33a2021-11-02 11:55:37 -0500697
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000698 if (waitForTransactionCallback) {
699 // We are waiting on a previous sync's transaction callback so allow another sync
700 // transaction to proceed.
701 //
702 // We need to first flush out the transactions that were in between the two syncs.
703 // We do this by merging them into mSyncTransaction so any buffer merging will get
704 // a release callback invoked.
705 while (mNumFrameAvailable > 0) {
706 // flush out the shadow queue
707 acquireAndReleaseBuffer();
708 }
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800709 } else {
710 // Make sure the frame available count is 0 before proceeding with a sync to ensure
711 // the correct frame is used for the sync. The only way mNumFrameAvailable would be
712 // greater than 0 is if we already ran out of buffers previously. This means we
713 // need to flush the buffers before proceeding with the sync.
714 while (mNumFrameAvailable > 0) {
715 BQA_LOGD("waiting until no queued buffers");
716 mCallbackCV.wait(_lock);
717 }
chaviwd7deef72021-10-06 11:53:40 -0500718 }
719 }
720
Tianhao Yao4861b102022-02-03 20:18:35 +0000721 // add to shadow queue
722 mNumFrameAvailable++;
chaviwc1cf4022022-06-03 13:32:33 -0500723 if (waitForTransactionCallback && mNumFrameAvailable >= 2) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000724 acquireAndReleaseBuffer();
725 }
726 ATRACE_INT(mQueuedBufferTrace.c_str(),
727 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
728
729 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
730 item.mFrameNumber, boolToString(syncTransactionSet));
731
732 if (syncTransactionSet) {
Vishnu Nairb4b484a2023-01-20 10:00:18 -0800733 // Add to mSyncedFrameNumbers before waiting in case any buffers are released
734 // while waiting for a free buffer. The release and commit callback will try to
735 // acquire buffers if there are any available, but we don't want it to acquire
736 // in the case where a sync transaction wants the buffer.
737 mSyncedFrameNumbers.emplace(item.mFrameNumber);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000738 // If there's no available buffer and we're in a sync transaction, we need to wait
739 // instead of returning since we guarantee a buffer will be acquired for the sync.
740 while (acquireNextBufferLocked(mSyncTransaction) == BufferQueue::NO_BUFFER_AVAILABLE) {
741 BQA_LOGD("waiting for available buffer");
742 mCallbackCV.wait(_lock);
743 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000744
745 // Only need a commit callback when syncing to ensure the buffer that's synced has been
746 // sent to SF
747 incStrong((void*)transactionCommittedCallbackThunk);
748 mSyncTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,
749 static_cast<void*>(this));
Tianhao Yao4861b102022-02-03 20:18:35 +0000750 if (mAcquireSingleBuffer) {
751 prevCallback = mTransactionReadyCallback;
752 prevTransaction = mSyncTransaction;
753 mTransactionReadyCallback = nullptr;
754 mSyncTransaction = nullptr;
755 }
chaviwc1cf4022022-06-03 13:32:33 -0500756 } else if (!waitForTransactionCallback) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000757 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800758 }
759 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000760 if (prevCallback) {
761 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500762 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800763}
764
Vishnu Nairaef1de92020-10-22 12:15:53 -0700765void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
766 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
767 // Do nothing since we are not storing unacquired buffer items locally.
768}
769
Vishnu Nairadf632b2021-01-07 14:05:08 -0800770void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000771 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800772 mDequeueTimestamps[bufferId] = systemTime();
773};
774
775void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000776 std::lock_guard _lock{mTimestampMutex};
Vishnu Nairadf632b2021-01-07 14:05:08 -0800777 mDequeueTimestamps.erase(bufferId);
778};
779
Tianhao Yao4861b102022-02-03 20:18:35 +0000780void BLASTBufferQueue::syncNextTransaction(
781 std::function<void(SurfaceComposerClient::Transaction*)> callback,
782 bool acquireSingleBuffer) {
chaviw3b4bdcf2022-03-17 09:27:03 -0500783 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
784 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
785
786 {
787 std::lock_guard _lock{mMutex};
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000788 BBQ_TRACE();
chaviw3b4bdcf2022-03-17 09:27:03 -0500789 // We're about to overwrite the previous call so we should invoke that callback
790 // immediately.
791 if (mTransactionReadyCallback) {
792 prevCallback = mTransactionReadyCallback;
793 prevTransaction = mSyncTransaction;
794 }
795
796 mTransactionReadyCallback = callback;
797 if (callback) {
798 mSyncTransaction = new SurfaceComposerClient::Transaction();
799 } else {
800 mSyncTransaction = nullptr;
801 }
802 mAcquireSingleBuffer = mTransactionReadyCallback ? acquireSingleBuffer : true;
Tianhao Yao4861b102022-02-03 20:18:35 +0000803 }
chaviw3b4bdcf2022-03-17 09:27:03 -0500804
805 if (prevCallback) {
806 prevCallback(prevTransaction);
807 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000808}
809
810void BLASTBufferQueue::stopContinuousSyncTransaction() {
811 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
812 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
813 {
814 std::lock_guard _lock{mMutex};
815 bool invokeCallback = mTransactionReadyCallback && !mAcquireSingleBuffer;
816 if (invokeCallback) {
817 prevCallback = mTransactionReadyCallback;
818 prevTransaction = mSyncTransaction;
819 }
820 mTransactionReadyCallback = nullptr;
821 mSyncTransaction = nullptr;
822 mAcquireSingleBuffer = true;
823 }
824 if (prevCallback) {
825 prevCallback(prevTransaction);
826 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700827}
828
Vishnu Nairea0de002020-11-17 17:42:37 -0800829bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700830 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
831 // Only reject buffers if scaling mode is freeze.
832 return false;
833 }
834
Vishnu Naire1a42322020-10-02 17:42:04 -0700835 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
836 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
837
838 // Take the buffer's orientation into account
839 if (item.mTransform & ui::Transform::ROT_90) {
840 std::swap(bufWidth, bufHeight);
841 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800842 ui::Size bufferSize(bufWidth, bufHeight);
843 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800844 return false;
845 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700846
Vishnu Nair670b3f72020-09-29 17:52:18 -0700847 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800848 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700849}
Vishnu Nairbf255772020-10-16 10:54:41 -0700850
Robert Carr05086b22020-10-13 18:22:51 -0700851class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700852private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700853 std::mutex mMutex;
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000854 sp<BLASTBufferQueue> mBbq GUARDED_BY(mMutex);
855 bool mDestroyed GUARDED_BY(mMutex) = false;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700856
Robert Carr05086b22020-10-13 18:22:51 -0700857public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700858 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
859 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
860 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700861
Robert Carr05086b22020-10-13 18:22:51 -0700862 void allocateBuffers() override {
863 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
864 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
865 auto gbp = getIGraphicBufferProducer();
866 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
867 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
868 gbp->allocateBuffers(reqWidth, reqHeight,
869 reqFormat, reqUsage);
870
871 }).detach();
872 }
Robert Carr9c006e02020-10-14 13:41:57 -0700873
Marin Shalamanovc5986772021-03-16 16:09:49 +0100874 status_t setFrameRate(float frameRate, int8_t compatibility,
875 int8_t changeFrameRateStrategy) override {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000876 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700877 if (mDestroyed) {
878 return DEAD_OBJECT;
879 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100880 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
881 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700882 return BAD_VALUE;
883 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100884 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700885 }
Robert Carr9b611b72020-10-19 12:00:23 -0700886
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800887 status_t setFrameTimelineInfo(uint64_t frameNumber,
888 const FrameTimelineInfo& frameTimelineInfo) override {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000889 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700890 if (mDestroyed) {
891 return DEAD_OBJECT;
892 }
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800893 return mBbq->setFrameTimelineInfo(frameNumber, frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700894 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700895
896 void destroy() override {
897 Surface::destroy();
898
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000899 std::lock_guard _lock{mMutex};
Vishnu Nair95b6d512021-08-30 15:31:08 -0700900 mDestroyed = true;
901 mBbq = nullptr;
902 }
Robert Carr05086b22020-10-13 18:22:51 -0700903};
904
Robert Carr9c006e02020-10-14 13:41:57 -0700905// TODO: Can we coalesce this with frame updates? Need to confirm
906// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200907status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
908 bool shouldBeSeamless) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000909 std::lock_guard _lock{mMutex};
Robert Carr9c006e02020-10-14 13:41:57 -0700910 SurfaceComposerClient::Transaction t;
911
Marin Shalamanov46084422020-10-13 12:33:42 +0200912 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700913}
914
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800915status_t BLASTBufferQueue::setFrameTimelineInfo(uint64_t frameNumber,
916 const FrameTimelineInfo& frameTimelineInfo) {
917 ATRACE_FORMAT("%s(%s) frameNumber: %" PRIu64 " vsyncId: %" PRId64, __func__, mName.c_str(),
918 frameNumber, frameTimelineInfo.vsyncId);
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000919 std::lock_guard _lock{mMutex};
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800920 mPendingFrameTimelines.push({frameNumber, frameTimelineInfo});
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100921 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700922}
923
Hongguang Chen621ec582021-02-16 15:42:35 -0800924void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000925 std::lock_guard _lock{mMutex};
Hongguang Chen621ec582021-02-16 15:42:35 -0800926 SurfaceComposerClient::Transaction t;
927
928 t.setSidebandStream(mSurfaceControl, stream).apply();
929}
930
Vishnu Nair992496b2020-10-22 17:27:21 -0700931sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +0000932 std::lock_guard _lock{mMutex};
Vishnu Nair992496b2020-10-22 17:27:21 -0700933 sp<IBinder> scHandle = nullptr;
934 if (includeSurfaceControlHandle && mSurfaceControl) {
935 scHandle = mSurfaceControl->getHandle();
936 }
937 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700938}
939
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800940void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
941 uint64_t frameNumber) {
942 std::lock_guard _lock{mMutex};
943 if (mLastAcquiredFrameNumber >= frameNumber) {
944 // Apply the transaction since we have already acquired the desired frame.
945 t->apply();
946 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500947 mPendingTransactions.emplace_back(frameNumber, *t);
948 // Clear the transaction so it can't be applied elsewhere.
949 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800950 }
951}
952
chaviw6a195272021-09-03 16:14:25 -0500953void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
954 std::lock_guard _lock{mMutex};
955
956 SurfaceComposerClient::Transaction t;
957 mergePendingTransactions(&t, frameNumber);
Robert Carr79dc06a2022-02-22 15:28:59 -0800958 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
959 t.setApplyToken(mApplyToken).apply(false, true);
chaviw6a195272021-09-03 16:14:25 -0500960}
961
962void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
963 uint64_t frameNumber) {
964 auto mergeTransaction =
965 [&t, currentFrameNumber = frameNumber](
966 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
967 auto& [targetFrameNumber, transaction] = pendingTransaction;
968 if (currentFrameNumber < targetFrameNumber) {
969 return false;
970 }
971 t->merge(std::move(transaction));
972 return true;
973 };
974
975 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
976 mPendingTransactions.end(), mergeTransaction),
977 mPendingTransactions.end());
978}
979
chaviwd84085a2022-02-08 11:07:04 -0600980SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
981 uint64_t frameNumber) {
982 std::lock_guard _lock{mMutex};
983 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
984 mergePendingTransactions(t, frameNumber);
985 return t;
986}
987
Vishnu Nair89496122020-12-14 17:14:53 -0800988// Maintains a single worker thread per process that services a list of runnables.
989class AsyncWorker : public Singleton<AsyncWorker> {
990private:
991 std::thread mThread;
992 bool mDone = false;
993 std::deque<std::function<void()>> mRunnables;
994 std::mutex mMutex;
995 std::condition_variable mCv;
996 void run() {
997 std::unique_lock<std::mutex> lock(mMutex);
998 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -0800999 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001000 std::deque<std::function<void()>> runnables = std::move(mRunnables);
1001 mRunnables.clear();
1002 lock.unlock();
1003 // Run outside the lock since the runnable might trigger another
1004 // post to the async worker.
1005 execute(runnables);
1006 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -08001007 }
Wonsik Kim567533e2021-05-04 19:31:29 -07001008 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -08001009 }
1010 }
1011
Vishnu Nair51e4dc82021-10-01 15:32:33 -07001012 void execute(std::deque<std::function<void()>>& runnables) {
1013 while (!runnables.empty()) {
1014 std::function<void()> runnable = runnables.front();
1015 runnables.pop_front();
1016 runnable();
1017 }
1018 }
1019
Vishnu Nair89496122020-12-14 17:14:53 -08001020public:
1021 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
1022
1023 ~AsyncWorker() {
1024 mDone = true;
1025 mCv.notify_all();
1026 if (mThread.joinable()) {
1027 mThread.join();
1028 }
1029 }
1030
1031 void post(std::function<void()> runnable) {
1032 std::unique_lock<std::mutex> lock(mMutex);
1033 mRunnables.emplace_back(std::move(runnable));
1034 mCv.notify_one();
1035 }
1036};
1037ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
1038
1039// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
1040class AsyncProducerListener : public BnProducerListener {
1041private:
1042 const sp<IProducerListener> mListener;
1043
1044public:
1045 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
1046
1047 void onBufferReleased() override {
1048 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
1049 }
1050
1051 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
1052 AsyncWorker::getInstance().post(
1053 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
1054 }
1055};
1056
1057// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
1058// can be non-blocking when the producer is in the client process.
1059class BBQBufferQueueProducer : public BufferQueueProducer {
1060public:
1061 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
1062 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
1063
1064 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
1065 QueueBufferOutput* output) override {
1066 if (!listener) {
1067 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
1068 }
1069
1070 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
1071 producerControlledByApp, output);
1072 }
Vishnu Nair17dde612020-12-28 11:39:59 -08001073
1074 int query(int what, int* value) override {
1075 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
1076 *value = 1;
1077 return NO_ERROR;
1078 }
1079 return BufferQueueProducer::query(what, value);
1080 }
Vishnu Nair89496122020-12-14 17:14:53 -08001081};
1082
1083// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
1084// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
1085// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
1086// we can deadlock.
1087void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
1088 sp<IGraphicBufferConsumer>* outConsumer) {
1089 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
1090 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
1091
1092 sp<BufferQueueCore> core(new BufferQueueCore());
1093 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
1094
1095 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
1096 LOG_ALWAYS_FATAL_IF(producer == nullptr,
1097 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
1098
Vishnu Nair8b30dd12021-01-25 14:16:54 -08001099 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
1100 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -08001101 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
1102 "BLASTBufferQueue: failed to create BufferQueueConsumer");
1103
1104 *outProducer = producer;
1105 *outConsumer = consumer;
1106}
1107
chaviw497e81c2021-02-04 17:09:47 -08001108PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
1109 PixelFormat convertedFormat = format;
1110 switch (format) {
1111 case PIXEL_FORMAT_TRANSPARENT:
1112 case PIXEL_FORMAT_TRANSLUCENT:
1113 convertedFormat = PIXEL_FORMAT_RGBA_8888;
1114 break;
1115 case PIXEL_FORMAT_OPAQUE:
1116 convertedFormat = PIXEL_FORMAT_RGBX_8888;
1117 break;
1118 }
1119 return convertedFormat;
1120}
1121
Robert Carr82d07c92021-05-10 11:36:43 -07001122uint32_t BLASTBufferQueue::getLastTransformHint() const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001123 std::lock_guard _lock{mMutex};
Robert Carr82d07c92021-05-10 11:36:43 -07001124 if (mSurfaceControl != nullptr) {
1125 return mSurfaceControl->getTransformHint();
1126 } else {
1127 return 0;
1128 }
1129}
1130
chaviw0b020f82021-08-20 12:00:47 -05001131uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001132 std::lock_guard _lock{mMutex};
chaviw0b020f82021-08-20 12:00:47 -05001133 return mLastAcquiredFrameNumber;
1134}
1135
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001136bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001137 std::lock_guard _lock{mMutex};
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001138 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1139}
1140
Patrick Williamsf1e5df12022-10-17 21:37:42 +00001141void BLASTBufferQueue::setTransactionHangCallback(
1142 std::function<void(const std::string&)> callback) {
Chavi Weingartene0237bb2023-02-06 21:48:32 +00001143 std::lock_guard _lock{mMutex};
Robert Carr4c1b6462021-12-21 10:30:50 -08001144 mTransactionHangCallback = callback;
1145}
1146
Robert Carr78c25dd2019-08-15 14:10:33 -07001147} // namespace android