blob: 948611218b18bc40a07b7ebc50effb6065310a0d [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
Robert Carr78c25dd2019-08-15 14:10:33 -070038#include <chrono>
39
40using namespace std::chrono_literals;
41
Vishnu Nairdab94092020-09-29 16:09:04 -070042namespace {
chaviw3277faf2021-05-19 16:45:23 -050043inline const char* boolToString(bool b) {
Vishnu Nairdab94092020-09-29 16:09:04 -070044 return b ? "true" : "false";
45}
46} // namespace
47
Robert Carr78c25dd2019-08-15 14:10:33 -070048namespace android {
49
Vishnu Nairdab94092020-09-29 16:09:04 -070050// Macros to include adapter info in log messages
chaviwd7deef72021-10-06 11:53:40 -050051#define BQA_LOGD(x, ...) \
52 ALOGD("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070053#define BQA_LOGV(x, ...) \
54 ALOGV("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairc6f89ee2020-12-11 14:27:32 -080055// enable logs for a single layer
56//#define BQA_LOGV(x, ...) \
57// ALOGV_IF((strstr(mName.c_str(), "SurfaceView") != nullptr), "[%s](f:%u,a:%u) " x, \
58// mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070059#define BQA_LOGE(x, ...) \
60 ALOGE("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
61
chaviw57ae4b22022-02-03 16:51:39 -060062#define BBQ_TRACE(x, ...) \
63 ATRACE_FORMAT("%s - %s(f:%u,a:%u)" x, __FUNCTION__, mName.c_str(), mNumFrameAvailable, \
64 mNumAcquired, ##__VA_ARGS__)
65
Valerie Hau871d6352020-01-29 08:44:02 -080066void BLASTBufferItemConsumer::onDisconnect() {
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000067 Mutex::Autolock lock(mMutex);
68 mPreviouslyConnected = mCurrentlyConnected;
69 mCurrentlyConnected = false;
70 if (mPreviouslyConnected) {
71 mDisconnectEvents.push(mCurrentFrameNumber);
Valerie Hau871d6352020-01-29 08:44:02 -080072 }
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000073 mFrameEventHistory.onDisconnect();
Valerie Hau871d6352020-01-29 08:44:02 -080074}
75
76void BLASTBufferItemConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
77 FrameEventHistoryDelta* outDelta) {
Hongguang Chen621ec582021-02-16 15:42:35 -080078 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080079 if (newTimestamps) {
80 // BufferQueueProducer only adds a new timestamp on
81 // queueBuffer
82 mCurrentFrameNumber = newTimestamps->frameNumber;
83 mFrameEventHistory.addQueue(*newTimestamps);
84 }
85 if (outDelta) {
86 // frame event histories will be processed
87 // only after the producer connects and requests
88 // deltas for the first time. Forward this intent
89 // to SF-side to turn event processing back on
90 mPreviouslyConnected = mCurrentlyConnected;
91 mCurrentlyConnected = true;
92 mFrameEventHistory.getAndResetDelta(outDelta);
93 }
94}
95
96void BLASTBufferItemConsumer::updateFrameTimestamps(uint64_t frameNumber, nsecs_t refreshStartTime,
97 const sp<Fence>& glDoneFence,
98 const sp<Fence>& presentFence,
99 const sp<Fence>& prevReleaseFence,
100 CompositorTiming compositorTiming,
101 nsecs_t latchTime, nsecs_t dequeueReadyTime) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800102 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800103
104 // if the producer is not connected, don't bother updating,
105 // the next producer that connects won't access this frame event
106 if (!mCurrentlyConnected) return;
107 std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
108 std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
109 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
110
111 mFrameEventHistory.addLatch(frameNumber, latchTime);
112 mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
113 mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
114 mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
115 compositorTiming);
116}
117
118void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
119 bool disconnect = false;
Hongguang Chen621ec582021-02-16 15:42:35 -0800120 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800121 while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
122 disconnect = true;
123 mDisconnectEvents.pop();
124 }
125 if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
126}
127
Hongguang Chen621ec582021-02-16 15:42:35 -0800128void BLASTBufferItemConsumer::onSidebandStreamChanged() {
Ady Abrahamdbca1352021-12-15 11:58:56 -0800129 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
130 if (bbq != nullptr) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800131 sp<NativeHandle> stream = getSidebandStream();
Ady Abrahamdbca1352021-12-15 11:58:56 -0800132 bbq->setSidebandStream(stream);
Hongguang Chen621ec582021-02-16 15:42:35 -0800133 }
134}
135
Brian Lindahl957985b2023-01-31 15:42:47 -0700136void BLASTBufferItemConsumer::resizeFrameEventHistory(size_t newSize) {
137 Mutex::Autolock lock(mMutex);
138 mFrameEventHistory.resize(newSize);
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
Robert Carr78c25dd2019-08-15 14:10:33 -0700215 std::unique_lock _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 {
285 std::unique_lock _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 {
333 std::unique_lock _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) {
chaviw57ae4b22022-02-03 16:51:39 -0600414 BBQ_TRACE();
Robert Carr405e2f62021-12-31 16:59:34 -0800415
Vishnu Nair1506b182021-02-22 14:35:15 -0800416 std::unique_lock _lock{mMutex};
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
431 const bool isEGL = [&] {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700432 const auto it = mSubmitted.find(id);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700433 return it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
434 }();
435
chaviw69058fb2021-09-27 09:37:30 -0500436 if (currentMaxAcquiredBufferCount) {
437 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
438 }
439
Ady Abraham899dcdb2021-06-15 16:56:21 -0700440 const auto numPendingBuffersToHold =
chaviw69058fb2021-09-27 09:37:30 -0500441 isEGL ? std::max(0u, mMaxAcquiredBuffers - mCurrentMaxAcquiredBufferCount) : 0;
Robert Carr405e2f62021-12-31 16:59:34 -0800442
443 auto rb = ReleasedBuffer{id, releaseFence};
444 if (std::find(mPendingRelease.begin(), mPendingRelease.end(), rb) == mPendingRelease.end()) {
445 mPendingRelease.emplace_back(rb);
Vishnu Nair28fe2e62022-11-01 14:29:10 -0700446 if (fakeRelease) {
447 BQA_LOGE("Faking releaseBufferCallback from transactionCompleteCallback %" PRIu64,
448 id.framenumber);
449 BBQ_TRACE("FakeReleaseCallback");
450 }
Robert Carr405e2f62021-12-31 16:59:34 -0800451 }
Ady Abraham899dcdb2021-06-15 16:56:21 -0700452
453 // Release all buffers that are beyond the ones that we need to hold
454 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500455 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700456 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500457 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwc1cf4022022-06-03 13:32:33 -0500458 // Don't process the transactions here if mSyncedFrameNumbers is not empty. That means
459 // are still transactions that have sync buffers in them that have not been applied or
460 // dropped. Instead, let onFrameAvailable handle processing them since it will merge with
461 // the syncTransaction.
462 if (mSyncedFrameNumbers.empty()) {
chaviwd7deef72021-10-06 11:53:40 -0500463 acquireNextBufferLocked(std::nullopt);
464 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800465 }
466
Ady Abraham899dcdb2021-06-15 16:56:21 -0700467 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700468 ATRACE_INT(mQueuedBufferTrace.c_str(),
469 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800470 mCallbackCV.notify_all();
471}
472
chaviw0acd33a2021-11-02 11:55:37 -0500473void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
474 const sp<Fence>& releaseFence) {
475 auto it = mSubmitted.find(callbackId);
476 if (it == mSubmitted.end()) {
477 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
478 callbackId.to_string().c_str());
479 return;
480 }
481 mNumAcquired--;
chaviw57ae4b22022-02-03 16:51:39 -0600482 BBQ_TRACE("frame=%" PRIu64, callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500483 BQA_LOGV("released %s", callbackId.to_string().c_str());
484 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
485 mSubmitted.erase(it);
chaviwc1cf4022022-06-03 13:32:33 -0500486 // Remove the frame number from mSyncedFrameNumbers since we can get a release callback
487 // without getting a transaction committed if the buffer was dropped.
488 mSyncedFrameNumbers.erase(callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500489}
490
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000491status_t BLASTBufferQueue::acquireNextBufferLocked(
chaviwd7deef72021-10-06 11:53:40 -0500492 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800493 // If the next transaction is set, we want to guarantee the our acquire will not fail, so don't
494 // include the extra buffer when checking if we can acquire the next buffer.
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000495 if (mNumFrameAvailable == 0) {
496 BQA_LOGV("Can't process next buffer. No available frames");
497 return NOT_ENOUGH_DATA;
Valerie Haud3b90d22019-11-06 09:37:31 -0800498 }
499
Valerie Haua32c5522019-12-09 10:11:08 -0800500 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700501 BQA_LOGE("ERROR : surface control is null");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000502 return NAME_NOT_FOUND;
Valerie Haud3b90d22019-11-06 09:37:31 -0800503 }
504
Robert Carr78c25dd2019-08-15 14:10:33 -0700505 SurfaceComposerClient::Transaction localTransaction;
506 bool applyTransaction = true;
507 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500508 if (transaction) {
509 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700510 applyTransaction = false;
511 }
512
Valerie Haua32c5522019-12-09 10:11:08 -0800513 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800514
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800515 status_t status =
516 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800517 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
518 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000519 return status;
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800520 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700521 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000522 return status;
Robert Carr78c25dd2019-08-15 14:10:33 -0700523 }
chaviw57ae4b22022-02-03 16:51:39 -0600524
Valerie Haua32c5522019-12-09 10:11:08 -0800525 auto buffer = bufferItem.mGraphicBuffer;
526 mNumFrameAvailable--;
chaviw57ae4b22022-02-03 16:51:39 -0600527 BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800528
529 if (buffer == nullptr) {
530 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700531 BQA_LOGE("Buffer was empty");
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000532 return BAD_VALUE;
Valerie Haua32c5522019-12-09 10:11:08 -0800533 }
534
Vishnu Nair670b3f72020-09-29 17:52:18 -0700535 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700536 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800537 "buffer{size=%dx%d transform=%d}",
538 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
539 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
540 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000541 return acquireNextBufferLocked(transaction);
Vishnu Nair670b3f72020-09-29 17:52:18 -0700542 }
543
Valerie Haua32c5522019-12-09 10:11:08 -0800544 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700545 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
546 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
547 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700548
Valerie Hau871d6352020-01-29 08:44:02 -0800549 bool needsDisconnect = false;
550 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
551
552 // if producer disconnected before, notify SurfaceFlinger
553 if (needsDisconnect) {
554 t->notifyProducerDisconnect(mSurfaceControl);
555 }
556
Robert Carr78c25dd2019-08-15 14:10:33 -0700557 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
558 incStrong((void*)transactionCallbackThunk);
559
Vishnu Nair932f6ae2021-09-29 17:33:10 -0700560 mSize = mRequestedSize;
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700561 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000562 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
563 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700564 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800565
Vishnu Nair1506b182021-02-22 14:35:15 -0800566 auto releaseBufferCallback =
567 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
chaviw69058fb2021-09-27 09:37:30 -0500568 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
chaviwba4320c2021-09-15 15:20:53 -0500569 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
chaviw8dd181f2022-01-05 18:36:46 -0600570 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500571 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
572 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
573 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700574 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviwf2dace72021-11-17 17:36:50 -0600575
chaviw42026162021-04-16 15:46:12 -0500576 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700577
Vishnu Naird2aaab12022-02-10 14:49:09 -0800578 if (mUpdateDestinationFrame) {
579 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
580 } else {
581 const bool ignoreDestinationFrame =
582 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
583 t->setFlags(mSurfaceControl,
584 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
585 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700586 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700587 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800588 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800589 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800590 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800591 if (!bufferItem.mIsAutoTimestamp) {
592 t->setDesiredPresentTime(bufferItem.mTimestamp);
593 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700594
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800595 // Drop stale frame timeline infos
596 while (!mPendingFrameTimelines.empty() &&
597 mPendingFrameTimelines.front().first < bufferItem.mFrameNumber) {
598 ATRACE_FORMAT_INSTANT("dropping stale frameNumber: %" PRIu64 " vsyncId: %" PRId64,
599 mPendingFrameTimelines.front().first,
600 mPendingFrameTimelines.front().second.vsyncId);
601 mPendingFrameTimelines.pop();
602 }
603
604 if (!mPendingFrameTimelines.empty() &&
605 mPendingFrameTimelines.front().first == bufferItem.mFrameNumber) {
606 ATRACE_FORMAT_INSTANT("Transaction::setFrameTimelineInfo frameNumber: %" PRIu64
607 " vsyncId: %" PRId64,
608 bufferItem.mFrameNumber,
609 mPendingFrameTimelines.front().second.vsyncId);
610 t->setFrameTimelineInfo(mPendingFrameTimelines.front().second);
611 mPendingFrameTimelines.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100612 }
613
Vishnu Nairadf632b2021-01-07 14:05:08 -0800614 {
615 std::unique_lock _lock{mTimestampMutex};
616 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
617 if (dequeueTime != mDequeueTimestamps.end()) {
618 Parcel p;
619 p.writeInt64(dequeueTime->second);
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800620 t->setMetadata(mSurfaceControl, gui::METADATA_DEQUEUE_TIME, p);
Vishnu Nairadf632b2021-01-07 14:05:08 -0800621 mDequeueTimestamps.erase(dequeueTime);
622 }
623 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800624
chaviw6a195272021-09-03 16:14:25 -0500625 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700626 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800627 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
628 t->setApplyToken(mApplyToken).apply(false, true);
629 mAppliedLastTransaction = true;
630 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
631 } else {
632 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
633 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700634 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700635
chaviwd7deef72021-10-06 11:53:40 -0500636 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800637 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700638 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500639 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800640 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700641 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700642 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000643 return OK;
Robert Carr78c25dd2019-08-15 14:10:33 -0700644}
645
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800646Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
647 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800648 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800649 }
650 return item.mCrop;
651}
652
chaviwd7deef72021-10-06 11:53:40 -0500653void BLASTBufferQueue::acquireAndReleaseBuffer() {
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000654 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500655 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500656 status_t status =
657 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
658 if (status != OK) {
659 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
660 statusToString(status).c_str());
661 return;
662 }
chaviwd7deef72021-10-06 11:53:40 -0500663 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500664 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500665}
666
Vishnu Nairaef1de92020-10-22 12:15:53 -0700667void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000668 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
669 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
chaviwc1cf4022022-06-03 13:32:33 -0500670 bool waitForTransactionCallback = !mSyncedFrameNumbers.empty();
671
Tianhao Yao4861b102022-02-03 20:18:35 +0000672 {
Tianhao Yao4861b102022-02-03 20:18:35 +0000673 std::unique_lock _lock{mMutex};
Chavi Weingartend00e0f72022-07-14 15:59:20 +0000674 BBQ_TRACE();
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800675
Tianhao Yao4861b102022-02-03 20:18:35 +0000676 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
677 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800678
Tianhao Yao4861b102022-02-03 20:18:35 +0000679 if (syncTransactionSet) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000680 // If we are going to re-use the same mSyncTransaction, release the buffer that may
681 // already be set in the Transaction. This is to allow us a free slot early to continue
682 // processing a new buffer.
683 if (!mAcquireSingleBuffer) {
684 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
685 if (bufferData) {
686 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
687 bufferData->frameNumber);
688 releaseBuffer(bufferData->generateReleaseCallbackId(),
689 bufferData->acquireFence);
Tianhao Yao4861b102022-02-03 20:18:35 +0000690 }
691 }
chaviw0acd33a2021-11-02 11:55:37 -0500692
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000693 if (waitForTransactionCallback) {
694 // We are waiting on a previous sync's transaction callback so allow another sync
695 // transaction to proceed.
696 //
697 // We need to first flush out the transactions that were in between the two syncs.
698 // We do this by merging them into mSyncTransaction so any buffer merging will get
699 // a release callback invoked.
700 while (mNumFrameAvailable > 0) {
701 // flush out the shadow queue
702 acquireAndReleaseBuffer();
703 }
chaviwd7deef72021-10-06 11:53:40 -0500704 }
705 }
706
Tianhao Yao4861b102022-02-03 20:18:35 +0000707 // add to shadow queue
708 mNumFrameAvailable++;
chaviwc1cf4022022-06-03 13:32:33 -0500709 if (waitForTransactionCallback && mNumFrameAvailable >= 2) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000710 acquireAndReleaseBuffer();
711 }
712 ATRACE_INT(mQueuedBufferTrace.c_str(),
713 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
714
715 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
716 item.mFrameNumber, boolToString(syncTransactionSet));
717
718 if (syncTransactionSet) {
Chavi Weingarten3a8f19b2022-12-27 22:00:24 +0000719 // If there's no available buffer and we're in a sync transaction, we need to wait
720 // instead of returning since we guarantee a buffer will be acquired for the sync.
721 while (acquireNextBufferLocked(mSyncTransaction) == BufferQueue::NO_BUFFER_AVAILABLE) {
722 BQA_LOGD("waiting for available buffer");
723 mCallbackCV.wait(_lock);
724 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000725
726 // Only need a commit callback when syncing to ensure the buffer that's synced has been
727 // sent to SF
728 incStrong((void*)transactionCommittedCallbackThunk);
729 mSyncTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,
730 static_cast<void*>(this));
chaviwc1cf4022022-06-03 13:32:33 -0500731 mSyncedFrameNumbers.emplace(item.mFrameNumber);
Tianhao Yao4861b102022-02-03 20:18:35 +0000732 if (mAcquireSingleBuffer) {
733 prevCallback = mTransactionReadyCallback;
734 prevTransaction = mSyncTransaction;
735 mTransactionReadyCallback = nullptr;
736 mSyncTransaction = nullptr;
737 }
chaviwc1cf4022022-06-03 13:32:33 -0500738 } else if (!waitForTransactionCallback) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000739 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800740 }
741 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000742 if (prevCallback) {
743 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500744 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800745}
746
Vishnu Nairaef1de92020-10-22 12:15:53 -0700747void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
748 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
749 // Do nothing since we are not storing unacquired buffer items locally.
750}
751
Vishnu Nairadf632b2021-01-07 14:05:08 -0800752void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
753 std::unique_lock _lock{mTimestampMutex};
754 mDequeueTimestamps[bufferId] = systemTime();
755};
756
757void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
758 std::unique_lock _lock{mTimestampMutex};
759 mDequeueTimestamps.erase(bufferId);
760};
761
Tianhao Yao4861b102022-02-03 20:18:35 +0000762void BLASTBufferQueue::syncNextTransaction(
763 std::function<void(SurfaceComposerClient::Transaction*)> callback,
764 bool acquireSingleBuffer) {
chaviw57ae4b22022-02-03 16:51:39 -0600765 BBQ_TRACE();
chaviw3b4bdcf2022-03-17 09:27:03 -0500766
767 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
768 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
769
770 {
771 std::lock_guard _lock{mMutex};
772 // We're about to overwrite the previous call so we should invoke that callback
773 // immediately.
774 if (mTransactionReadyCallback) {
775 prevCallback = mTransactionReadyCallback;
776 prevTransaction = mSyncTransaction;
777 }
778
779 mTransactionReadyCallback = callback;
780 if (callback) {
781 mSyncTransaction = new SurfaceComposerClient::Transaction();
782 } else {
783 mSyncTransaction = nullptr;
784 }
785 mAcquireSingleBuffer = mTransactionReadyCallback ? acquireSingleBuffer : true;
Tianhao Yao4861b102022-02-03 20:18:35 +0000786 }
chaviw3b4bdcf2022-03-17 09:27:03 -0500787
788 if (prevCallback) {
789 prevCallback(prevTransaction);
790 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000791}
792
793void BLASTBufferQueue::stopContinuousSyncTransaction() {
794 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
795 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
796 {
797 std::lock_guard _lock{mMutex};
798 bool invokeCallback = mTransactionReadyCallback && !mAcquireSingleBuffer;
799 if (invokeCallback) {
800 prevCallback = mTransactionReadyCallback;
801 prevTransaction = mSyncTransaction;
802 }
803 mTransactionReadyCallback = nullptr;
804 mSyncTransaction = nullptr;
805 mAcquireSingleBuffer = true;
806 }
807 if (prevCallback) {
808 prevCallback(prevTransaction);
809 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700810}
811
Vishnu Nairea0de002020-11-17 17:42:37 -0800812bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700813 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
814 // Only reject buffers if scaling mode is freeze.
815 return false;
816 }
817
Vishnu Naire1a42322020-10-02 17:42:04 -0700818 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
819 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
820
821 // Take the buffer's orientation into account
822 if (item.mTransform & ui::Transform::ROT_90) {
823 std::swap(bufWidth, bufHeight);
824 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800825 ui::Size bufferSize(bufWidth, bufHeight);
826 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800827 return false;
828 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700829
Vishnu Nair670b3f72020-09-29 17:52:18 -0700830 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800831 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700832}
Vishnu Nairbf255772020-10-16 10:54:41 -0700833
Robert Carr05086b22020-10-13 18:22:51 -0700834class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700835private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700836 std::mutex mMutex;
Robert Carr9c006e02020-10-14 13:41:57 -0700837 sp<BLASTBufferQueue> mBbq;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700838 bool mDestroyed = false;
839
Robert Carr05086b22020-10-13 18:22:51 -0700840public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700841 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
842 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
843 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700844
Robert Carr05086b22020-10-13 18:22:51 -0700845 void allocateBuffers() override {
846 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
847 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
848 auto gbp = getIGraphicBufferProducer();
849 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
850 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
851 gbp->allocateBuffers(reqWidth, reqHeight,
852 reqFormat, reqUsage);
853
854 }).detach();
855 }
Robert Carr9c006e02020-10-14 13:41:57 -0700856
Marin Shalamanovc5986772021-03-16 16:09:49 +0100857 status_t setFrameRate(float frameRate, int8_t compatibility,
858 int8_t changeFrameRateStrategy) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700859 std::unique_lock _lock{mMutex};
860 if (mDestroyed) {
861 return DEAD_OBJECT;
862 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100863 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
864 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700865 return BAD_VALUE;
866 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100867 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700868 }
Robert Carr9b611b72020-10-19 12:00:23 -0700869
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800870 status_t setFrameTimelineInfo(uint64_t frameNumber,
871 const FrameTimelineInfo& frameTimelineInfo) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700872 std::unique_lock _lock{mMutex};
873 if (mDestroyed) {
874 return DEAD_OBJECT;
875 }
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800876 return mBbq->setFrameTimelineInfo(frameNumber, frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700877 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700878
879 void destroy() override {
880 Surface::destroy();
881
882 std::unique_lock _lock{mMutex};
883 mDestroyed = true;
884 mBbq = nullptr;
885 }
Robert Carr05086b22020-10-13 18:22:51 -0700886};
887
Robert Carr9c006e02020-10-14 13:41:57 -0700888// TODO: Can we coalesce this with frame updates? Need to confirm
889// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200890status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
891 bool shouldBeSeamless) {
Robert Carr9c006e02020-10-14 13:41:57 -0700892 std::unique_lock _lock{mMutex};
893 SurfaceComposerClient::Transaction t;
894
Marin Shalamanov46084422020-10-13 12:33:42 +0200895 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700896}
897
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800898status_t BLASTBufferQueue::setFrameTimelineInfo(uint64_t frameNumber,
899 const FrameTimelineInfo& frameTimelineInfo) {
900 ATRACE_FORMAT("%s(%s) frameNumber: %" PRIu64 " vsyncId: %" PRId64, __func__, mName.c_str(),
901 frameNumber, frameTimelineInfo.vsyncId);
Robert Carr9b611b72020-10-19 12:00:23 -0700902 std::unique_lock _lock{mMutex};
Ady Abrahamd6e409e2023-01-19 16:07:31 -0800903 mPendingFrameTimelines.push({frameNumber, frameTimelineInfo});
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100904 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700905}
906
Hongguang Chen621ec582021-02-16 15:42:35 -0800907void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
908 std::unique_lock _lock{mMutex};
909 SurfaceComposerClient::Transaction t;
910
911 t.setSidebandStream(mSurfaceControl, stream).apply();
912}
913
Vishnu Nair992496b2020-10-22 17:27:21 -0700914sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
915 std::unique_lock _lock{mMutex};
916 sp<IBinder> scHandle = nullptr;
917 if (includeSurfaceControlHandle && mSurfaceControl) {
918 scHandle = mSurfaceControl->getHandle();
919 }
920 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700921}
922
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800923void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
924 uint64_t frameNumber) {
925 std::lock_guard _lock{mMutex};
926 if (mLastAcquiredFrameNumber >= frameNumber) {
927 // Apply the transaction since we have already acquired the desired frame.
928 t->apply();
929 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500930 mPendingTransactions.emplace_back(frameNumber, *t);
931 // Clear the transaction so it can't be applied elsewhere.
932 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800933 }
934}
935
chaviw6a195272021-09-03 16:14:25 -0500936void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
937 std::lock_guard _lock{mMutex};
938
939 SurfaceComposerClient::Transaction t;
940 mergePendingTransactions(&t, frameNumber);
Robert Carr79dc06a2022-02-22 15:28:59 -0800941 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
942 t.setApplyToken(mApplyToken).apply(false, true);
chaviw6a195272021-09-03 16:14:25 -0500943}
944
945void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
946 uint64_t frameNumber) {
947 auto mergeTransaction =
948 [&t, currentFrameNumber = frameNumber](
949 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
950 auto& [targetFrameNumber, transaction] = pendingTransaction;
951 if (currentFrameNumber < targetFrameNumber) {
952 return false;
953 }
954 t->merge(std::move(transaction));
955 return true;
956 };
957
958 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
959 mPendingTransactions.end(), mergeTransaction),
960 mPendingTransactions.end());
961}
962
chaviwd84085a2022-02-08 11:07:04 -0600963SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
964 uint64_t frameNumber) {
965 std::lock_guard _lock{mMutex};
966 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
967 mergePendingTransactions(t, frameNumber);
968 return t;
969}
970
Vishnu Nair89496122020-12-14 17:14:53 -0800971// Maintains a single worker thread per process that services a list of runnables.
972class AsyncWorker : public Singleton<AsyncWorker> {
973private:
974 std::thread mThread;
975 bool mDone = false;
976 std::deque<std::function<void()>> mRunnables;
977 std::mutex mMutex;
978 std::condition_variable mCv;
979 void run() {
980 std::unique_lock<std::mutex> lock(mMutex);
981 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -0800982 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700983 std::deque<std::function<void()>> runnables = std::move(mRunnables);
984 mRunnables.clear();
985 lock.unlock();
986 // Run outside the lock since the runnable might trigger another
987 // post to the async worker.
988 execute(runnables);
989 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -0800990 }
Wonsik Kim567533e2021-05-04 19:31:29 -0700991 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -0800992 }
993 }
994
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700995 void execute(std::deque<std::function<void()>>& runnables) {
996 while (!runnables.empty()) {
997 std::function<void()> runnable = runnables.front();
998 runnables.pop_front();
999 runnable();
1000 }
1001 }
1002
Vishnu Nair89496122020-12-14 17:14:53 -08001003public:
1004 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
1005
1006 ~AsyncWorker() {
1007 mDone = true;
1008 mCv.notify_all();
1009 if (mThread.joinable()) {
1010 mThread.join();
1011 }
1012 }
1013
1014 void post(std::function<void()> runnable) {
1015 std::unique_lock<std::mutex> lock(mMutex);
1016 mRunnables.emplace_back(std::move(runnable));
1017 mCv.notify_one();
1018 }
1019};
1020ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
1021
1022// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
1023class AsyncProducerListener : public BnProducerListener {
1024private:
1025 const sp<IProducerListener> mListener;
1026
1027public:
1028 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
1029
1030 void onBufferReleased() override {
1031 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
1032 }
1033
1034 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
1035 AsyncWorker::getInstance().post(
1036 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
1037 }
1038};
1039
1040// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
1041// can be non-blocking when the producer is in the client process.
1042class BBQBufferQueueProducer : public BufferQueueProducer {
1043public:
Brian Lindahl957985b2023-01-31 15:42:47 -07001044 BBQBufferQueueProducer(const sp<BufferQueueCore>& core, wp<BLASTBufferQueue> bbq)
1045 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/),
1046 mBLASTBufferQueue(std::move(bbq)) {}
Vishnu Nair89496122020-12-14 17:14:53 -08001047
1048 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
1049 QueueBufferOutput* output) override {
1050 if (!listener) {
1051 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
1052 }
1053
1054 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
1055 producerControlledByApp, output);
1056 }
Vishnu Nair17dde612020-12-28 11:39:59 -08001057
Brian Lindahl957985b2023-01-31 15:42:47 -07001058 // We want to resize the frame history when changing the size of the buffer queue
1059 status_t setMaxDequeuedBufferCount(int maxDequeuedBufferCount) override {
1060 int maxBufferCount;
1061 status_t status = BufferQueueProducer::setMaxDequeuedBufferCount(maxDequeuedBufferCount,
1062 &maxBufferCount);
1063 // if we can't determine the max buffer count, then just skip growing the history size
1064 if (status == OK) {
1065 size_t newFrameHistorySize = maxBufferCount + 2; // +2 because triple buffer rendering
1066 // optimize away resizing the frame history unless it will grow
1067 if (newFrameHistorySize > FrameEventHistory::INITIAL_MAX_FRAME_HISTORY) {
1068 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
1069 if (bbq != nullptr) {
1070 ALOGV("increasing frame history size to %zu", newFrameHistorySize);
1071 bbq->resizeFrameEventHistory(newFrameHistorySize);
1072 }
1073 }
1074 }
1075 return status;
1076 }
1077
Vishnu Nair17dde612020-12-28 11:39:59 -08001078 int query(int what, int* value) override {
1079 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
1080 *value = 1;
1081 return NO_ERROR;
1082 }
1083 return BufferQueueProducer::query(what, value);
1084 }
Brian Lindahl957985b2023-01-31 15:42:47 -07001085
1086private:
1087 const wp<BLASTBufferQueue> mBLASTBufferQueue;
Vishnu Nair89496122020-12-14 17:14:53 -08001088};
1089
1090// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
1091// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
1092// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
1093// we can deadlock.
1094void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
1095 sp<IGraphicBufferConsumer>* outConsumer) {
1096 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
1097 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
1098
1099 sp<BufferQueueCore> core(new BufferQueueCore());
1100 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
1101
Brian Lindahl957985b2023-01-31 15:42:47 -07001102 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core, this));
Vishnu Nair89496122020-12-14 17:14:53 -08001103 LOG_ALWAYS_FATAL_IF(producer == nullptr,
1104 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
1105
Vishnu Nair8b30dd12021-01-25 14:16:54 -08001106 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
1107 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -08001108 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
1109 "BLASTBufferQueue: failed to create BufferQueueConsumer");
1110
1111 *outProducer = producer;
1112 *outConsumer = consumer;
1113}
1114
Brian Lindahl957985b2023-01-31 15:42:47 -07001115void BLASTBufferQueue::resizeFrameEventHistory(size_t newSize) {
1116 // This can be null during creation of the buffer queue, but resizing won't do anything at that
1117 // point in time, so just ignore. This can go away once the class relationships and lifetimes of
1118 // objects are cleaned up with a major refactor of BufferQueue as a whole.
1119 if (mBufferItemConsumer != nullptr) {
1120 std::unique_lock _lock{mMutex};
1121 mBufferItemConsumer->resizeFrameEventHistory(newSize);
1122 }
1123}
1124
chaviw497e81c2021-02-04 17:09:47 -08001125PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
1126 PixelFormat convertedFormat = format;
1127 switch (format) {
1128 case PIXEL_FORMAT_TRANSPARENT:
1129 case PIXEL_FORMAT_TRANSLUCENT:
1130 convertedFormat = PIXEL_FORMAT_RGBA_8888;
1131 break;
1132 case PIXEL_FORMAT_OPAQUE:
1133 convertedFormat = PIXEL_FORMAT_RGBX_8888;
1134 break;
1135 }
1136 return convertedFormat;
1137}
1138
Robert Carr82d07c92021-05-10 11:36:43 -07001139uint32_t BLASTBufferQueue::getLastTransformHint() const {
1140 if (mSurfaceControl != nullptr) {
1141 return mSurfaceControl->getTransformHint();
1142 } else {
1143 return 0;
1144 }
1145}
1146
chaviw0b020f82021-08-20 12:00:47 -05001147uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
1148 std::unique_lock _lock{mMutex};
1149 return mLastAcquiredFrameNumber;
1150}
1151
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001152bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
1153 std::unique_lock _lock{mMutex};
1154 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1155}
1156
Patrick Williamsf1e5df12022-10-17 21:37:42 +00001157void BLASTBufferQueue::setTransactionHangCallback(
1158 std::function<void(const std::string&)> callback) {
Robert Carr4c1b6462021-12-21 10:30:50 -08001159 std::unique_lock _lock{mMutex};
1160 mTransactionHangCallback = callback;
1161}
1162
Robert Carr78c25dd2019-08-15 14:10:33 -07001163} // namespace android