blob: 2104c772752783485780c01981cd84c708304906 [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>
Vishnu Nair89496122020-12-14 17:14:53 -080031#include <utils/Singleton.h>
Valerie Haua32c5522019-12-09 10:11:08 -080032#include <utils/Trace.h>
33
Ady Abraham0bde6b52021-05-18 13:57:02 -070034#include <private/gui/ComposerService.h>
35
Robert Carr78c25dd2019-08-15 14:10:33 -070036#include <chrono>
37
38using namespace std::chrono_literals;
39
Vishnu Nairdab94092020-09-29 16:09:04 -070040namespace {
chaviw3277faf2021-05-19 16:45:23 -050041inline const char* boolToString(bool b) {
Vishnu Nairdab94092020-09-29 16:09:04 -070042 return b ? "true" : "false";
43}
44} // namespace
45
Robert Carr78c25dd2019-08-15 14:10:33 -070046namespace android {
47
Vishnu Nairdab94092020-09-29 16:09:04 -070048// Macros to include adapter info in log messages
chaviw2d2150e2021-10-06 11:53:40 -050049#define BQA_LOGD(x, ...) \
50 ALOGD("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070051#define BQA_LOGV(x, ...) \
52 ALOGV("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairc6f89ee2020-12-11 14:27:32 -080053// enable logs for a single layer
54//#define BQA_LOGV(x, ...) \
55// ALOGV_IF((strstr(mName.c_str(), "SurfaceView") != nullptr), "[%s](f:%u,a:%u) " x, \
56// mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070057#define BQA_LOGE(x, ...) \
58 ALOGE("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
59
Valerie Hau871d6352020-01-29 08:44:02 -080060void BLASTBufferItemConsumer::onDisconnect() {
Hongguang Chen621ec582021-02-16 15:42:35 -080061 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080062 mPreviouslyConnected = mCurrentlyConnected;
63 mCurrentlyConnected = false;
64 if (mPreviouslyConnected) {
65 mDisconnectEvents.push(mCurrentFrameNumber);
66 }
67 mFrameEventHistory.onDisconnect();
68}
69
70void BLASTBufferItemConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
71 FrameEventHistoryDelta* outDelta) {
Hongguang Chen621ec582021-02-16 15:42:35 -080072 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080073 if (newTimestamps) {
74 // BufferQueueProducer only adds a new timestamp on
75 // queueBuffer
76 mCurrentFrameNumber = newTimestamps->frameNumber;
77 mFrameEventHistory.addQueue(*newTimestamps);
78 }
79 if (outDelta) {
80 // frame event histories will be processed
81 // only after the producer connects and requests
82 // deltas for the first time. Forward this intent
83 // to SF-side to turn event processing back on
84 mPreviouslyConnected = mCurrentlyConnected;
85 mCurrentlyConnected = true;
86 mFrameEventHistory.getAndResetDelta(outDelta);
87 }
88}
89
90void BLASTBufferItemConsumer::updateFrameTimestamps(uint64_t frameNumber, nsecs_t refreshStartTime,
91 const sp<Fence>& glDoneFence,
92 const sp<Fence>& presentFence,
93 const sp<Fence>& prevReleaseFence,
94 CompositorTiming compositorTiming,
95 nsecs_t latchTime, nsecs_t dequeueReadyTime) {
Hongguang Chen621ec582021-02-16 15:42:35 -080096 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080097
98 // if the producer is not connected, don't bother updating,
99 // the next producer that connects won't access this frame event
100 if (!mCurrentlyConnected) return;
101 std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
102 std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
103 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
104
105 mFrameEventHistory.addLatch(frameNumber, latchTime);
106 mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
107 mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
108 mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
109 compositorTiming);
110}
111
112void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
113 bool disconnect = false;
Hongguang Chen621ec582021-02-16 15:42:35 -0800114 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800115 while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
116 disconnect = true;
117 mDisconnectEvents.pop();
118 }
119 if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
120}
121
Hongguang Chen621ec582021-02-16 15:42:35 -0800122void BLASTBufferItemConsumer::setBlastBufferQueue(BLASTBufferQueue* blastbufferqueue) {
Alec Mouri5c8b18c2021-08-19 16:52:34 -0700123 std::scoped_lock lock(mBufferQueueMutex);
Hongguang Chen621ec582021-02-16 15:42:35 -0800124 mBLASTBufferQueue = blastbufferqueue;
125}
126
127void BLASTBufferItemConsumer::onSidebandStreamChanged() {
Alec Mouri5c8b18c2021-08-19 16:52:34 -0700128 std::scoped_lock lock(mBufferQueueMutex);
Hongguang Chen621ec582021-02-16 15:42:35 -0800129 if (mBLASTBufferQueue != nullptr) {
130 sp<NativeHandle> stream = getSidebandStream();
131 mBLASTBufferQueue->setSidebandStream(stream);
132 }
133}
134
Vishnu Nair22b6d232021-12-06 16:45:48 -0800135BLASTBufferQueue::BLASTBufferQueue(const std::string& name)
136 : mSurfaceControl(nullptr),
137 mSize(1, 1),
Vishnu Nairea0de002020-11-17 17:42:37 -0800138 mRequestedSize(mSize),
Vishnu Nair22b6d232021-12-06 16:45:48 -0800139 mFormat(PIXEL_FORMAT_RGBA_8888),
Valerie Haud3b90d22019-11-06 09:37:31 -0800140 mNextTransaction(nullptr) {
Vishnu Nair89496122020-12-14 17:14:53 -0800141 createBufferQueue(&mProducer, &mConsumer);
Valerie Hau0889c622020-02-19 15:04:47 -0800142 // since the adapter is in the client process, set dequeue timeout
143 // explicitly so that dequeueBuffer will block
144 mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
Valerie Hau65b8e872020-02-13 09:45:14 -0800145
Vishnu Nairdebd1cb2021-03-16 10:06:01 -0700146 // safe default, most producers are expected to override this
147 mProducer->setMaxDequeuedBufferCount(2);
Vishnu Nair1618c672021-02-05 13:08:26 -0800148 mBufferItemConsumer = new BLASTBufferItemConsumer(mConsumer,
149 GraphicBuffer::USAGE_HW_COMPOSER |
150 GraphicBuffer::USAGE_HW_TEXTURE,
151 1, false);
Valerie Haua32c5522019-12-09 10:11:08 -0800152 static int32_t id = 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700153 mName = name + "#" + std::to_string(id);
Vishnu Nairdab94092020-09-29 16:09:04 -0700154 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(id);
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700155 mQueuedBufferTrace = "QueuedBuffer - " + mName + "BLAST#" + std::to_string(id);
Valerie Haua32c5522019-12-09 10:11:08 -0800156 id++;
Vishnu Nairdab94092020-09-29 16:09:04 -0700157 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700158 mBufferItemConsumer->setFrameAvailableListener(this);
159 mBufferItemConsumer->setBufferFreedListener(this);
Hongguang Chen621ec582021-02-16 15:42:35 -0800160 mBufferItemConsumer->setBlastBufferQueue(this);
Robert Carr9f133d72020-04-01 15:51:46 -0700161
Ady Abraham899dcdb2021-06-15 16:56:21 -0700162 ComposerService::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);
Ady Abraham0bde6b52021-05-18 13:57:02 -0700163 mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
Valerie Haua32c5522019-12-09 10:11:08 -0800164 mNumAcquired = 0;
165 mNumFrameAvailable = 0;
Vishnu Nair22b6d232021-12-06 16:45:48 -0800166 BQA_LOGV("BLASTBufferQueue created");
167}
168
169BLASTBufferQueue::BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface,
170 int width, int height, int32_t format)
171 : BLASTBufferQueue(name) {
172 update(surface, width, height, format);
Robert Carr78c25dd2019-08-15 14:10:33 -0700173}
174
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800175BLASTBufferQueue::~BLASTBufferQueue() {
Hongguang Chen621ec582021-02-16 15:42:35 -0800176 mBufferItemConsumer->setBlastBufferQueue(nullptr);
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800177 if (mPendingTransactions.empty()) {
178 return;
179 }
180 BQA_LOGE("Applying pending transactions on dtor %d",
181 static_cast<uint32_t>(mPendingTransactions.size()));
182 SurfaceComposerClient::Transaction t;
183 for (auto& [targetFrameNumber, transaction] : mPendingTransactions) {
184 t.merge(std::move(transaction));
185 }
186 t.apply();
187}
188
chaviw565ee542021-01-14 10:21:23 -0800189void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Nair084514a2021-07-30 16:07:42 -0700190 int32_t format, SurfaceComposerClient::Transaction* outTransaction) {
Robert Carr78c25dd2019-08-15 14:10:33 -0700191 std::unique_lock _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800192 if (mFormat != format) {
193 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800194 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800195 }
196
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800197 SurfaceComposerClient::Transaction t;
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700198 const bool setBackpressureFlag = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800199 bool applyTransaction = false;
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800200
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700201 // Always update the native object even though they might have the same layer handle, so we can
202 // get the updated transform hint from WM.
203 mSurfaceControl = surface;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800204 if (mSurfaceControl != nullptr) {
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700205 if (setBackpressureFlag) {
206 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
207 layer_state_t::eEnableBackpressure);
208 applyTransaction = true;
209 }
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800210 mTransformHint = mSurfaceControl->getTransformHint();
211 mBufferItemConsumer->setTransformHint(mTransformHint);
212 }
Vishnu Naira4fbca52021-07-07 16:52:34 -0700213 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
214 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800215
Vishnu Nairea0de002020-11-17 17:42:37 -0800216 ui::Size newSize(width, height);
217 if (mRequestedSize != newSize) {
218 mRequestedSize.set(newSize);
219 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000220 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800221 // If the buffer supports scaling, update the frame immediately since the client may
222 // want to scale the existing buffer to the new size.
223 mSize = mRequestedSize;
Vishnu Nair084514a2021-07-30 16:07:42 -0700224 SurfaceComposerClient::Transaction* destFrameTransaction =
225 (outTransaction) ? outTransaction : &t;
Vishnu Nair22b6d232021-12-06 16:45:48 -0800226 if (mSurfaceControl != nullptr) {
Vishnu Nair084514a2021-07-30 16:07:42 -0700227 destFrameTransaction->setDestinationFrame(mSurfaceControl,
228 Rect(0, 0, newSize.getWidth(),
229 newSize.getHeight()));
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000230 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800231 applyTransaction = true;
Vishnu Nair53c936c2020-12-03 11:46:37 -0800232 }
Robert Carrfc416512020-04-02 12:32:44 -0700233 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800234 if (applyTransaction) {
Vishnu Nair084514a2021-07-30 16:07:42 -0700235 t.setApplyToken(mApplyToken).apply();
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800236 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700237}
238
chaviw2d2150e2021-10-06 11:53:40 -0500239static std::optional<SurfaceControlStats> findMatchingStat(
240 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
241 for (auto stat : stats) {
242 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
243 return stat;
244 }
245 }
246 return std::nullopt;
247}
248
249static void transactionCommittedCallbackThunk(void* context, nsecs_t latchTime,
250 const sp<Fence>& presentFence,
251 const std::vector<SurfaceControlStats>& stats) {
252 if (context == nullptr) {
253 return;
254 }
255 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
256 bq->transactionCommittedCallback(latchTime, presentFence, stats);
257}
258
259void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
260 const sp<Fence>& /*presentFence*/,
261 const std::vector<SurfaceControlStats>& stats) {
262 {
263 std::unique_lock _lock{mMutex};
264 ATRACE_CALL();
265 BQA_LOGV("transactionCommittedCallback");
266 if (!mSurfaceControlsWithPendingCallback.empty()) {
267 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
268 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
269 if (stat) {
270 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
271
272 // We need to check if we were waiting for a transaction callback in order to
273 // process any pending buffers and unblock. It's possible to get transaction
274 // callbacks for previous requests so we need to ensure the frame from this
275 // transaction callback matches the last acquired buffer. Since acquireNextBuffer
276 // will stop processing buffers when mWaitForTransactionCallback is set, we know
277 // that mLastAcquiredFrameNumber is the frame we're waiting on.
278 // We also want to check if mNextTransaction is null because it's possible another
279 // sync request came in while waiting, but it hasn't started processing yet. In that
280 // case, we don't actually want to flush the frames in between since they will get
281 // processed and merged with the sync transaction and released earlier than if they
282 // were sent to SF
283 if (mWaitForTransactionCallback && mNextTransaction == nullptr &&
284 currFrameNumber >= mLastAcquiredFrameNumber) {
285 mWaitForTransactionCallback = false;
286 flushShadowQueueLocked();
287 }
288 } else {
chaviwa840a122021-11-01 09:50:57 -0500289 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviw2d2150e2021-10-06 11:53:40 -0500290 }
291 } else {
292 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
293 "empty.");
294 }
295
296 decStrong((void*)transactionCommittedCallbackThunk);
297 }
298}
299
Robert Carr78c25dd2019-08-15 14:10:33 -0700300static void transactionCallbackThunk(void* context, nsecs_t latchTime,
301 const sp<Fence>& presentFence,
302 const std::vector<SurfaceControlStats>& stats) {
303 if (context == nullptr) {
304 return;
305 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800306 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700307 bq->transactionCallback(latchTime, presentFence, stats);
308}
309
310void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
311 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700312 std::function<void(int64_t)> transactionCompleteCallback = nullptr;
313 uint64_t currFrameNumber = 0;
Vishnu Nairdab94092020-09-29 16:09:04 -0700314
chaviw71c2cc42020-10-23 16:42:02 -0700315 {
316 std::unique_lock _lock{mMutex};
317 ATRACE_CALL();
318 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700319
chaviw42026162021-04-16 15:46:12 -0500320 if (!mSurfaceControlsWithPendingCallback.empty()) {
321 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
322 mSurfaceControlsWithPendingCallback.pop();
chaviw2d2150e2021-10-06 11:53:40 -0500323 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
324 if (statsOptional) {
325 SurfaceControlStats stat = *statsOptional;
chaviw42026162021-04-16 15:46:12 -0500326 mTransformHint = stat.transformHint;
327 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700328 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
Vishnu Nairde66dc72021-06-17 17:54:41 -0700329 // Update frametime stamps if the frame was latched and presented, indicated by a
330 // valid latch time.
331 if (stat.latchTime > 0) {
332 mBufferItemConsumer
333 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
334 stat.frameEventStats.refreshStartTime,
335 stat.frameEventStats.gpuCompositionDoneFence,
336 stat.presentFence, stat.previousReleaseFence,
337 stat.frameEventStats.compositorTiming,
338 stat.latchTime,
339 stat.frameEventStats.dequeueReadyTime);
340 }
chaviw42026162021-04-16 15:46:12 -0500341 currFrameNumber = stat.frameEventStats.frameNumber;
342
343 if (mTransactionCompleteCallback &&
344 currFrameNumber >= mTransactionCompleteFrameNumber) {
345 if (currFrameNumber > mTransactionCompleteFrameNumber) {
346 BQA_LOGE("transactionCallback received for a newer framenumber=%" PRIu64
347 " than expected=%" PRIu64,
348 currFrameNumber, mTransactionCompleteFrameNumber);
349 }
350 transactionCompleteCallback = std::move(mTransactionCompleteCallback);
351 mTransactionCompleteFrameNumber = 0;
352 }
Robert Carraca25f62021-12-31 16:59:34 -0800353 std::vector<ReleaseCallbackId> staleReleases;
354 for (const auto& [key, value]: mSubmitted) {
355 if (currFrameNumber > key.framenumber) {
356 staleReleases.push_back(key);
357 }
358 }
359 for (const auto& staleRelease : staleReleases) {
360 releaseBufferCallbackLocked(staleRelease, stat.previousReleaseFence ? stat.previousReleaseFence : Fence::NO_FENCE,
361 stat.transformHint, stat.currentMaxAcquiredBufferCount);
362 }
chaviw2d2150e2021-10-06 11:53:40 -0500363 } else {
chaviwa840a122021-11-01 09:50:57 -0500364 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500365 }
366 } else {
367 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
368 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800369 }
chaviw71c2cc42020-10-23 16:42:02 -0700370
Robert Carraca25f62021-12-31 16:59:34 -0800371
chaviw71c2cc42020-10-23 16:42:02 -0700372 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700373 }
Valerie Haua32c5522019-12-09 10:11:08 -0800374
chaviw71c2cc42020-10-23 16:42:02 -0700375 if (transactionCompleteCallback) {
376 transactionCompleteCallback(currFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800377 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700378}
379
Vishnu Nair1506b182021-02-22 14:35:15 -0800380// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
381// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
382// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
383// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700384static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700385 const sp<Fence>& releaseFence, uint32_t transformHint,
386 uint32_t currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800387 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800388 if (blastBufferQueue) {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700389 blastBufferQueue->releaseBufferCallback(id, releaseFence, transformHint,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700390 currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700391 } else {
392 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800393 }
394}
395
chaviw2d2150e2021-10-06 11:53:40 -0500396void BLASTBufferQueue::flushShadowQueueLocked() {
397 BQA_LOGV("flushShadowQueueLocked");
398 int numFramesToFlush = mNumFrameAvailable;
399 while (numFramesToFlush > 0) {
400 acquireNextBufferLocked(std::nullopt);
401 numFramesToFlush--;
402 }
403}
404
405void BLASTBufferQueue::flushShadowQueue() {
406 std::unique_lock _lock{mMutex};
407 flushShadowQueueLocked();
408}
409
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700410void BLASTBufferQueue::releaseBufferCallback(const ReleaseCallbackId& id,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700411 const sp<Fence>& releaseFence, uint32_t transformHint,
412 uint32_t currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800413 std::unique_lock _lock{mMutex};
Robert Carraca25f62021-12-31 16:59:34 -0800414 releaseBufferCallbackLocked(id, releaseFence, transformHint, currentMaxAcquiredBufferCount);
415}
416
417void BLASTBufferQueue::releaseBufferCallbackLocked(const ReleaseCallbackId& id,
418 const sp<Fence>& releaseFence, uint32_t transformHint,
419 uint32_t currentMaxAcquiredBufferCount) {
420 ATRACE_CALL();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700421 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800422
Robert Carr82d07c92021-05-10 11:36:43 -0700423 if (mSurfaceControl != nullptr) {
Robert Carr97e7cc02021-06-07 10:45:40 -0700424 mTransformHint = transformHint;
425 mSurfaceControl->setTransformHint(transformHint);
Robert Carr82d07c92021-05-10 11:36:43 -0700426 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700427 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
Robert Carr82d07c92021-05-10 11:36:43 -0700428 }
429
Ady Abraham899dcdb2021-06-15 16:56:21 -0700430 // Calculate how many buffers we need to hold before we release them back
431 // to the buffer queue. This will prevent higher latency when we are running
432 // on a lower refresh rate than the max supported. We only do that for EGL
433 // clients as others don't care about latency
434 const bool isEGL = [&] {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700435 const auto it = mSubmitted.find(id);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700436 return it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
437 }();
438
439 const auto numPendingBuffersToHold =
440 isEGL ? std::max(0u, mMaxAcquiredBuffers - currentMaxAcquiredBufferCount) : 0;
Robert Carraca25f62021-12-31 16:59:34 -0800441 auto rb = ReleasedBuffer{id, releaseFence};
442 if (std::find(mPendingRelease.begin(), mPendingRelease.end(), rb) == mPendingRelease.end()) {
443 mPendingRelease.emplace_back(rb);
444 }
Ady Abraham899dcdb2021-06-15 16:56:21 -0700445
446 // Release all buffers that are beyond the ones that we need to hold
447 while (mPendingRelease.size() > numPendingBuffersToHold) {
448 const auto releaseBuffer = mPendingRelease.front();
449 mPendingRelease.pop_front();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700450 auto it = mSubmitted.find(releaseBuffer.callbackId);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700451 if (it == mSubmitted.end()) {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700452 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
453 releaseBuffer.callbackId.to_string().c_str());
Ady Abraham899dcdb2021-06-15 16:56:21 -0700454 return;
455 }
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700456 mNumAcquired--;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700457 BQA_LOGV("released %s", id.to_string().c_str());
Ady Abraham899dcdb2021-06-15 16:56:21 -0700458 mBufferItemConsumer->releaseBuffer(it->second, releaseBuffer.releaseFence);
459 mSubmitted.erase(it);
chaviw2d2150e2021-10-06 11:53:40 -0500460 // Don't process the transactions here if mWaitForTransactionCallback is set. Instead, let
461 // onFrameAvailable handle processing them since it will merge with the nextTransaction.
462 if (!mWaitForTransactionCallback) {
463 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
chaviw2d2150e2021-10-06 11:53:40 -0500473void BLASTBufferQueue::acquireNextBufferLocked(
474 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Valerie Haua32c5522019-12-09 10:11:08 -0800475 ATRACE_CALL();
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800476 // If the next transaction is set, we want to guarantee the our acquire will not fail, so don't
477 // include the extra buffer when checking if we can acquire the next buffer.
chaviw2d2150e2021-10-06 11:53:40 -0500478 const bool includeExtraAcquire = !transaction;
479 const bool maxAcquired = maxBuffersAcquired(includeExtraAcquire);
480 if (mNumFrameAvailable == 0 || maxAcquired) {
481 BQA_LOGV("Can't process next buffer maxBuffersAcquired=%s", boolToString(maxAcquired));
Valerie Haud3b90d22019-11-06 09:37:31 -0800482 return;
483 }
484
Valerie Haua32c5522019-12-09 10:11:08 -0800485 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700486 BQA_LOGE("ERROR : surface control is null");
Valerie Haud3b90d22019-11-06 09:37:31 -0800487 return;
488 }
489
Robert Carr78c25dd2019-08-15 14:10:33 -0700490 SurfaceComposerClient::Transaction localTransaction;
491 bool applyTransaction = true;
492 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviw2d2150e2021-10-06 11:53:40 -0500493 if (transaction) {
494 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700495 applyTransaction = false;
496 }
497
Valerie Haua32c5522019-12-09 10:11:08 -0800498 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800499
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800500 status_t status =
501 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800502 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
503 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
504 return;
505 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700506 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Robert Carr78c25dd2019-08-15 14:10:33 -0700507 return;
508 }
Valerie Haua32c5522019-12-09 10:11:08 -0800509 auto buffer = bufferItem.mGraphicBuffer;
510 mNumFrameAvailable--;
511
512 if (buffer == nullptr) {
513 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700514 BQA_LOGE("Buffer was empty");
Valerie Haua32c5522019-12-09 10:11:08 -0800515 return;
516 }
517
Vishnu Nair670b3f72020-09-29 17:52:18 -0700518 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700519 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800520 "buffer{size=%dx%d transform=%d}",
521 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
522 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
523 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
chaviw2d2150e2021-10-06 11:53:40 -0500524 acquireNextBufferLocked(transaction);
Vishnu Nairea0de002020-11-17 17:42:37 -0800525 return;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700526 }
527
Valerie Haua32c5522019-12-09 10:11:08 -0800528 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700529 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
530 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
531 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700532
Valerie Hau871d6352020-01-29 08:44:02 -0800533 bool needsDisconnect = false;
534 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
535
536 // if producer disconnected before, notify SurfaceFlinger
537 if (needsDisconnect) {
538 t->notifyProducerDisconnect(mSurfaceControl);
539 }
540
Robert Carr78c25dd2019-08-15 14:10:33 -0700541 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
542 incStrong((void*)transactionCallbackThunk);
543
Vishnu Nair22b6d232021-12-06 16:45:48 -0800544 const bool updateDestinationFrame = mRequestedSize != mSize;
Vishnu Nair932f6ae2021-09-29 17:33:10 -0700545 mSize = mRequestedSize;
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700546 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000547 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
548 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700549 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800550
Vishnu Nair1506b182021-02-22 14:35:15 -0800551 auto releaseBufferCallback =
552 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700553 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
554 std::placeholders::_4);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700555 t->setBuffer(mSurfaceControl, buffer, releaseCallbackId, releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500556 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
557 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
558 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700559 t->setAcquireFence(mSurfaceControl,
Valerie Haua32c5522019-12-09 10:11:08 -0800560 bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE);
Robert Carr78c25dd2019-08-15 14:10:33 -0700561 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviw9d12adc2021-11-17 17:36:50 -0600562
chaviw42026162021-04-16 15:46:12 -0500563 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700564
Vishnu Nair084514a2021-07-30 16:07:42 -0700565 if (updateDestinationFrame) {
566 t->setDestinationFrame(mSurfaceControl, Rect(0, 0, mSize.getWidth(), mSize.getHeight()));
567 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700568 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800569 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800570 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800571 if (!bufferItem.mIsAutoTimestamp) {
572 t->setDesiredPresentTime(bufferItem.mTimestamp);
573 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -0700574 t->setFrameNumber(mSurfaceControl, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700575
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000576 if (!mNextFrameTimelineInfoQueue.empty()) {
Ady Abraham8db10102021-03-15 17:19:23 -0700577 t->setFrameTimelineInfo(mNextFrameTimelineInfoQueue.front());
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000578 mNextFrameTimelineInfoQueue.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100579 }
580
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800581 if (mAutoRefresh != bufferItem.mAutoRefresh) {
582 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
583 mAutoRefresh = bufferItem.mAutoRefresh;
584 }
Vishnu Nairadf632b2021-01-07 14:05:08 -0800585 {
586 std::unique_lock _lock{mTimestampMutex};
587 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
588 if (dequeueTime != mDequeueTimestamps.end()) {
589 Parcel p;
590 p.writeInt64(dequeueTime->second);
591 t->setMetadata(mSurfaceControl, METADATA_DEQUEUE_TIME, p);
592 mDequeueTimestamps.erase(dequeueTime);
593 }
594 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800595
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800596 auto mergeTransaction =
597 [&t, currentFrameNumber = bufferItem.mFrameNumber](
598 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
599 auto& [targetFrameNumber, transaction] = pendingTransaction;
600 if (currentFrameNumber < targetFrameNumber) {
601 return false;
602 }
603 t->merge(std::move(transaction));
604 return true;
605 };
606
607 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
608 mPendingTransactions.end(), mergeTransaction),
609 mPendingTransactions.end());
610
Robert Carr78c25dd2019-08-15 14:10:33 -0700611 if (applyTransaction) {
Vishnu Nair277142c2021-01-05 18:35:29 -0800612 t->setApplyToken(mApplyToken).apply();
Robert Carr78c25dd2019-08-15 14:10:33 -0700613 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700614
chaviw2d2150e2021-10-06 11:53:40 -0500615 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800616 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700617 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500618 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800619 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700620 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700621 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Robert Carr78c25dd2019-08-15 14:10:33 -0700622}
623
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800624Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
625 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800626 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800627 }
628 return item.mCrop;
629}
630
chaviw2d2150e2021-10-06 11:53:40 -0500631void BLASTBufferQueue::acquireAndReleaseBuffer() {
632 BufferItem bufferItem;
chaviw8cba4ce2021-10-14 11:57:22 -0500633 status_t status =
634 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
635 if (status != OK) {
636 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
637 statusToString(status).c_str());
638 return;
639 }
chaviw2d2150e2021-10-06 11:53:40 -0500640 mNumFrameAvailable--;
chaviw8cba4ce2021-10-14 11:57:22 -0500641 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviw2d2150e2021-10-06 11:53:40 -0500642}
643
Vishnu Nairaef1de92020-10-22 12:15:53 -0700644void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Valerie Haua32c5522019-12-09 10:11:08 -0800645 ATRACE_CALL();
Valerie Hau0188adf2020-02-13 08:29:20 -0800646 std::unique_lock _lock{mMutex};
Valerie Haud3b90d22019-11-06 09:37:31 -0800647
Vishnu Nairdab94092020-09-29 16:09:04 -0700648 const bool nextTransactionSet = mNextTransaction != nullptr;
chaviw2d2150e2021-10-06 11:53:40 -0500649 BQA_LOGV("onFrameAvailable-start nextTransactionSet=%s", boolToString(nextTransactionSet));
Vishnu Nair1506b182021-02-22 14:35:15 -0800650 if (nextTransactionSet) {
chaviw2d2150e2021-10-06 11:53:40 -0500651 if (mWaitForTransactionCallback) {
652 // We are waiting on a previous sync's transaction callback so allow another sync
653 // transaction to proceed.
654 //
655 // We need to first flush out the transactions that were in between the two syncs.
656 // We do this by merging them into mNextTransaction so any buffer merging will get
657 // a release callback invoked. The release callback will be async so we need to wait
658 // on max acquired to make sure we have the capacity to acquire another buffer.
659 if (maxBuffersAcquired(false /* includeExtraAcquire */)) {
660 BQA_LOGD("waiting to flush shadow queue...");
661 mCallbackCV.wait(_lock);
662 }
663 while (mNumFrameAvailable > 0) {
664 // flush out the shadow queue
665 acquireAndReleaseBuffer();
666 }
667 }
668
669 while (maxBuffersAcquired(false /* includeExtraAcquire */)) {
670 BQA_LOGD("waiting for free buffer.");
Valerie Hau0188adf2020-02-13 08:29:20 -0800671 mCallbackCV.wait(_lock);
672 }
673 }
chaviw2d2150e2021-10-06 11:53:40 -0500674
Valerie Haud3b90d22019-11-06 09:37:31 -0800675 // add to shadow queue
Valerie Haua32c5522019-12-09 10:11:08 -0800676 mNumFrameAvailable++;
Robert Carre9323b32021-11-30 14:47:02 -0800677 if (mWaitForTransactionCallback && mNumFrameAvailable == 2) {
678 acquireAndReleaseBuffer();
679 }
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700680 ATRACE_INT(mQueuedBufferTrace.c_str(),
681 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800682
683 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " nextTransactionSet=%s", item.mFrameNumber,
chaviw3277faf2021-05-19 16:45:23 -0500684 boolToString(nextTransactionSet));
chaviw2d2150e2021-10-06 11:53:40 -0500685
686 if (nextTransactionSet) {
687 acquireNextBufferLocked(std::move(mNextTransaction));
chaviw9d12adc2021-11-17 17:36:50 -0600688
689 // Only need a commit callback when syncing to ensure the buffer that's synced has been sent
690 // to SF
691 incStrong((void*)transactionCommittedCallbackThunk);
692 mNextTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,
693 static_cast<void*>(this));
694
chaviw2d2150e2021-10-06 11:53:40 -0500695 mNextTransaction = nullptr;
696 mWaitForTransactionCallback = true;
697 } else if (!mWaitForTransactionCallback) {
698 acquireNextBufferLocked(std::nullopt);
699 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800700}
701
Vishnu Nairaef1de92020-10-22 12:15:53 -0700702void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
703 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
704 // Do nothing since we are not storing unacquired buffer items locally.
705}
706
Vishnu Nairadf632b2021-01-07 14:05:08 -0800707void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
708 std::unique_lock _lock{mTimestampMutex};
709 mDequeueTimestamps[bufferId] = systemTime();
710};
711
712void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
713 std::unique_lock _lock{mTimestampMutex};
714 mDequeueTimestamps.erase(bufferId);
715};
716
Robert Carr78c25dd2019-08-15 14:10:33 -0700717void BLASTBufferQueue::setNextTransaction(SurfaceComposerClient::Transaction* t) {
Valerie Haud3b90d22019-11-06 09:37:31 -0800718 std::lock_guard _lock{mMutex};
Robert Carr78c25dd2019-08-15 14:10:33 -0700719 mNextTransaction = t;
720}
721
Vishnu Nairea0de002020-11-17 17:42:37 -0800722bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700723 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
724 // Only reject buffers if scaling mode is freeze.
725 return false;
726 }
727
Vishnu Naire1a42322020-10-02 17:42:04 -0700728 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
729 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
730
731 // Take the buffer's orientation into account
732 if (item.mTransform & ui::Transform::ROT_90) {
733 std::swap(bufWidth, bufHeight);
734 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800735 ui::Size bufferSize(bufWidth, bufHeight);
736 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800737 return false;
738 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700739
Vishnu Nair670b3f72020-09-29 17:52:18 -0700740 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800741 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700742}
Vishnu Nairbf255772020-10-16 10:54:41 -0700743
chaviw71c2cc42020-10-23 16:42:02 -0700744void BLASTBufferQueue::setTransactionCompleteCallback(
745 uint64_t frameNumber, std::function<void(int64_t)>&& transactionCompleteCallback) {
746 std::lock_guard _lock{mMutex};
747 if (transactionCompleteCallback == nullptr) {
748 mTransactionCompleteCallback = nullptr;
749 } else {
750 mTransactionCompleteCallback = std::move(transactionCompleteCallback);
751 mTransactionCompleteFrameNumber = frameNumber;
752 }
753}
754
Vishnu Nairbf255772020-10-16 10:54:41 -0700755// Check if we have acquired the maximum number of buffers.
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800756// Consumer can acquire an additional buffer if that buffer is not droppable. Set
757// includeExtraAcquire is true to include this buffer to the count. Since this depends on the state
758// of the buffer, the next acquire may return with NO_BUFFER_AVAILABLE.
759bool BLASTBufferQueue::maxBuffersAcquired(bool includeExtraAcquire) const {
Ady Abraham0bde6b52021-05-18 13:57:02 -0700760 int maxAcquiredBuffers = mMaxAcquiredBuffers + (includeExtraAcquire ? 2 : 1);
Vishnu Nair1506b182021-02-22 14:35:15 -0800761 return mNumAcquired == maxAcquiredBuffers;
Vishnu Nairbf255772020-10-16 10:54:41 -0700762}
763
Robert Carr05086b22020-10-13 18:22:51 -0700764class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700765private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700766 std::mutex mMutex;
Robert Carr9c006e02020-10-14 13:41:57 -0700767 sp<BLASTBufferQueue> mBbq;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700768 bool mDestroyed = false;
769
Robert Carr05086b22020-10-13 18:22:51 -0700770public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700771 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
772 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
773 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700774
Robert Carr05086b22020-10-13 18:22:51 -0700775 void allocateBuffers() override {
776 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
777 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
778 auto gbp = getIGraphicBufferProducer();
779 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
780 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
781 gbp->allocateBuffers(reqWidth, reqHeight,
782 reqFormat, reqUsage);
783
784 }).detach();
785 }
Robert Carr9c006e02020-10-14 13:41:57 -0700786
Marin Shalamanovc5986772021-03-16 16:09:49 +0100787 status_t setFrameRate(float frameRate, int8_t compatibility,
788 int8_t changeFrameRateStrategy) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700789 std::unique_lock _lock{mMutex};
790 if (mDestroyed) {
791 return DEAD_OBJECT;
792 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100793 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
794 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700795 return BAD_VALUE;
796 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100797 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700798 }
Robert Carr9b611b72020-10-19 12:00:23 -0700799
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000800 status_t setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700801 std::unique_lock _lock{mMutex};
802 if (mDestroyed) {
803 return DEAD_OBJECT;
804 }
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000805 return mBbq->setFrameTimelineInfo(frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700806 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700807
808 void destroy() override {
809 Surface::destroy();
810
811 std::unique_lock _lock{mMutex};
812 mDestroyed = true;
813 mBbq = nullptr;
814 }
Robert Carr05086b22020-10-13 18:22:51 -0700815};
816
Robert Carr9c006e02020-10-14 13:41:57 -0700817// TODO: Can we coalesce this with frame updates? Need to confirm
818// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200819status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
820 bool shouldBeSeamless) {
Robert Carr9c006e02020-10-14 13:41:57 -0700821 std::unique_lock _lock{mMutex};
822 SurfaceComposerClient::Transaction t;
823
Marin Shalamanov46084422020-10-13 12:33:42 +0200824 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700825}
826
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000827status_t BLASTBufferQueue::setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) {
Robert Carr9b611b72020-10-19 12:00:23 -0700828 std::unique_lock _lock{mMutex};
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000829 mNextFrameTimelineInfoQueue.push(frameTimelineInfo);
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100830 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700831}
832
Hongguang Chen621ec582021-02-16 15:42:35 -0800833void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
834 std::unique_lock _lock{mMutex};
835 SurfaceComposerClient::Transaction t;
836
837 t.setSidebandStream(mSurfaceControl, stream).apply();
838}
839
Vishnu Nair992496b2020-10-22 17:27:21 -0700840sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
841 std::unique_lock _lock{mMutex};
842 sp<IBinder> scHandle = nullptr;
843 if (includeSurfaceControlHandle && mSurfaceControl) {
844 scHandle = mSurfaceControl->getHandle();
845 }
846 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700847}
848
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800849void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
850 uint64_t frameNumber) {
851 std::lock_guard _lock{mMutex};
852 if (mLastAcquiredFrameNumber >= frameNumber) {
853 // Apply the transaction since we have already acquired the desired frame.
854 t->apply();
855 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500856 mPendingTransactions.emplace_back(frameNumber, *t);
857 // Clear the transaction so it can't be applied elsewhere.
858 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800859 }
860}
861
Vishnu Nair89496122020-12-14 17:14:53 -0800862// Maintains a single worker thread per process that services a list of runnables.
863class AsyncWorker : public Singleton<AsyncWorker> {
864private:
865 std::thread mThread;
866 bool mDone = false;
867 std::deque<std::function<void()>> mRunnables;
868 std::mutex mMutex;
869 std::condition_variable mCv;
870 void run() {
871 std::unique_lock<std::mutex> lock(mMutex);
872 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -0800873 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700874 std::deque<std::function<void()>> runnables = std::move(mRunnables);
875 mRunnables.clear();
876 lock.unlock();
877 // Run outside the lock since the runnable might trigger another
878 // post to the async worker.
879 execute(runnables);
880 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -0800881 }
Wonsik Kim567533e2021-05-04 19:31:29 -0700882 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -0800883 }
884 }
885
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700886 void execute(std::deque<std::function<void()>>& runnables) {
887 while (!runnables.empty()) {
888 std::function<void()> runnable = runnables.front();
889 runnables.pop_front();
890 runnable();
891 }
892 }
893
Vishnu Nair89496122020-12-14 17:14:53 -0800894public:
895 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
896
897 ~AsyncWorker() {
898 mDone = true;
899 mCv.notify_all();
900 if (mThread.joinable()) {
901 mThread.join();
902 }
903 }
904
905 void post(std::function<void()> runnable) {
906 std::unique_lock<std::mutex> lock(mMutex);
907 mRunnables.emplace_back(std::move(runnable));
908 mCv.notify_one();
909 }
910};
911ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
912
913// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
914class AsyncProducerListener : public BnProducerListener {
915private:
916 const sp<IProducerListener> mListener;
917
918public:
919 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
920
921 void onBufferReleased() override {
922 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
923 }
924
925 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
926 AsyncWorker::getInstance().post(
927 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
928 }
929};
930
931// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
932// can be non-blocking when the producer is in the client process.
933class BBQBufferQueueProducer : public BufferQueueProducer {
934public:
935 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
936 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
937
938 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
939 QueueBufferOutput* output) override {
940 if (!listener) {
941 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
942 }
943
944 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
945 producerControlledByApp, output);
946 }
Vishnu Nair17dde612020-12-28 11:39:59 -0800947
948 int query(int what, int* value) override {
949 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
950 *value = 1;
951 return NO_ERROR;
952 }
953 return BufferQueueProducer::query(what, value);
954 }
Vishnu Nair89496122020-12-14 17:14:53 -0800955};
956
957// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
958// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
959// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
960// we can deadlock.
961void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
962 sp<IGraphicBufferConsumer>* outConsumer) {
963 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
964 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
965
966 sp<BufferQueueCore> core(new BufferQueueCore());
967 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
968
969 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
970 LOG_ALWAYS_FATAL_IF(producer == nullptr,
971 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
972
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800973 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
974 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -0800975 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
976 "BLASTBufferQueue: failed to create BufferQueueConsumer");
977
978 *outProducer = producer;
979 *outConsumer = consumer;
980}
981
chaviw497e81c2021-02-04 17:09:47 -0800982PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
983 PixelFormat convertedFormat = format;
984 switch (format) {
985 case PIXEL_FORMAT_TRANSPARENT:
986 case PIXEL_FORMAT_TRANSLUCENT:
987 convertedFormat = PIXEL_FORMAT_RGBA_8888;
988 break;
989 case PIXEL_FORMAT_OPAQUE:
990 convertedFormat = PIXEL_FORMAT_RGBX_8888;
991 break;
992 }
993 return convertedFormat;
994}
995
Robert Carr82d07c92021-05-10 11:36:43 -0700996uint32_t BLASTBufferQueue::getLastTransformHint() const {
997 if (mSurfaceControl != nullptr) {
998 return mSurfaceControl->getTransformHint();
999 } else {
1000 return 0;
1001 }
1002}
1003
chaviw3d8a3192021-08-20 12:00:47 -05001004uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
1005 std::unique_lock _lock{mMutex};
1006 return mLastAcquiredFrameNumber;
1007}
1008
Robert Carr78c25dd2019-08-15 14:10:33 -07001009} // namespace android